You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by xi...@apache.org on 2026/04/15 11:31:18 UTC

(pinot) branch release/1.5.0-STP-2.134.x created (now f30d306374b)

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

xiangfu pushed a change to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git


      at f30d306374b [bugfix] Clear realtime inverted index bitmaps on close (#18204)

This branch includes the following new commits:

     new 9fccc7ce08e Use BytesDeserializer for Kafka record keys to preserve binary key format (#17899)
     new 205b54a3cab Fix binary key stream decoder (#17927)
     new 833989a5dc2 Add useRawBytes config to Murmur and Murmur3 partition functions (#17932)
     new df4a370141d Fix partition function config not passed in realtime segment creation
     new 780f7a366dd Add tests for partition function config preservation in realtime segments
     new 42ce629b7c2 Migrate lz4-java from org.lz4:lz4-java 1.8.0 to at.yawk.lz4:lz4-java 1.10.4 (#18015)
     new cdc6d3a5d1c Merge pull request #472 from startreedata/lz4_failure
     new 5c33c2b475a fix: Exclude transitive org.lz4:lz4-java to prevent LZ4 classpath conflict (2.134.x)
     new 18e464389eb Upgrade Netty from 4.1.122.Final to 4.1.132.Final (#17981)
     new 0f000cb1db7 Merge pull request #475 from startreedata/fix/lz4-classpath-conflict-2.134.x
     new f21c705d777 Add additional pruning step for Upsert Tables (#17898)
     new 1307cb3a669 Upserts Pruning Optimization - Do not clone MutableRoaringBitmap for each segment  (#17920)
     new ef5c51f668b Give out clear message when coordinate is NULL - H3 Index (#17967)
     new c16234ac3f3 Handle null H3 coordinates with continueOnError (#18040)
     new 474e2f98ef6 Upserts Bitmap Optimizations while taking Snapshot - Segment Commit (#18020)
     new 6f8896432a7 Merge pull request #481 from startreedata/hotfix-merge
     new a02bca26ddb allow enforceConsumptionInOrder to be rewritten at runtime (#18045)
     new cd9e1871258 Merge pull request #484 from startreedata/codex/cherry-pick-18045-startreedata-release-1.5.0-STP-2.134.x
     new 7e8a6eb061e Add endpoint to find segments with invalid partition metadata (#18057)
     new fa4d7594045 Add dropRecordOnPartitionMismatch config to StreamIngestionConfig (#18066)
     new a64acdce027 Merge pull request #494 from startreedata/cherry_pick_18066_and_18057
     new 68bd37ad6a1 Fix multi-controller race conditions in ResponseStoreCleaner cursor cleanup (#18113) (#487)
     new 2c02c75fbd9 Fix compilation issue in ResponseStoreCleaner (#496)
     new 4aa0f7695b0 Always emit COMMITTING_SEGMENT_SIZE and NUM_ROWS_THRESHOLD regardless of the threshold update type (#18137) (#501)
     new f30d306374b [bugfix] Clear realtime inverted index bitmaps on close (#18204)

The 25 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



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


(pinot) 14/25: Handle null H3 coordinates with continueOnError (#18040)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit c16234ac3f3304313fce1294853d6cbb92beac92
Author: Xiang Fu <xi...@apache.org>
AuthorDate: Tue Mar 31 03:23:12 2026 -0700

    Handle null H3 coordinates with continueOnError (#18040)
---
 .../impl/inv/geospatial/BaseH3IndexCreator.java    | 25 +++++-
 .../segment/local/segment/index/H3IndexTest.java   | 88 ++++++++++++++++++++++
 2 files changed, 111 insertions(+), 2 deletions(-)

diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java
index 5daa0ff163f..9d5d449b130 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java
@@ -19,6 +19,7 @@
 package org.apache.pinot.segment.local.segment.creator.impl.inv.geospatial;
 
 import com.google.common.base.Preconditions;
+import com.uber.h3core.exceptions.H3Exception;
 import java.io.BufferedOutputStream;
 import java.io.DataOutputStream;
 import java.io.File;
@@ -119,15 +120,35 @@ public abstract class BaseH3IndexCreator implements GeoSpatialIndexCreator {
   public void add(@Nullable Geometry geometry)
       throws IOException {
     if (_continueOnError && !(geometry instanceof Point)) {
-      MetricUtils.updateIndexingErrorMetric(_tableNameWithType, H3IndexType.INDEX_DISPLAY_NAME);
-      _nextDocId++;
+      skipInvalidGeometry();
       return;
     }
     Preconditions.checkState(geometry != null, "Null geometry record found and continueOnError is disabled");
     Preconditions.checkState(geometry instanceof Point, "H3 index can only be applied to Point, got: %s",
         geometry.getGeometryType());
     Coordinate coordinate = geometry.getCoordinate();
+    if (_continueOnError && coordinate == null) {
+      skipInvalidGeometry();
+      return;
+    }
     Preconditions.checkState(coordinate != null, "Point has null coordinate and continueOnError is disabled");
+    try {
+      addCoordinate(coordinate);
+    } catch (H3Exception e) {
+      if (_continueOnError) {
+        skipInvalidGeometry();
+        return;
+      }
+      throw e;
+    }
+  }
+
+  private void skipInvalidGeometry() {
+    MetricUtils.updateIndexingErrorMetric(_tableNameWithType, H3IndexType.INDEX_DISPLAY_NAME);
+    _nextDocId++;
+  }
+
+  private void addCoordinate(Coordinate coordinate) {
     // TODO: support multiple resolutions
     long h3Id = H3Utils.H3_CORE.latLngToCell(coordinate.y, coordinate.x, _lowestResolution);
     RoaringBitmapWriter<RoaringBitmap> bitmapWriter = _postingListMap.get(h3Id);
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/H3IndexTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/H3IndexTest.java
index 7e1bee3bf57..2ea6ae55e64 100644
--- a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/H3IndexTest.java
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/H3IndexTest.java
@@ -21,6 +21,7 @@ package org.apache.pinot.segment.local.segment.index;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.google.common.collect.Lists;
+import com.uber.h3core.exceptions.H3Exception;
 import java.io.File;
 import java.io.IOException;
 import java.util.Collections;
@@ -49,6 +50,7 @@ import org.apache.pinot.spi.config.table.FieldConfig;
 import org.locationtech.jts.geom.Coordinate;
 import org.locationtech.jts.geom.MultiPoint;
 import org.locationtech.jts.geom.Point;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
@@ -208,6 +210,58 @@ public class H3IndexTest implements PinotBuffersAfterMethodCheckRule {
     }
   }
 
+  @Test
+  public void testSkipPointWithNullCoordinate()
+      throws Exception {
+    String columnName = "skipPointWithNullCoordinate";
+    int res = 5;
+    H3IndexResolution resolution = new H3IndexResolution(Collections.singletonList(res));
+
+    try (GeoSpatialIndexCreator creator = new OnHeapH3IndexCreator(TEMP_DIR, columnName, "myTable_OFFLINE", true,
+        resolution)) {
+      Point point = GeometryUtils.GEOMETRY_FACTORY.createPoint(new Coordinate(10, 20));
+      Point pointWithNullCoordinate = GeometryUtils.GEOMETRY_FACTORY.createPoint((Coordinate) null);
+      creator.add(point);
+      creator.add(pointWithNullCoordinate);
+      creator.add(point);
+
+      creator.seal();
+    }
+
+    File indexFile = new File(TEMP_DIR, columnName + V1Constants.Indexes.H3_INDEX_FILE_EXTENSION);
+    try (PinotDataBuffer buffer = PinotDataBuffer.mapReadOnlyBigEndianFile(indexFile);
+        H3IndexReader reader = new ImmutableH3IndexReader(buffer)) {
+      long h3Id = H3Utils.H3_CORE.latLngToCell(20, 10, res);
+      Assert.assertEquals(reader.getDocIds(h3Id), ImmutableRoaringBitmap.bitmapOf(0, 2));
+    }
+  }
+
+  @Test
+  public void testSkipPointWithInvalidCoordinate()
+      throws Exception {
+    String columnName = "skipPointWithInvalidCoordinate";
+    int res = 5;
+    H3IndexResolution resolution = new H3IndexResolution(Collections.singletonList(res));
+
+    try (GeoSpatialIndexCreator creator = new OnHeapH3IndexCreator(TEMP_DIR, columnName, "myTable_OFFLINE", true,
+        resolution)) {
+      Point point = GeometryUtils.GEOMETRY_FACTORY.createPoint(new Coordinate(10, 20));
+      Point pointWithInvalidCoordinate = GeometryUtils.GEOMETRY_FACTORY.createPoint(new Coordinate(10, Double.NaN));
+      creator.add(point);
+      creator.add(pointWithInvalidCoordinate);
+      creator.add(point);
+
+      creator.seal();
+    }
+
+    File indexFile = new File(TEMP_DIR, columnName + V1Constants.Indexes.H3_INDEX_FILE_EXTENSION);
+    try (PinotDataBuffer buffer = PinotDataBuffer.mapReadOnlyBigEndianFile(indexFile);
+        H3IndexReader reader = new ImmutableH3IndexReader(buffer)) {
+      long h3Id = H3Utils.H3_CORE.latLngToCell(20, 10, res);
+      Assert.assertEquals(reader.getDocIds(h3Id), ImmutableRoaringBitmap.bitmapOf(0, 2));
+    }
+  }
+
   @Test
   public void testSkipInvalidGeometryContinueOnErrorFalse()
       throws Exception {
@@ -262,6 +316,40 @@ public class H3IndexTest implements PinotBuffersAfterMethodCheckRule {
     }
   }
 
+  @Test
+  public void testSkipPointWithNullCoordinateContinueOnErrorFalse()
+      throws Exception {
+    String columnName = "skipPointWithNullCoordinate";
+    int res = 5;
+    H3IndexResolution resolution = new H3IndexResolution(Collections.singletonList(res));
+
+    try (GeoSpatialIndexCreator creator = new OnHeapH3IndexCreator(TEMP_DIR, columnName, "myTable_OFFLINE", false,
+        resolution)) {
+      Point point = GeometryUtils.GEOMETRY_FACTORY.createPoint(new Coordinate(10, 20));
+      Point pointWithNullCoordinate = GeometryUtils.GEOMETRY_FACTORY.createPoint((Coordinate) null);
+      creator.add(point);
+
+      Assert.assertThrows(IllegalStateException.class, () -> creator.add(pointWithNullCoordinate));
+    }
+  }
+
+  @Test
+  public void testSkipPointWithInvalidCoordinateContinueOnErrorFalse()
+      throws Exception {
+    String columnName = "skipPointWithInvalidCoordinate";
+    int res = 5;
+    H3IndexResolution resolution = new H3IndexResolution(Collections.singletonList(res));
+
+    try (GeoSpatialIndexCreator creator = new OnHeapH3IndexCreator(TEMP_DIR, columnName, "myTable_OFFLINE", false,
+        resolution)) {
+      Point point = GeometryUtils.GEOMETRY_FACTORY.createPoint(new Coordinate(10, 20));
+      Point pointWithInvalidCoordinate = GeometryUtils.GEOMETRY_FACTORY.createPoint(new Coordinate(10, Double.NaN));
+      creator.add(point);
+
+      Assert.assertThrows(H3Exception.class, () -> creator.add(pointWithInvalidCoordinate));
+    }
+  }
+
   public static class ConfTest extends AbstractSerdeIndexContract {
 
     protected void assertEquals(H3IndexConfig expected) {


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


(pinot) 18/25: Merge pull request #484 from startreedata/codex/cherry-pick-18045-startreedata-release-1.5.0-STP-2.134.x

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit cd9e18712582180e53c0b265de66882f3446936f
Merge: 6f8896432a7 a02bca26ddb
Author: Kartik Khare <kh...@gmail.com>
AuthorDate: Tue Apr 7 12:46:13 2026 +0530

    Merge pull request #484 from startreedata/codex/cherry-pick-18045-startreedata-release-1.5.0-STP-2.134.x
    
    Cherry-pick #18045 into release/1.5.0-STP-2.134.x

 .../data/manager/realtime/RealtimeTableDataManager.java     |  7 +++++--
 .../data/manager/realtime/RealtimeTableDataManagerTest.java | 13 +++++++++++++
 2 files changed, 18 insertions(+), 2 deletions(-)


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


(pinot) 19/25: Add endpoint to find segments with invalid partition metadata (#18057)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 7e8a6eb061edca1a90e97d8fd63db0b7907c2e97
Author: Xiaotian (Jackie) Jiang <17...@users.noreply.github.com>
AuthorDate: Tue Mar 31 19:30:02 2026 -0700

    Add endpoint to find segments with invalid partition metadata (#18057)
---
 .../api/resources/PinotSegmentRestletResource.java | 144 +++++++++++++++------
 .../resources/PinotSegmentRestletResourceTest.java |  85 ++++++++++++
 2 files changed, 188 insertions(+), 41 deletions(-)

diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResource.java b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResource.java
index 6355371273c..a8c52298253 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResource.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResource.java
@@ -70,6 +70,7 @@ import org.apache.helix.zookeeper.datamodel.ZNRecord;
 import org.apache.pinot.common.exception.InvalidConfigException;
 import org.apache.pinot.common.lineage.SegmentLineage;
 import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.metadata.segment.SegmentPartitionMetadata;
 import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
 import org.apache.pinot.common.utils.DatabaseUtils;
 import org.apache.pinot.common.utils.LLCSegmentName;
@@ -87,10 +88,12 @@ import org.apache.pinot.controller.util.TableTierReader;
 import org.apache.pinot.core.auth.Actions;
 import org.apache.pinot.core.auth.Authorize;
 import org.apache.pinot.core.auth.TargetType;
+import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.config.table.TableType;
 import org.apache.pinot.spi.data.DateTimeFieldSpec;
 import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.utils.CommonConstants;
 import org.apache.pinot.spi.utils.JsonUtils;
 import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.slf4j.Logger;
@@ -166,15 +169,18 @@ import static org.apache.pinot.spi.utils.CommonConstants.SWAGGER_AUTHORIZATION_K
  *   </li>
  * </ul>
  */
-@Api(tags = Constants.SEGMENT_TAG, authorizations = {@Authorization(value = SWAGGER_AUTHORIZATION_KEY),
-    @Authorization(value = DATABASE)})
+@Api(tags = Constants.SEGMENT_TAG, authorizations = {
+    @Authorization(value = SWAGGER_AUTHORIZATION_KEY),
+    @Authorization(value = DATABASE)
+})
 @SwaggerDefinition(securityDefinition = @SecurityDefinition(apiKeyAuthDefinitions = {
     @ApiKeyAuthDefinition(name = HttpHeaders.AUTHORIZATION, in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER,
         key = SWAGGER_AUTHORIZATION_KEY,
         description = "The format of the key is  ```\"Basic <token>\" or \"Bearer <token>\"```"),
     @ApiKeyAuthDefinition(name = DATABASE, in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = DATABASE,
         description = "Database context passed through http header. If no context is provided 'default' database "
-            + "context will be considered.")}))
+            + "context will be considered.")
+}))
 @Path("/")
 public class PinotSegmentRestletResource {
   private static final Logger LOGGER = LoggerFactory.getLogger(PinotSegmentRestletResource.class);
@@ -372,7 +378,6 @@ public class PinotSegmentRestletResource {
     return segmentZKMetadata != null ? segmentZKMetadata.toMap() : null;
   }
 
-
   /**
    * Helper method to find the existing table based on the given table name (with or without type suffix) and segment
    * name.
@@ -404,10 +409,10 @@ public class PinotSegmentRestletResource {
           + "it again", notes = "Resets a segment by disabling and then enabling it")
   public SuccessResponse resetSegment(
       @ApiParam(value = "Name of the table with type", required = true) @PathParam("tableNameWithType")
-          String tableNameWithType,
+      String tableNameWithType,
       @ApiParam(value = "Name of the segment", required = true) @PathParam("segmentName") @Encoded String segmentName,
       @ApiParam(value = "Name of the target instance to reset") @QueryParam("targetInstance") @Nullable
-          String targetInstance, @Context HttpHeaders headers) {
+      String targetInstance, @Context HttpHeaders headers) {
     tableNameWithType = DatabaseUtils.translateTableName(tableNameWithType, headers);
     segmentName = URIUtils.decode(segmentName);
     TableType tableType = TableNameBuilder.getTableTypeFromTableName(tableNameWithType);
@@ -444,9 +449,9 @@ public class PinotSegmentRestletResource {
           + " and finally enabling them", notes = "Resets segments by disabling and then enabling them")
   public SuccessResponse resetSegments(
       @ApiParam(value = "Name of the table with type", required = true) @PathParam("tableNameWithType")
-          String tableNameWithType,
+      String tableNameWithType,
       @ApiParam(value = "Name of the target instance to reset") @QueryParam("targetInstance") @Nullable
-          String targetInstance,
+      String targetInstance,
       @ApiParam(value = "Whether to reset only segments with error state") @QueryParam("errorSegmentsOnly")
       @DefaultValue("false") boolean errorSegmentsOnly, @Context HttpHeaders headers) {
     tableNameWithType = DatabaseUtils.translateTableName(tableNameWithType, headers);
@@ -728,7 +733,6 @@ public class PinotSegmentRestletResource {
     return segmentsMetadata;
   }
 
-
   @GET
   @Path("segments/{tableNameWithType}/isStale")
   @Authorize(targetType = TargetType.TABLE, paramName = "tableNameWithType", action = Actions.Table.GET_METADATA)
@@ -745,7 +749,7 @@ public class PinotSegmentRestletResource {
       TableMetadataReader tableMetadataReader =
           new TableMetadataReader(_executor, _connectionManager, _pinotHelixResourceManager);
       return tableMetadataReader.getStaleSegments(tableNameWithType,
-              _controllerConf.getServerAdminRequestTimeoutSeconds() * 1000);
+          _controllerConf.getServerAdminRequestTimeoutSeconds() * 1000);
     } catch (InvalidConfigException e) {
       throw new ControllerApplicationException(LOGGER, e.getMessage(), Status.BAD_REQUEST);
     } catch (IOException ioe) {
@@ -779,6 +783,64 @@ public class PinotSegmentRestletResource {
     return segmentToMetadataMap;
   }
 
+  @GET
+  @Path("segments/{tableName}/invalidPartitionMetadata")
+  @Authorize(targetType = TargetType.TABLE, paramName = "tableName", action = Actions.Table.GET_METADATA)
+  @Produces(MediaType.APPLICATION_JSON)
+  @ApiOperation(
+      value = "Get the invalid partition metadata for all table segments",
+      notes = "Get the invalid partition metadata for all table segments"
+  )
+  public Map<String, String> getSegmentsWithInvalidPartitionMetadata(
+      @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName,
+      @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") @Nullable String tableTypeStr,
+      @ApiParam(value = "Partition column") @QueryParam("partitionColumn") @Nullable String partitionColumn,
+      @Context HttpHeaders headers) {
+    String tableNameWithType = ResourceUtils.getExistingTableNamesWithType(_pinotHelixResourceManager,
+        DatabaseUtils.translateTableName(tableName, headers), Constants.validateTableType(tableTypeStr), LOGGER).get(0);
+    LOGGER.info("Received a request to fetch invalid partition metadata for all segments for table {}",
+        tableNameWithType);
+    Map<String, String> segmentsWithInvalidPartitionMetadata = new HashMap<>();
+    List<SegmentZKMetadata> segmentZKMetadataList = _pinotHelixResourceManager.getSegmentsZKMetadata(tableNameWithType);
+    for (SegmentZKMetadata segmentZKMetadata : segmentZKMetadataList) {
+      String partitionMetadataJson =
+          segmentZKMetadata.getSimpleFields().get(CommonConstants.Segment.PARTITION_METADATA);
+      if (!isValidPartitionMetadata(partitionMetadataJson, partitionColumn)) {
+        segmentsWithInvalidPartitionMetadata.put(segmentZKMetadata.getSegmentName(), partitionMetadataJson);
+      }
+    }
+    return segmentsWithInvalidPartitionMetadata;
+  }
+
+  /// When partition column is not specified, returns `true` when all columns within the metadata contain single
+  /// partition. Treat `null` metadata as valid.
+  /// When partition column is specified, return `true` when the specified column within the metadata contains single
+  /// partition. Treat `null` metadata as invalid.
+  private boolean isValidPartitionMetadata(@Nullable String partitionMetadataJson, @Nullable String partitionColumn) {
+    if (StringUtils.isBlank(partitionColumn)) {
+      partitionColumn = null;
+    }
+    if (partitionMetadataJson == null) {
+      return partitionColumn == null;
+    }
+    SegmentPartitionMetadata metadata;
+    try {
+      metadata = SegmentPartitionMetadata.fromJsonString(partitionMetadataJson);
+    } catch (Exception e) {
+      return false;
+    }
+    if (partitionColumn == null) {
+      for (ColumnPartitionMetadata columnMetadata : metadata.getColumnPartitionMap().values()) {
+        if (columnMetadata.getPartitions().size() != 1) {
+          return false;
+        }
+      }
+      return true;
+    }
+    Set<Integer> partitions = metadata.getPartitions(partitionColumn);
+    return partitions != null && partitions.size() == 1;
+  }
+
   @GET
   @Path("segments/{tableName}/tiers")
   @Authorize(targetType = TargetType.TABLE, paramName = "tableName", action = Actions.Table.GET_STORAGE_TIER)
@@ -859,9 +921,9 @@ public class PinotSegmentRestletResource {
       @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName,
       @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr,
       @ApiParam(value = "Start timestamp (inclusive) in milliseconds") @QueryParam("startTimestamp") @DefaultValue("")
-          String startTimestampStr,
+      String startTimestampStr,
       @ApiParam(value = "End timestamp (exclusive) in milliseconds") @QueryParam("endTimestamp") @DefaultValue("")
-          String endTimestampStr,
+      String endTimestampStr,
       @ApiParam(value = "Whether to exclude the segments overlapping with the timestamps, false by default")
       @QueryParam("excludeOverlapping") @DefaultValue("false") boolean excludeOverlapping) {
     long startTimestamp;
@@ -1120,39 +1182,39 @@ public class PinotSegmentRestletResource {
    * @return
    */
   private SuccessResponse updateZKTimeIntervalInternal(String tableNameWithType) {
-      TableConfig tableConfig = _pinotHelixResourceManager.getTableConfig(tableNameWithType);
-      if (tableConfig == null) {
-        throw new ControllerApplicationException(LOGGER,
-            "Failed to find table config for table: " + tableNameWithType, Status.NOT_FOUND);
-      }
+    TableConfig tableConfig = _pinotHelixResourceManager.getTableConfig(tableNameWithType);
+    if (tableConfig == null) {
+      throw new ControllerApplicationException(LOGGER,
+          "Failed to find table config for table: " + tableNameWithType, Status.NOT_FOUND);
+    }
 
-      Schema tableSchema = _pinotHelixResourceManager.getTableSchema(tableNameWithType);
-      if (tableSchema == null) {
-        throw new ControllerApplicationException(LOGGER,
-            "Failed to find schema for table: " + tableNameWithType, Status.NOT_FOUND);
-      }
+    Schema tableSchema = _pinotHelixResourceManager.getTableSchema(tableNameWithType);
+    if (tableSchema == null) {
+      throw new ControllerApplicationException(LOGGER,
+          "Failed to find schema for table: " + tableNameWithType, Status.NOT_FOUND);
+    }
 
-      String timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
-      if (StringUtils.isEmpty(timeColumn)) {
-        throw new ControllerApplicationException(LOGGER,
-            "Failed to find time column for table : " + tableNameWithType, Status.NOT_FOUND);
-      }
+    String timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+    if (StringUtils.isEmpty(timeColumn)) {
+      throw new ControllerApplicationException(LOGGER,
+          "Failed to find time column for table : " + tableNameWithType, Status.NOT_FOUND);
+    }
 
-      DateTimeFieldSpec timeColumnFieldSpec = tableSchema.getSpecForTimeColumn(timeColumn);
-      if (timeColumnFieldSpec == null) {
-        throw new ControllerApplicationException(LOGGER,
-            String.format("Failed to find field spec for column: %s and table: %s", timeColumn, tableNameWithType),
-            Status.NOT_FOUND);
-      }
+    DateTimeFieldSpec timeColumnFieldSpec = tableSchema.getSpecForTimeColumn(timeColumn);
+    if (timeColumnFieldSpec == null) {
+      throw new ControllerApplicationException(LOGGER,
+          String.format("Failed to find field spec for column: %s and table: %s", timeColumn, tableNameWithType),
+          Status.NOT_FOUND);
+    }
 
-      try {
-        _pinotHelixResourceManager.updateSegmentsZKTimeInterval(tableNameWithType, timeColumnFieldSpec);
-      } catch (Exception e) {
-        throw new ControllerApplicationException(LOGGER,
-            String.format("Failed to update time interval zk metadata for table %s", tableNameWithType),
-            Status.INTERNAL_SERVER_ERROR, e);
-      }
-      return new SuccessResponse("Successfully updated time interval zk metadata for table: " + tableNameWithType);
+    try {
+      _pinotHelixResourceManager.updateSegmentsZKTimeInterval(tableNameWithType, timeColumnFieldSpec);
+    } catch (Exception e) {
+      throw new ControllerApplicationException(LOGGER,
+          String.format("Failed to update time interval zk metadata for table %s", tableNameWithType),
+          Status.INTERNAL_SERVER_ERROR, e);
+    }
+    return new SuccessResponse("Successfully updated time interval zk metadata for table: " + tableNameWithType);
   }
 
   private List<Pair<TableType, List<String>>> selectSegments(
diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResourceTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResourceTest.java
index 97f14aa2ee7..8cc2a397c27 100644
--- a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResourceTest.java
+++ b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentRestletResourceTest.java
@@ -27,19 +27,30 @@ import java.util.Set;
 import java.util.stream.Collectors;
 import org.apache.helix.model.IdealState;
 import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.pinot.common.exception.TableNotFoundException;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
 import org.apache.pinot.common.utils.LLCSegmentName;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.spi.utils.CommonConstants;
 import org.mockito.InjectMocks;
+import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
 
 
 public class PinotSegmentRestletResourceTest {
 
+  @Mock
+  PinotHelixResourceManager _pinotHelixResourceManager;
+
   @InjectMocks
   PinotSegmentRestletResource _pinotSegmentRestletResource;
 
@@ -132,6 +143,80 @@ public class PinotSegmentRestletResourceTest {
     assertEquals(expectedResult, result);
   }
 
+  @Test
+  public void testGetSegmentsWithInvalidPartitionMetadata()
+      throws TableNotFoundException {
+    String tableName = "testTable";
+    String tableNameWithType = "testTable_OFFLINE";
+    when(_pinotHelixResourceManager.getExistingTableNamesWithType(eq(tableName), any()))
+        .thenReturn(List.of(tableNameWithType));
+
+    // seg0: null partition metadata, no column filter → valid
+    SegmentZKMetadata seg0 = new SegmentZKMetadata("seg0");
+
+    // seg1: single partition per column, no column filter → valid
+    SegmentZKMetadata seg1 = new SegmentZKMetadata("seg1");
+    seg1.getSimpleFields().put(CommonConstants.Segment.PARTITION_METADATA,
+        "{\"columnPartitionMap\":{\"col\":{\"functionName\":\"Modulo\",\"numPartitions\":4,\"partitions\":[0]}}}");
+
+    // seg2: multiple partitions for a column, no column filter → invalid
+    SegmentZKMetadata seg2 = new SegmentZKMetadata("seg2");
+    seg2.getSimpleFields().put(CommonConstants.Segment.PARTITION_METADATA,
+        "{\"columnPartitionMap\":{\"col\":{\"functionName\":\"Modulo\",\"numPartitions\":4,\"partitions\":[0,1]}}}");
+
+    // seg3: malformed JSON → invalid
+    SegmentZKMetadata seg3 = new SegmentZKMetadata("seg3");
+    seg3.getSimpleFields().put(CommonConstants.Segment.PARTITION_METADATA, "not-valid-json");
+
+    when(_pinotHelixResourceManager.getSegmentsZKMetadata(tableNameWithType))
+        .thenReturn(List.of(seg0, seg1, seg2, seg3));
+
+    // no column filter: seg0 (null) is valid, seg1 is valid, seg2 (multi-partition) and seg3 (malformed) are invalid
+    Map<String, String> result =
+        _pinotSegmentRestletResource.getSegmentsWithInvalidPartitionMetadata(tableName, "OFFLINE", null, null);
+    assertEquals(result.size(), 2);
+    assertTrue(result.containsKey("seg2"));
+    assertTrue(result.containsKey("seg3"));
+  }
+
+  @Test
+  public void testGetSegmentsWithInvalidPartitionMetadataWithColumnFilter()
+      throws TableNotFoundException {
+    String tableName = "testTable2";
+    String tableNameWithType = "testTable2_OFFLINE";
+    when(_pinotHelixResourceManager.getExistingTableNamesWithType(eq(tableName), any()))
+        .thenReturn(List.of(tableNameWithType));
+
+    // seg0: null partition metadata, column specified → invalid
+    SegmentZKMetadata seg0 = new SegmentZKMetadata("seg0");
+
+    // seg1: single partition for the specified column → valid
+    SegmentZKMetadata seg1 = new SegmentZKMetadata("seg1");
+    seg1.getSimpleFields().put(CommonConstants.Segment.PARTITION_METADATA,
+        "{\"columnPartitionMap\":{\"col\":{\"functionName\":\"Modulo\",\"numPartitions\":4,\"partitions\":[2]}}}");
+
+    // seg2: multiple partitions for the specified column → invalid
+    SegmentZKMetadata seg2 = new SegmentZKMetadata("seg2");
+    seg2.getSimpleFields().put(CommonConstants.Segment.PARTITION_METADATA,
+        "{\"columnPartitionMap\":{\"col\":{\"functionName\":\"Modulo\",\"numPartitions\":4,\"partitions\":[0,1]}}}");
+
+    // seg3: specified column not present in partition metadata → invalid
+    SegmentZKMetadata seg3 = new SegmentZKMetadata("seg3");
+    seg3.getSimpleFields().put(CommonConstants.Segment.PARTITION_METADATA,
+        "{\"columnPartitionMap\":{\"otherCol\":{\"functionName\":\"Modulo\",\"numPartitions\":4,\"partitions\":[0]}}}");
+
+    when(_pinotHelixResourceManager.getSegmentsZKMetadata(tableNameWithType))
+        .thenReturn(List.of(seg0, seg1, seg2, seg3));
+
+    // with column filter "col": seg0 (null metadata), seg2 (multi-partition), seg3 (column absent) are invalid
+    Map<String, String> result =
+        _pinotSegmentRestletResource.getSegmentsWithInvalidPartitionMetadata(tableName, "OFFLINE", "col", null);
+    assertEquals(result.size(), 3);
+    assertTrue(result.containsKey("seg0"));
+    assertTrue(result.containsKey("seg2"));
+    assertTrue(result.containsKey("seg3"));
+  }
+
   private List<String> getSegmentForPartition(String tableName, int partitionID, int sequenceNumberOffset,
       int numberOfSegments, long currentTime) {
     List<String> segments = new ArrayList<>();


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


(pinot) 07/25: Merge pull request #472 from startreedata/lz4_failure

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit cdc6d3a5d1cedb898ed3b0f0dc5700e140679f07
Merge: 780f7a366dd 42ce629b7c2
Author: Xiang Fu <xi...@apache.org>
AuthorDate: Mon Mar 30 03:17:44 2026 -0700

    Merge pull request #472 from startreedata/lz4_failure
    
    cherry-pick: Migrate lz4-java from org.lz4:lz4-java 1.8.0 to at.yawk.lz4:lz4-java1.10.4 (#18015)

 pinot-common/pom.xml | 2 +-
 pom.xml              | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)


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


(pinot) 08/25: fix: Exclude transitive org.lz4:lz4-java to prevent LZ4 classpath conflict (2.134.x)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 5c33c2b475ad672e40b0912ba2bce7951e998643
Author: Jinesh Parakh <ji...@hotmail.com>
AuthorDate: Mon Mar 30 23:55:20 2026 +0530

    fix: Exclude transitive org.lz4:lz4-java to prevent LZ4 classpath conflict (2.134.x)
    
    Signed-off-by: Jinesh Parakh <ji...@hotmail.com>
---
 pinot-connectors/pinot-flink-connector/pom.xml                      | 6 ++++++
 pinot-connectors/pinot-spark-2-connector/pom.xml                    | 4 ++++
 pinot-connectors/pinot-spark-3-connector/pom.xml                    | 6 ++++++
 pinot-integration-tests/pom.xml                                     | 6 ++++++
 .../pinot-batch-ingestion/pinot-batch-ingestion-spark-2.4/pom.xml   | 4 ++++
 .../pinot-batch-ingestion/pinot-batch-ingestion-spark-3/pom.xml     | 4 ++++
 pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/pom.xml        | 6 ++++++
 pom.xml                                                             | 2 ++
 8 files changed, 38 insertions(+)

diff --git a/pinot-connectors/pinot-flink-connector/pom.xml b/pinot-connectors/pinot-flink-connector/pom.xml
index f2a7587dfe3..242ac5fb062 100644
--- a/pinot-connectors/pinot-flink-connector/pom.xml
+++ b/pinot-connectors/pinot-flink-connector/pom.xml
@@ -46,6 +46,12 @@
     <dependency>
       <groupId>org.apache.flink</groupId>
       <artifactId>flink-streaming-java</artifactId>
+      <exclusions>
+        <exclusion>
+          <groupId>org.lz4</groupId>
+          <artifactId>lz4-java</artifactId>
+        </exclusion>
+      </exclusions>
     </dependency>
     <dependency>
       <groupId>org.apache.flink</groupId>
diff --git a/pinot-connectors/pinot-spark-2-connector/pom.xml b/pinot-connectors/pinot-spark-2-connector/pom.xml
index b9638b6c87e..7414af1acaf 100644
--- a/pinot-connectors/pinot-spark-2-connector/pom.xml
+++ b/pinot-connectors/pinot-spark-2-connector/pom.xml
@@ -103,6 +103,10 @@
               <groupId>org.slf4j</groupId>
               <artifactId>slf4j-log4j12</artifactId>
             </exclusion>
+            <exclusion>
+              <groupId>org.lz4</groupId>
+              <artifactId>lz4-java</artifactId>
+            </exclusion>
           </exclusions>
         </dependency>
         <dependency>
diff --git a/pinot-connectors/pinot-spark-3-connector/pom.xml b/pinot-connectors/pinot-spark-3-connector/pom.xml
index b626e6aa48d..d4a59eadd68 100644
--- a/pinot-connectors/pinot-spark-3-connector/pom.xml
+++ b/pinot-connectors/pinot-spark-3-connector/pom.xml
@@ -90,6 +90,12 @@
           <artifactId>spark-sql_${scala.compat.version}</artifactId>
           <version>${spark3.version}</version>
           <scope>provided</scope>
+          <exclusions>
+            <exclusion>
+              <groupId>org.lz4</groupId>
+              <artifactId>lz4-java</artifactId>
+            </exclusion>
+          </exclusions>
         </dependency>
         <dependency>
           <groupId>org.scala-lang</groupId>
diff --git a/pinot-integration-tests/pom.xml b/pinot-integration-tests/pom.xml
index d304beb91f8..275a65b11b4 100644
--- a/pinot-integration-tests/pom.xml
+++ b/pinot-integration-tests/pom.xml
@@ -316,6 +316,12 @@
       <artifactId>spark-core_${scala.compat.version}</artifactId>
       <version>${spark3.version}</version>
       <scope>test</scope>
+      <exclusions>
+        <exclusion>
+          <groupId>org.lz4</groupId>
+          <artifactId>lz4-java</artifactId>
+        </exclusion>
+      </exclusions>
     </dependency>
     <dependency>
       <groupId>org.apache.pinot</groupId>
diff --git a/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-2.4/pom.xml b/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-2.4/pom.xml
index 30bca0af843..05024e78049 100644
--- a/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-2.4/pom.xml
+++ b/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-2.4/pom.xml
@@ -59,6 +59,10 @@
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
         </exclusion>
+        <exclusion>
+          <groupId>org.lz4</groupId>
+          <artifactId>lz4-java</artifactId>
+        </exclusion>
       </exclusions>
     </dependency>
     <dependency>
diff --git a/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-3/pom.xml b/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-3/pom.xml
index 53ccc1b7283..2e3b634ac4a 100644
--- a/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-3/pom.xml
+++ b/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-spark-3/pom.xml
@@ -58,6 +58,10 @@
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
         </exclusion>
+        <exclusion>
+          <groupId>org.lz4</groupId>
+          <artifactId>lz4-java</artifactId>
+        </exclusion>
       </exclusions>
     </dependency>
     <dependency>
diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/pom.xml b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/pom.xml
index 00c585b3971..c812dd03bed 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/pom.xml
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/pom.xml
@@ -46,6 +46,12 @@
       <groupId>org.apache.kafka</groupId>
       <artifactId>kafka-clients</artifactId>
       <version>${kafka4.version}</version>
+      <exclusions>
+        <exclusion>
+          <groupId>org.lz4</groupId>
+          <artifactId>lz4-java</artifactId>
+        </exclusion>
+      </exclusions>
     </dependency>
 
     <!-- Test dependencies -->
diff --git a/pom.xml b/pom.xml
index dcd7976c5f3..229c1b7974e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2370,6 +2370,8 @@
                       <exclude>org.apache.hadoop.thirdparty:hadoop-shaded-protobuf_3_7</exclude>
                       <!-- Use org.bouncycastle:bcprov-jdk18on -->
                       <exclude>org.bouncycastle:bcprov-jdk15on</exclude>
+                      <!-- Use at.yawk.lz4:lz4-java -->
+                      <exclude>org.lz4:lz4-java</exclude>
                     </excludes>
                   </bannedDependencies>
                 </rules>


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


(pinot) 09/25: Upgrade Netty from 4.1.122.Final to 4.1.132.Final (#17981)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 18e464389eb81bf790eb6cb7c8849206876e3d21
Author: Xiaotian (Jackie) Jiang <17...@users.noreply.github.com>
AuthorDate: Wed Mar 25 17:45:01 2026 -0700

    Upgrade Netty from 4.1.122.Final to 4.1.132.Final (#17981)
---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index dcd7976c5f3..cfc949564b3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -170,7 +170,7 @@
     <libthrift.verion>0.22.0</libthrift.verion>
     <log4j.version>2.25.3</log4j.version>
     <slf4j.version>2.0.17</slf4j.version>
-    <netty.version>4.1.122.Final</netty.version>
+    <netty.version>4.1.132.Final</netty.version>
     <reactivestreams.version>1.0.4</reactivestreams.version>
     <jts.version>1.20.0</jts.version>
     <h3.version>4.4.0</h3.version>


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


(pinot) 21/25: Merge pull request #494 from startreedata/cherry_pick_18066_and_18057

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit a64acdce0278b755b0bd56761668b3447891aa68
Merge: cd9e1871258 fa4d7594045
Author: 9aman <35...@users.noreply.github.com>
AuthorDate: Wed Apr 8 18:48:40 2026 +0530

    Merge pull request #494 from startreedata/cherry_pick_18066_and_18057
    
    Cherry pick 18066 and 18057

 .../api/resources/PinotSegmentRestletResource.java | 144 +++++++++++++++------
 .../resources/PinotSegmentRestletResourceTest.java |  85 ++++++++++++
 .../realtime/RealtimeSegmentDataManager.java       |   5 +-
 .../indexsegment/mutable/MutableSegmentImpl.java   |  53 ++++----
 .../local/realtime/impl/RealtimeSegmentConfig.java |  17 ++-
 .../writer/StatelessRealtimeSegmentWriter.java     |   9 +-
 ...gmentImplDropRecordOnPartitionMismatchTest.java | 131 +++++++++++++++++++
 .../mutable/MutableSegmentImplTestUtils.java       |  26 ++++
 .../table/ingestion/StreamIngestionConfig.java     |  12 ++
 9 files changed, 414 insertions(+), 68 deletions(-)


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


(pinot) 03/25: Add useRawBytes config to Murmur and Murmur3 partition functions (#17932)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 833989a5dc25f200943452c6b72bda69412dedce
Author: Xiang Fu <xi...@apache.org>
AuthorDate: Sat Mar 21 22:19:21 2026 -0700

    Add useRawBytes config to Murmur and Murmur3 partition functions (#17932)
    
    * Add useRawBytes config to Murmur and Murmur3 partition functions
    
    When partitioning on BYTES columns, the partition value is hex-encoded.
    With useRawBytes=true in functionConfig, the hex string is decoded back
    to raw bytes before hashing, ensuring partition assignment matches the
    original byte values rather than treating the hex string as UTF-8 text.
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    * Override getFunctionConfig() and restore backward-compatible constructor
    
    - Murmur and Murmur3 partition functions now persist and return the
      functionConfig via getFunctionConfig(), ensuring partition metadata
      written to ZK retains the config so brokers can reconstruct the
      function correctly.
    - Re-introduce MurmurPartitionFunction(int) constructor delegating to
      the new (int, Map) constructor to preserve SPI backward compatibility.
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    * Defensive copy and @Nullable annotations for functionConfig
    
    - Store functionConfig as Collections.unmodifiableMap() to prevent
      external mutation from diverging with parsed fields.
    - Annotate _functionConfig field and getFunctionConfig() with @Nullable
      in both MurmurPartitionFunction and Murmur3PartitionFunction.
    - Annotate Murmur3PartitionFunction constructor parameter with @Nullable.
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    * Add factory end-to-end test for useRawBytes with Murmur/Murmur2/Murmur3
    
    Verify that PartitionFunctionFactory.getPartitionFunction() correctly
    wires functionConfig through to the partition function for all three
    aliases, and that getFunctionConfig() roundtrips the config.
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 <no...@anthropic.com>
---
 .../spi/partition/Murmur3PartitionFunction.java    | 25 +++++-
 .../spi/partition/MurmurPartitionFunction.java     | 30 ++++++-
 .../spi/partition/PartitionFunctionFactory.java    |  2 +-
 .../spi/partition/PartitionFunctionTest.java       | 95 ++++++++++++++++++++++
 4 files changed, 148 insertions(+), 4 deletions(-)

diff --git a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/Murmur3PartitionFunction.java b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/Murmur3PartitionFunction.java
index ba22c1a992f..9a0110f810e 100644
--- a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/Murmur3PartitionFunction.java
+++ b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/Murmur3PartitionFunction.java
@@ -19,8 +19,11 @@
 package org.apache.pinot.segment.spi.partition;
 
 import com.google.common.base.Preconditions;
+import java.util.Collections;
 import java.util.Map;
+import javax.annotation.Nullable;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.spi.utils.BytesUtils;
 import org.apache.pinot.spi.utils.hash.MurmurHashFunctions;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
@@ -33,21 +36,27 @@ public class Murmur3PartitionFunction implements PartitionFunction {
   private static final String NAME = "Murmur3";
   private static final String SEED_KEY = "seed";
   private static final String VARIANT_KEY = "variant";
+  private static final String USE_RAW_BYTES_KEY = "useRawBytes";
   private final int _numPartitions;
+  @Nullable
+  private final Map<String, String> _functionConfig;
   private final int _seed;
   private final boolean _useX64;
+  private final boolean _useRawBytes;
 
   /**
    * Constructor for the class.
    * @param numPartitions Number of partitions.
    * @param functionConfig to extract configurations for the partition function.
    */
-  public Murmur3PartitionFunction(int numPartitions, Map<String, String> functionConfig) {
+  public Murmur3PartitionFunction(int numPartitions, @Nullable Map<String, String> functionConfig) {
     Preconditions.checkArgument(numPartitions > 0, "Number of partitions must be > 0");
     _numPartitions = numPartitions;
+    _functionConfig = functionConfig != null ? Collections.unmodifiableMap(functionConfig) : null;
 
     int seed = 0;
     boolean useX64 = false;
+    boolean useRawBytes = false;
     if (functionConfig != null) {
       String seedString = functionConfig.get(SEED_KEY);
       if (StringUtils.isNotEmpty(seedString)) {
@@ -62,13 +71,21 @@ public class Murmur3PartitionFunction implements PartitionFunction {
               "Murmur3 variant must be either x86_32 or x64_32");
         }
       }
+      useRawBytes = Boolean.parseBoolean(functionConfig.get(USE_RAW_BYTES_KEY));
     }
     _seed = seed;
     _useX64 = useX64;
+    _useRawBytes = useRawBytes;
   }
 
   @Override
   public int getPartition(String value) {
+    if (_useRawBytes) {
+      byte[] bytes = BytesUtils.toBytes(value);
+      int hash = _useX64 ? MurmurHashFunctions.murmurHash3X64Bit32(bytes, _seed)
+          : MurmurHashFunctions.murmurHash3X86Bit32(bytes, _seed);
+      return (hash & Integer.MAX_VALUE) % _numPartitions;
+    }
     int hash = _useX64 ? MurmurHashFunctions.murmurHash3X64Bit32(value, _seed)
         : MurmurHashFunctions.murmurHash3X86Bit32(value.getBytes(UTF_8), _seed);
     return (hash & Integer.MAX_VALUE) % _numPartitions;
@@ -84,6 +101,12 @@ public class Murmur3PartitionFunction implements PartitionFunction {
     return _numPartitions;
   }
 
+  @Nullable
+  @Override
+  public Map<String, String> getFunctionConfig() {
+    return _functionConfig;
+  }
+
   // Keep it for backward-compatibility, use getName() instead
   @Override
   public String toString() {
diff --git a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/MurmurPartitionFunction.java b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/MurmurPartitionFunction.java
index 8251450c44b..6c64dee763a 100644
--- a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/MurmurPartitionFunction.java
+++ b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/MurmurPartitionFunction.java
@@ -19,6 +19,10 @@
 package org.apache.pinot.segment.spi.partition;
 
 import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.pinot.spi.utils.BytesUtils;
 import org.apache.pinot.spi.utils.hash.MurmurHashFunctions;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
@@ -29,20 +33,36 @@ import static java.nio.charset.StandardCharsets.UTF_8;
  */
 public class MurmurPartitionFunction implements PartitionFunction {
   private static final String NAME = "Murmur";
+  private static final String USE_RAW_BYTES_KEY = "useRawBytes";
   private final int _numPartitions;
+  @Nullable
+  private final Map<String, String> _functionConfig;
+  private final boolean _useRawBytes;
 
   /**
-   * Constructor for the class.
+   * Constructor for backward compatibility.
    * @param numPartitions Number of partitions.
    */
   public MurmurPartitionFunction(int numPartitions) {
+    this(numPartitions, null);
+  }
+
+  /**
+   * Constructor for the class.
+   * @param numPartitions Number of partitions.
+   * @param functionConfig to extract configurations for the partition function.
+   */
+  public MurmurPartitionFunction(int numPartitions, @Nullable Map<String, String> functionConfig) {
     Preconditions.checkArgument(numPartitions > 0, "Number of partitions must be > 0");
     _numPartitions = numPartitions;
+    _functionConfig = functionConfig != null ? Collections.unmodifiableMap(functionConfig) : null;
+    _useRawBytes = functionConfig != null && Boolean.parseBoolean(functionConfig.get(USE_RAW_BYTES_KEY));
   }
 
   @Override
   public int getPartition(String value) {
-    return (MurmurHashFunctions.murmurHash2(value.getBytes(UTF_8)) & Integer.MAX_VALUE) % _numPartitions;
+    byte[] bytes = _useRawBytes ? BytesUtils.toBytes(value) : value.getBytes(UTF_8);
+    return (MurmurHashFunctions.murmurHash2(bytes) & Integer.MAX_VALUE) % _numPartitions;
   }
 
   @Override
@@ -55,6 +75,12 @@ public class MurmurPartitionFunction implements PartitionFunction {
     return _numPartitions;
   }
 
+  @Nullable
+  @Override
+  public Map<String, String> getFunctionConfig() {
+    return _functionConfig;
+  }
+
   // Keep it for backward-compatibility, use getName() instead
   @Override
   public String toString() {
diff --git a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java
index 202b04843ca..5a2bc20f431 100644
--- a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java
+++ b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java
@@ -77,7 +77,7 @@ public class PartitionFunctionFactory {
 
       case Murmur:
       case Murmur2:
-        return new MurmurPartitionFunction(numPartitions);
+        return new MurmurPartitionFunction(numPartitions, functionConfig);
 
       case Murmur3:
         return new Murmur3PartitionFunction(numPartitions, functionConfig);
diff --git a/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/partition/PartitionFunctionTest.java b/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/partition/PartitionFunctionTest.java
index 8bb44bb024f..42d7634376d 100644
--- a/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/partition/PartitionFunctionTest.java
+++ b/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/partition/PartitionFunctionTest.java
@@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.JsonNode;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Random;
+import org.apache.pinot.spi.utils.BytesUtils;
 import org.apache.pinot.spi.utils.JsonUtils;
 import org.apache.pinot.spi.utils.hash.MurmurHashFunctions;
 import org.testng.annotations.Test;
@@ -439,6 +440,100 @@ public class PartitionFunctionTest {
     testPartitionFunction(murmurPartitionFunction, expectedPartitions);
   }
 
+  @Test
+  public void testMurmurPartitionFunctionUseRawBytes() {
+    int numPartitions = 5;
+    Map<String, String> functionConfig = new HashMap<>();
+    functionConfig.put("useRawBytes", "true");
+    MurmurPartitionFunction partitionFunction = new MurmurPartitionFunction(numPartitions, functionConfig);
+
+    // When useRawBytes is true, the hex-encoded value should be decoded back to raw bytes before hashing.
+    // This means getPartition(hexString) should produce the same result as hashing the original raw bytes.
+    byte[] rawBytes = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05};
+    String hexValue = BytesUtils.toHexString(rawBytes);
+
+    int expectedPartition =
+        (MurmurHashFunctions.murmurHash2(rawBytes) & Integer.MAX_VALUE) % numPartitions;
+    assertEquals(partitionFunction.getPartition(hexValue), expectedPartition);
+
+    // Without useRawBytes, the same hex string should be treated as UTF-8 text (different result).
+    MurmurPartitionFunction defaultPartitionFunction = new MurmurPartitionFunction(numPartitions, null);
+    int defaultPartition =
+        (MurmurHashFunctions.murmurHash2(hexValue.getBytes(UTF_8)) & Integer.MAX_VALUE) % numPartitions;
+    assertEquals(defaultPartitionFunction.getPartition(hexValue), defaultPartition);
+  }
+
+  @Test
+  public void testMurmur3PartitionFunctionUseRawBytes() {
+    int numPartitions = 5;
+    byte[] rawBytes = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05};
+    String hexValue = BytesUtils.toHexString(rawBytes);
+
+    // Test x86_32 variant with useRawBytes
+    Map<String, String> functionConfig = new HashMap<>();
+    functionConfig.put("useRawBytes", "true");
+    Murmur3PartitionFunction partitionFunction = new Murmur3PartitionFunction(numPartitions, functionConfig);
+
+    int expectedPartition =
+        (MurmurHashFunctions.murmurHash3X86Bit32(rawBytes, 0) & Integer.MAX_VALUE) % numPartitions;
+    assertEquals(partitionFunction.getPartition(hexValue), expectedPartition);
+
+    // Test x64_32 variant with useRawBytes
+    functionConfig.put("variant", "x64_32");
+    Murmur3PartitionFunction partitionFunctionX64 = new Murmur3PartitionFunction(numPartitions, functionConfig);
+
+    int expectedPartitionX64 =
+        (MurmurHashFunctions.murmurHash3X64Bit32(rawBytes, 0) & Integer.MAX_VALUE) % numPartitions;
+    assertEquals(partitionFunctionX64.getPartition(hexValue), expectedPartitionX64);
+
+    // Test x86_32 variant with useRawBytes and non-zero seed
+    functionConfig.remove("variant");
+    functionConfig.put("seed", "9001");
+    Murmur3PartitionFunction partitionFunctionWithSeed = new Murmur3PartitionFunction(numPartitions, functionConfig);
+
+    int expectedPartitionWithSeed =
+        (MurmurHashFunctions.murmurHash3X86Bit32(rawBytes, 9001) & Integer.MAX_VALUE) % numPartitions;
+    assertEquals(partitionFunctionWithSeed.getPartition(hexValue), expectedPartitionWithSeed);
+
+    // Without useRawBytes, the same hex string should be treated as UTF-8 text.
+    Murmur3PartitionFunction defaultPartitionFunction = new Murmur3PartitionFunction(numPartitions, null);
+    int defaultPartition =
+        (MurmurHashFunctions.murmurHash3X86Bit32(hexValue.getBytes(UTF_8), 0) & Integer.MAX_VALUE) % numPartitions;
+    assertEquals(defaultPartitionFunction.getPartition(hexValue), defaultPartition);
+  }
+
+  @Test
+  public void testUseRawBytesThroughFactory() {
+    int numPartitions = 5;
+    byte[] rawBytes = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05};
+    String hexValue = BytesUtils.toHexString(rawBytes);
+    int expectedPartition =
+        (MurmurHashFunctions.murmurHash2(rawBytes) & Integer.MAX_VALUE) % numPartitions;
+
+    Map<String, String> functionConfig = new HashMap<>();
+    functionConfig.put("useRawBytes", "true");
+
+    // Test Murmur alias through factory
+    PartitionFunction murmurFn =
+        PartitionFunctionFactory.getPartitionFunction("Murmur", numPartitions, functionConfig);
+    assertEquals(murmurFn.getPartition(hexValue), expectedPartition);
+    assertEquals(murmurFn.getFunctionConfig().get("useRawBytes"), "true");
+
+    // Test Murmur2 alias through factory
+    PartitionFunction murmur2Fn =
+        PartitionFunctionFactory.getPartitionFunction("Murmur2", numPartitions, functionConfig);
+    assertEquals(murmur2Fn.getPartition(hexValue), expectedPartition);
+    assertEquals(murmur2Fn.getFunctionConfig().get("useRawBytes"), "true");
+
+    // Test Murmur3 through factory
+    int expectedPartitionMurmur3 =
+        (MurmurHashFunctions.murmurHash3X86Bit32(rawBytes, 0) & Integer.MAX_VALUE) % numPartitions;
+    PartitionFunction murmur3Fn =
+        PartitionFunctionFactory.getPartitionFunction("Murmur3", numPartitions, functionConfig);
+    assertEquals(murmur3Fn.getPartition(hexValue), expectedPartitionMurmur3);
+    assertEquals(murmur3Fn.getFunctionConfig().get("useRawBytes"), "true");
+  }
+
   @Test
   public void testMurmur3PartitionFunctionEquivalence() {
 


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


(pinot) 06/25: Migrate lz4-java from org.lz4:lz4-java 1.8.0 to at.yawk.lz4:lz4-java 1.10.4 (#18015)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 42ce629b7c25325df2ccf8d51e40a9c35c609500
Author: Xiang Fu <xi...@apache.org>
AuthorDate: Sat Mar 28 04:04:27 2026 -0700

    Migrate lz4-java from org.lz4:lz4-java 1.8.0 to at.yawk.lz4:lz4-java 1.10.4 (#18015)
    
    Auto-merged by automated PR review bot.
---
 pinot-common/pom.xml | 2 +-
 pom.xml              | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/pinot-common/pom.xml b/pinot-common/pom.xml
index e7dda3066f9..e2f4877fbef 100644
--- a/pinot-common/pom.xml
+++ b/pinot-common/pom.xml
@@ -203,7 +203,7 @@
       <artifactId>zstd-jni</artifactId>
     </dependency>
     <dependency>
-      <groupId>org.lz4</groupId>
+      <groupId>at.yawk.lz4</groupId>
       <artifactId>lz4-java</artifactId>
     </dependency>
     <dependency>
diff --git a/pom.xml b/pom.xml
index 895adbc8379..dcd7976c5f3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -166,7 +166,7 @@
     <dropwizard-metrics.version>4.2.38</dropwizard-metrics.version>
     <snappy-java.version>1.1.10.8</snappy-java.version>
     <zstd-jni.version>1.5.7-7</zstd-jni.version>
-    <lz4-java.version>1.8.0</lz4-java.version>
+    <lz4-java.version>1.10.4</lz4-java.version>
     <libthrift.verion>0.22.0</libthrift.verion>
     <log4j.version>2.25.3</log4j.version>
     <slf4j.version>2.0.17</slf4j.version>
@@ -1059,7 +1059,7 @@
         <version>${zstd-jni.version}</version>
       </dependency>
       <dependency>
-        <groupId>org.lz4</groupId>
+        <groupId>at.yawk.lz4</groupId>
         <artifactId>lz4-java</artifactId>
         <version>${lz4-java.version}</version>
       </dependency>


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


(pinot) 15/25: Upserts Bitmap Optimizations while taking Snapshot - Segment Commit (#18020)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 474e2f98ef6575fa186784c21144160aaee55737
Author: Chaitanya Deepthi <45...@users.noreply.github.com>
AuthorDate: Tue Mar 31 16:07:16 2026 -0700

    Upserts Bitmap Optimizations while taking Snapshot - Segment Commit (#18020)
---
 .../immutable/ImmutableSegmentImpl.java            | 38 ++++++------
 .../segment/local/segment/readers/LazyRow.java     |  1 +
 .../upsert/BasePartitionUpsertMetadataManager.java | 71 ++++++++++++----------
 ...oncurrentMapPartitionUpsertMetadataManager.java | 10 ++-
 ...nUpsertMetadataManagerForConsistentDeletes.java | 10 ++-
 .../BasePartitionUpsertMetadataManagerTest.java    | 50 +++++++--------
 .../mutable/ThreadSafeMutableRoaringBitmap.java    | 45 +++++++++++++-
 7 files changed, 140 insertions(+), 85 deletions(-)

diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/immutable/ImmutableSegmentImpl.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/immutable/ImmutableSegmentImpl.java
index 1e39eee3fd6..ea746139e90 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/immutable/ImmutableSegmentImpl.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/immutable/ImmutableSegmentImpl.java
@@ -20,7 +20,6 @@ package org.apache.pinot.segment.local.indexsegment.immutable;
 
 import com.google.common.base.Preconditions;
 import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
-import java.io.DataOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -151,26 +150,23 @@ public class ImmutableSegmentImpl implements ImmutableSegment {
     return null;
   }
 
-  public void persistDocIdsSnapshot(String fileName, ThreadSafeMutableRoaringBitmap docIds) {
-    File docIdsSnapshotFile = getSnapshotFile(fileName);
-    try {
-      File tmpFile =
-          new File(SegmentDirectoryPaths.findSegmentDirectory(_segmentMetadata.getIndexDir()), fileName + "_tmp");
-      if (tmpFile.exists()) {
-        LOGGER.warn("Previous snapshot was not taken cleanly. Remove tmp file: {}", tmpFile);
-        FileUtils.deleteQuietly(tmpFile);
-      }
-      MutableRoaringBitmap docIdsSnapshot = docIds.getMutableRoaringBitmap();
-      try (DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(tmpFile))) {
-        docIdsSnapshot.serialize(dataOutputStream);
-      }
-      Preconditions.checkState(tmpFile.renameTo(docIdsSnapshotFile),
-          "Failed to rename tmp snapshot file: %s to snapshot file: %s", tmpFile, docIdsSnapshotFile);
-      LOGGER.info("Persisted docIds for segment: {} with: {}", getSegmentName(), docIdsSnapshot.getCardinality());
-    } catch (Exception e) {
-      LOGGER.warn("Caught exception while persisting docIds to snapshot file: {}, skipping",
-          docIdsSnapshotFile, e);
+  /// Persists the doc ids bitmap snapshot into the given file.
+  public void persistDocIdsSnapshot(String fileName, ThreadSafeMutableRoaringBitmap.CardinalityAndBytes docIdsSnapshot)
+      throws IOException {
+    File tmpFile =
+        new File(SegmentDirectoryPaths.findSegmentDirectory(_segmentMetadata.getIndexDir()), fileName + "_tmp");
+    if (tmpFile.exists()) {
+      LOGGER.warn("Previous snapshot was not taken cleanly. Remove tmp file: {}", tmpFile);
+      FileUtils.deleteQuietly(tmpFile);
+    }
+    try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
+      fos.write(docIdsSnapshot.getBytes());
     }
+    File docIdsSnapshotFile = getSnapshotFile(fileName);
+    Preconditions.checkState(tmpFile.renameTo(docIdsSnapshotFile),
+        "Failed to rename tmp snapshot file: %s to snapshot file: %s", tmpFile, docIdsSnapshotFile);
+    LOGGER.info("Persisted {} with: {} docs for segment: {}", fileName, docIdsSnapshot.getCardinality(),
+        getSegmentName());
   }
 
   public void deleteSnapshotFile(String fileName) {
@@ -181,7 +177,7 @@ public class ImmutableSegmentImpl implements ImmutableSegment {
           LOGGER.warn("Cannot delete old snapshot file: {}, skipping", snapshotFile);
           return;
         }
-        LOGGER.info("Deleted snapshot for segment: {}", getSegmentName());
+        LOGGER.info("Deleted {} for segment: {}", fileName, getSegmentName());
       } catch (Exception e) {
         LOGGER.warn("Caught exception while deleting snapshot file: {}, skipping", snapshotFile);
       }
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/readers/LazyRow.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/readers/LazyRow.java
index 4f05ae96f6e..11a491ac0d4 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/readers/LazyRow.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/readers/LazyRow.java
@@ -91,6 +91,7 @@ public class LazyRow {
   public void clear() {
     _fieldToValueMap.clear();
     _nullValueFields.clear();
+    _segment = null;
   }
 
   public Set<String> getColumnNames() {
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManager.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManager.java
index 1c9975da3f9..1381e4e2ab0 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManager.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManager.java
@@ -592,6 +592,8 @@ public abstract class BasePartitionUpsertMetadataManager implements PartitionUps
         }
       }
       _trackedSegments.remove(oldSegment);
+      // Remove the segment eagerly so we need not wait until next snapshot cycle to remove replaced segment
+      _updatedSegmentsSinceLastSnapshot.remove(oldSegment);
     } finally {
       finishOperation();
     }
@@ -767,6 +769,8 @@ public abstract class BasePartitionUpsertMetadataManager implements PartitionUps
         doRemoveSegment(segment);
       }
       _trackedSegments.remove(segment);
+      // Remove the segment eagerly so we need not wait until next snapshot cycle to remove dropped segment
+      _updatedSegmentsSinceLastSnapshot.remove(segment);
     } finally {
       finishOperation();
     }
@@ -961,26 +965,25 @@ public abstract class BasePartitionUpsertMetadataManager implements PartitionUps
           segmentsWithoutSnapshot.add(immutableSegment);
           continue;
         }
-        ThreadSafeMutableRoaringBitmap queryableDocIdsBitMap = null;
-        ThreadSafeMutableRoaringBitmap validDocIdsBitMap =
-            immutableSegment.getValidDocIds() == null ? new ThreadSafeMutableRoaringBitmap()
-                : immutableSegment.getValidDocIds();
-        immutableSegment.persistDocIdsSnapshot(V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME,
-            validDocIdsBitMap);
+        ThreadSafeMutableRoaringBitmap validDocIds = immutableSegment.getValidDocIds();
+        // NOTE: Segment out of TTL without snapshot might have null validDocIds
+        if (validDocIds != null) {
+          ThreadSafeMutableRoaringBitmap.CardinalityAndBytes validDocIdsSnapshot = validDocIds.getBytesAndCardinality();
+          immutableSegment.persistDocIdsSnapshot(V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME, validDocIdsSnapshot);
+          numPrimaryKeysInSnapshot += validDocIdsSnapshot.getCardinality();
+        }
         if (_deleteRecordColumn != null) {
-          queryableDocIdsBitMap =
-              immutableSegment.getQueryableDocIds() == null ? new ThreadSafeMutableRoaringBitmap()
-                  : immutableSegment.getQueryableDocIds();
-          immutableSegment.persistDocIdsSnapshot(V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME,
-              queryableDocIdsBitMap);
+          ThreadSafeMutableRoaringBitmap queryableDocIds = immutableSegment.getQueryableDocIds();
+          if (queryableDocIds != null) {
+            ThreadSafeMutableRoaringBitmap.CardinalityAndBytes queryableDocIdsSnapshot =
+                queryableDocIds.getBytesAndCardinality();
+            immutableSegment.persistDocIdsSnapshot(V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME,
+                queryableDocIdsSnapshot);
+            numQueryableDocIdsInSnapshot += queryableDocIdsSnapshot.getCardinality();
+          }
         }
         _updatedSegmentsSinceLastSnapshot.remove(segment);
         numImmutableSegments++;
-        numPrimaryKeysInSnapshot += validDocIdsBitMap.getMutableRoaringBitmap().getCardinality();
-        if (_deleteRecordColumn != null) {
-          numQueryableDocIdsInSnapshot +=
-              queryableDocIdsBitMap.getMutableRoaringBitmap().getCardinality();
-        }
       } catch (Exception e) {
         _logger.warn("Caught exception while taking snapshot for segment: {}, skipping", segmentName, e);
         isSegmentSkipped = true;
@@ -990,8 +993,8 @@ public abstract class BasePartitionUpsertMetadataManager implements PartitionUps
     }
     // If we have skipped any segments in the previous for-loop, we should skip the next for-loop, basically to not
     // add new snapshot files on disk. This ensures all the validDocIds & queryable docIds snapshots kept on disk are
-    // still disjoint
-    // with each other, although some of them may have become stale, i.e. tracking more valid docs than expected.
+    // still disjoint with each other, although some of them may have become stale, i.e. tracking more valid docs than
+    // expected.
     if (!isSegmentSkipped) {
       for (ImmutableSegmentImpl segment : segmentsWithoutSnapshot) {
         String segmentName = segment.getSegmentName();
@@ -1003,22 +1006,25 @@ public abstract class BasePartitionUpsertMetadataManager implements PartitionUps
           continue;
         }
         try {
-          ThreadSafeMutableRoaringBitmap segmentQueryableDocIdsBitMap = null;
-          ThreadSafeMutableRoaringBitmap segmentValidDocIdsBitMap =
-              segment.getValidDocIds() == null ? new ThreadSafeMutableRoaringBitmap() : segment.getValidDocIds();
-          segment.persistDocIdsSnapshot(V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME, segmentValidDocIdsBitMap);
+          ThreadSafeMutableRoaringBitmap validDocIds = segment.getValidDocIds();
+          // NOTE: Segment out of TTL without snapshot might have null validDocIds
+          if (validDocIds != null) {
+            ThreadSafeMutableRoaringBitmap.CardinalityAndBytes validDocIdsSnapshot =
+                validDocIds.getBytesAndCardinality();
+            segment.persistDocIdsSnapshot(V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME, validDocIdsSnapshot);
+            numPrimaryKeysInSnapshot += validDocIdsSnapshot.getCardinality();
+          }
           if (_deleteRecordColumn != null) {
-            segmentQueryableDocIdsBitMap = segment.getQueryableDocIds() == null ? new ThreadSafeMutableRoaringBitmap()
-                : segment.getQueryableDocIds();
-            segment.persistDocIdsSnapshot(V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME,
-                segmentQueryableDocIdsBitMap);
+            ThreadSafeMutableRoaringBitmap queryableDocIds = segment.getQueryableDocIds();
+            if (queryableDocIds != null) {
+              ThreadSafeMutableRoaringBitmap.CardinalityAndBytes queryableDocIdsSnapshot =
+                  queryableDocIds.getBytesAndCardinality();
+              segment.persistDocIdsSnapshot(V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME, queryableDocIdsSnapshot);
+              numQueryableDocIdsInSnapshot += queryableDocIdsSnapshot.getCardinality();
+            }
           }
           _updatedSegmentsSinceLastSnapshot.remove(segment);
           numImmutableSegments++;
-          numPrimaryKeysInSnapshot += segmentValidDocIdsBitMap.getMutableRoaringBitmap().getCardinality();
-          if (_deleteRecordColumn != null) {
-            numQueryableDocIdsInSnapshot += segmentQueryableDocIdsBitMap.getMutableRoaringBitmap().getCardinality();
-          }
         } catch (Exception e) {
           _logger.warn("Caught exception while taking snapshot for segment: {} w/o snapshot, skipping", segmentName, e);
         } finally {
@@ -1035,8 +1041,9 @@ public abstract class BasePartitionUpsertMetadataManager implements PartitionUps
     }
     updateSnapshotMetrics(numImmutableSegments, numPrimaryKeysInSnapshot, numQueryableDocIdsInSnapshot,
         numTrackedSegments, numConsumingSegments, numUnchangedSegments);
-    _logger.info("Finished taking snapshot for {} immutable segments with {} primary keys (out of {} total segments, "
-            + "{} are consuming segments) in {} ms", numImmutableSegments, numPrimaryKeysInSnapshot, numTrackedSegments,
+    _logger.info("Finished taking snapshot for {} immutable segments with {} ({} queryable) primary keys "
+            + "(out of {} total segments, {} are consuming segments) in {} ms", numImmutableSegments,
+        numPrimaryKeysInSnapshot, numQueryableDocIdsInSnapshot, numTrackedSegments,
         numConsumingSegments, System.currentTimeMillis() - startTimeMs);
   }
 
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManager.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManager.java
index be9c0b17307..510304c1968 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManager.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManager.java
@@ -429,9 +429,13 @@ public class ConcurrentMapPartitionUpsertMetadataManager extends BasePartitionUp
             ThreadSafeMutableRoaringBitmap currentQueryableDocIds = currentSegment.getQueryableDocIds();
             int currentDocId = recordLocation.getDocId();
             if (currentQueryableDocIds == null || currentQueryableDocIds.contains(currentDocId)) {
-              _reusePreviousRow.init(currentSegment, currentDocId);
-              _partialUpsertHandler.merge(_reusePreviousRow, record, _reuseMergeResultHolder);
-              _reuseMergeResultHolder.clear();
+              try {
+                _reusePreviousRow.init(currentSegment, currentDocId);
+                _partialUpsertHandler.merge(_reusePreviousRow, record, _reuseMergeResultHolder);
+              } finally {
+                _reuseMergeResultHolder.clear();
+                _reusePreviousRow.clear();
+              }
             }
           }
           return recordLocation;
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManagerForConsistentDeletes.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManagerForConsistentDeletes.java
index d21120a0450..d17ad0c4b15 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManagerForConsistentDeletes.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/ConcurrentMapPartitionUpsertMetadataManagerForConsistentDeletes.java
@@ -563,9 +563,13 @@ public class ConcurrentMapPartitionUpsertMetadataManagerForConsistentDeletes
             ThreadSafeMutableRoaringBitmap currentQueryableDocIds = currentSegment.getQueryableDocIds();
             int currentDocId = recordLocation.getDocId();
             if (currentQueryableDocIds == null || currentQueryableDocIds.contains(currentDocId)) {
-              _reusePreviousRow.init(currentSegment, currentDocId);
-              _partialUpsertHandler.merge(_reusePreviousRow, record, _reuseMergeResultHolder);
-              _reuseMergeResultHolder.clear();
+              try {
+                _reusePreviousRow.init(currentSegment, currentDocId);
+                _partialUpsertHandler.merge(_reusePreviousRow, record, _reuseMergeResultHolder);
+              } finally {
+                _reuseMergeResultHolder.clear();
+                _reusePreviousRow.clear();
+              }
             }
           }
           return recordLocation;
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManagerTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManagerTest.java
index 8435d013978..aefd1cfc895 100644
--- a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManagerTest.java
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/BasePartitionUpsertMetadataManagerTest.java
@@ -117,21 +117,21 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), null);
     upsertMetadataManager.addSegment(seg01);
     // seg01 has a tmp snapshot file, but no snapshot file
     FileUtils.touch(new File(segDir01, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), null);
     upsertMetadataManager.addSegment(seg02);
     // seg02 has snapshot file, so its snapshot is taken first.
     FileUtils.touch(new File(segDir02, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), null);
     upsertMetadataManager.addSegment(seg03);
 
@@ -178,21 +178,21 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), null);
     upsertMetadataManager.addSegment(seg01);
     // seg01 has a tmp snapshot file, but no snapshot file
     FileUtils.touch(new File(segDir01, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), null);
     upsertMetadataManager.addSegment(seg02);
     // seg02 has snapshot file, so its snapshot is taken first.
     FileUtils.touch(new File(segDir02, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), null);
     upsertMetadataManager.addSegment(seg03);
 
@@ -253,21 +253,21 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), null);
     upsertMetadataManager.addSegment(seg01);
     // seg01 has a tmp snapshot file, but no snapshot file
     FileUtils.touch(new File(segDir01, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), null);
     upsertMetadataManager.addSegment(seg02);
     // seg02 has snapshot file, so its snapshot is taken first.
     FileUtils.touch(new File(segDir02, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), null);
     // just track it but not mark it as updated.
     upsertMetadataManager.trackSegment(seg03);
@@ -309,7 +309,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), null);
     // addSegment() would track seg, and mark it as updated for snapshotting.
     upsertMetadataManager.addSegment(seg01);
@@ -317,14 +317,14 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir01, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), null);
     upsertMetadataManager.addSegment(seg02);
     // seg02 has snapshot file, so its snapshot is taken first.
     FileUtils.touch(new File(segDir02, V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), null);
     upsertMetadataManager.addSegment(seg03);
 
@@ -441,7 +441,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds01 = createDocIds(0, 1, 2); // Some docs excluded due to deletes
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), queryableDocIds01);
     upsertMetadataManager.trackSegment(seg01);
@@ -451,7 +451,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir01, V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds02 = createDocIds(0, 2, 3, 5); // Some docs excluded due to deletes
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), queryableDocIds02);
     upsertMetadataManager.trackSegment(seg02);
@@ -461,7 +461,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir02, V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds03 = createDocIds(3, 7); // Some docs excluded due to deletes
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), queryableDocIds03);
     upsertMetadataManager.trackSegment(seg03);
@@ -525,7 +525,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds01 = createDocIds(0, 1, 2); // Some docs excluded due to deletes
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), queryableDocIds01);
     upsertMetadataManager.trackSegment(seg01);
@@ -535,7 +535,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir01, V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds02 = createDocIds(0, 2, 3, 5); // Some docs excluded due to deletes
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), queryableDocIds02);
     upsertMetadataManager.trackSegment(seg02);
@@ -545,7 +545,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir02, V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds03 = createDocIds(3, 7); // Some docs excluded due to deletes
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), queryableDocIds03);
     // just track it but not mark it as updated.
@@ -587,7 +587,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     List<String> segmentsTakenSnapshot = new ArrayList<>();
 
     File segDir01 = new File(TEMP_DIR, "seg01");
-    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg01 = createImmutableSegment("seg01", segDir01, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds01 = createDocIds(0, 1, 2); // Some docs excluded due to deletes
     seg01.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3), queryableDocIds01);
     // addSegment() would track seg, and mark it as updated for snapshotting.
@@ -598,7 +598,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir01, V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME + "_tmp"));
 
     File segDir02 = new File(TEMP_DIR, "seg02");
-    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg02 = createImmutableSegment("seg02", segDir02, segmentsTakenSnapshot, null);
     ThreadSafeMutableRoaringBitmap queryableDocIds02 = createDocIds(0, 2, 3, 5); // Some docs excluded due to deletes
     seg02.enableUpsert(upsertMetadataManager, createDocIds(0, 1, 2, 3, 4, 5), queryableDocIds02);
     upsertMetadataManager.trackSegment(seg02);
@@ -608,7 +608,7 @@ public class BasePartitionUpsertMetadataManagerTest {
     FileUtils.touch(new File(segDir02, V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME));
 
     File segDir03 = new File(TEMP_DIR, "seg03");
-    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, new ArrayList<>());
+    ImmutableSegmentImpl seg03 = createImmutableSegment("seg03", segDir03, segmentsTakenSnapshot, null);
     // seg03 has all documents queryable initially but then loses them due to deletes
     ThreadSafeMutableRoaringBitmap queryableDocIds03 = new ThreadSafeMutableRoaringBitmap(); // Empty due to all deletes
     seg03.enableUpsert(upsertMetadataManager, createDocIds(3, 4, 7), queryableDocIds03);
@@ -981,21 +981,23 @@ public class BasePartitionUpsertMetadataManagerTest {
   }
 
   private static ImmutableSegmentImpl createImmutableSegment(String segName, File segDir,
-      List<String> segmentsTakenSnapshot, List<String> queryableDocIdsSegmentsTaken)
+      List<String> segmentsTakenSnapshot, @Nullable List<String> queryableDocIdsSegmentsTaken)
       throws IOException {
     FileUtils.forceMkdir(segDir);
     SegmentMetadataImpl meta = mock(SegmentMetadataImpl.class);
     when(meta.getName()).thenReturn(segName);
     when(meta.getIndexDir()).thenReturn(segDir);
     return new ImmutableSegmentImpl(mock(SegmentDirectory.class), meta, new HashMap<>(), null) {
-      public void persistDocIdsSnapshot(String fileName, ThreadSafeMutableRoaringBitmap docIds) {
+      public void persistDocIdsSnapshot(String fileName,
+          ThreadSafeMutableRoaringBitmap.CardinalityAndBytes docIdsSnapshot)
+          throws IOException {
         if (V1Constants.VALID_DOC_IDS_SNAPSHOT_FILE_NAME.equals(fileName)) {
           segmentsTakenSnapshot.add(segName);
         } else if (V1Constants.QUERYABLE_DOC_IDS_SNAPSHOT_FILE_NAME.equals(fileName)
             && queryableDocIdsSegmentsTaken != null) {
           queryableDocIdsSegmentsTaken.add(segName);
         }
-        super.persistDocIdsSnapshot(fileName, docIds);
+        super.persistDocIdsSnapshot(fileName, docIdsSnapshot);
       }
     };
   }
diff --git a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java
index 470913fd4ce..1abe35a3b49 100644
--- a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java
+++ b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.segment.spi.index.mutable;
 
+import java.nio.ByteBuffer;
 import org.roaringbitmap.buffer.MutableRoaringBitmap;
 
 
@@ -57,11 +58,51 @@ public class ThreadSafeMutableRoaringBitmap {
     _mutableRoaringBitmap.add(newDocId);
   }
 
+  public synchronized boolean isEmpty() {
+    return _mutableRoaringBitmap.isEmpty();
+  }
+
+  public synchronized int getCardinality() {
+    return _mutableRoaringBitmap.getCardinality();
+  }
+
   public synchronized MutableRoaringBitmap getMutableRoaringBitmap() {
     return _mutableRoaringBitmap.clone();
   }
 
-  public synchronized boolean isEmpty() {
-    return _mutableRoaringBitmap.isEmpty();
+  /// Returns a point-in-time snapshot of the bitmap as a serialized byte array.
+  /// This avoids cloning the full object clone() unlike in getMutableRoaringBitmap()
+  public synchronized byte[] getBytes() {
+    return serialize();
+  }
+
+  /// Returns a consistent point-in-time snapshot containing both cardinality and serialized bytes captured under a
+  /// single lock.
+  public synchronized CardinalityAndBytes getBytesAndCardinality() {
+    return new CardinalityAndBytes(_mutableRoaringBitmap.getCardinality(), serialize());
+  }
+
+  private byte[] serialize() {
+    byte[] bytes = new byte[_mutableRoaringBitmap.serializedSizeInBytes()];
+    _mutableRoaringBitmap.serialize(ByteBuffer.wrap(bytes));
+    return bytes;
+  }
+
+  public static final class CardinalityAndBytes {
+    private final int _cardinality;
+    private final byte[] _bytes;
+
+    public CardinalityAndBytes(int cardinality, byte[] bytes) {
+      _cardinality = cardinality;
+      _bytes = bytes;
+    }
+
+    public int getCardinality() {
+      return _cardinality;
+    }
+
+    public byte[] getBytes() {
+      return _bytes;
+    }
   }
 }


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


(pinot) 01/25: Use BytesDeserializer for Kafka record keys to preserve binary key format (#17899)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 9fccc7ce08e185cba7438327ed8dd4bb8350a840
Author: NOOB <43...@users.noreply.github.com>
AuthorDate: Wed Mar 18 23:57:25 2026 +0530

    Use BytesDeserializer for Kafka record keys to preserve binary key format (#17899)
---
 .../KafkaPartitionLevelConnectionHandler.java       | 11 +++++------
 .../stream/kafka30/KafkaPartitionLevelConsumer.java | 13 ++++++-------
 .../kafka30/KafkaPartitionLevelConsumerTest.java    | 21 ++++++++++++---------
 .../KafkaPartitionLevelConnectionHandler.java       | 11 +++++------
 .../stream/kafka40/KafkaPartitionLevelConsumer.java | 13 ++++++-------
 .../kafka40/KafkaPartitionLevelConsumerTest.java    | 21 ++++++++++++---------
 6 files changed, 46 insertions(+), 44 deletions(-)

diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConnectionHandler.java b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConnectionHandler.java
index c469cc75e48..ffa36d3c06c 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConnectionHandler.java
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConnectionHandler.java
@@ -36,7 +36,6 @@ import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.serialization.BytesDeserializer;
-import org.apache.kafka.common.serialization.StringDeserializer;
 import org.apache.kafka.common.utils.Bytes;
 import org.apache.pinot.plugin.stream.kafka.KafkaAdminClientManager;
 import org.apache.pinot.plugin.stream.kafka.KafkaPartitionLevelStreamConfig;
@@ -63,7 +62,7 @@ public abstract class KafkaPartitionLevelConnectionHandler {
   protected final String _clientId;
   protected final int _partition;
   protected final String _topic;
-  protected final Consumer<String, Bytes> _consumer;
+  protected final Consumer<Bytes, Bytes> _consumer;
   protected final TopicPartition _topicPartition;
   protected final Properties _consumerProp;
   protected volatile KafkaAdminClientManager.AdminClientReference _sharedAdminClientRef;
@@ -93,7 +92,7 @@ public abstract class KafkaPartitionLevelConnectionHandler {
     Properties consumerProp = new Properties();
     consumerProp.putAll(streamConfig.getStreamConfigsMap());
     consumerProp.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, _config.getBootstrapHosts());
-    consumerProp.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+    consumerProp.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class.getName());
     consumerProp.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class.getName());
     if (_config.getKafkaIsolationLevel() != null) {
       consumerProp.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, _config.getKafkaIsolationLevel());
@@ -120,8 +119,8 @@ public abstract class KafkaPartitionLevelConnectionHandler {
     return filteredProps;
   }
 
-  private Consumer<String, Bytes> createConsumer(Properties consumerProp, RetryPolicy retryPolicy) {
-    AtomicReference<Consumer<String, Bytes>> consumer = new AtomicReference<>();
+  private Consumer<Bytes, Bytes> createConsumer(Properties consumerProp, RetryPolicy retryPolicy) {
+    AtomicReference<Consumer<Bytes, Bytes>> consumer = new AtomicReference<>();
     try {
       retryPolicy.attempt(() -> {
         try {
@@ -140,7 +139,7 @@ public abstract class KafkaPartitionLevelConnectionHandler {
   }
 
   @VisibleForTesting
-  protected Consumer<String, Bytes> createConsumer(Properties consumerProp) {
+  protected Consumer<Bytes, Bytes> createConsumer(Properties consumerProp) {
     return retry(() -> new KafkaConsumer<>(filterKafkaProperties(consumerProp, CONSUMER_CONFIG_NAMES)), 5);
   }
 
diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumer.java b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumer.java
index 262b8a7996e..a91545dd6f8 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumer.java
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/main/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumer.java
@@ -18,7 +18,6 @@
  */
 package org.apache.pinot.plugin.stream.kafka30;
 
-import java.nio.charset.StandardCharsets;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.List;
@@ -71,8 +70,8 @@ public class KafkaPartitionLevelConsumer extends KafkaPartitionLevelConnectionHa
       _consumer.seek(_topicPartition, startOffset);
     }
 
-    ConsumerRecords<String, Bytes> consumerRecords = _consumer.poll(Duration.ofMillis(timeoutMs));
-    List<ConsumerRecord<String, Bytes>> records = consumerRecords.records(_topicPartition);
+    ConsumerRecords<Bytes, Bytes> consumerRecords = _consumer.poll(Duration.ofMillis(timeoutMs));
+    List<ConsumerRecord<Bytes, Bytes>> records = consumerRecords.records(_topicPartition);
     List<BytesStreamMessage> filteredRecords = new ArrayList<>(records.size());
     long firstOffset = -1;
     long offsetOfNextBatch = startOffset;
@@ -82,12 +81,12 @@ public class KafkaPartitionLevelConsumer extends KafkaPartitionLevelConnectionHa
       firstOffset = records.get(0).offset();
       _lastFetchedOffset = records.get(records.size() - 1).offset();
       offsetOfNextBatch = _lastFetchedOffset + 1;
-      for (ConsumerRecord<String, Bytes> record : records) {
+      for (ConsumerRecord<Bytes, Bytes> record : records) {
         StreamMessageMetadata messageMetadata = extractMessageMetadata(record);
         Bytes message = record.value();
         if (message != null) {
-          String key = record.key();
-          byte[] keyBytes = key != null ? key.getBytes(StandardCharsets.UTF_8) : null;
+          Bytes key = record.key();
+          byte[] keyBytes = key != null ? key.get() : null;
           filteredRecords.add(new BytesStreamMessage(keyBytes, message.get(), messageMetadata));
           if (messageMetadata.getRecordSerializedSize() > 0) {
             batchSizeInBytes += messageMetadata.getRecordSerializedSize();
@@ -111,7 +110,7 @@ public class KafkaPartitionLevelConsumer extends KafkaPartitionLevelConnectionHa
         hasDataLoss, batchSizeInBytes);
   }
 
-  private StreamMessageMetadata extractMessageMetadata(ConsumerRecord<String, Bytes> record) {
+  private StreamMessageMetadata extractMessageMetadata(ConsumerRecord<Bytes, Bytes> record) {
     long timestamp = record.timestamp();
     long offset = record.offset();
 
diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/test/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumerTest.java b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/test/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumerTest.java
index 38423b0de4a..96afe08e070 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/test/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumerTest.java
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-3.0/src/test/java/org/apache/pinot/plugin/stream/kafka30/KafkaPartitionLevelConsumerTest.java
@@ -520,20 +520,23 @@ public class KafkaPartitionLevelConsumerTest {
       }
 
       @Override
-      protected Consumer<String, Bytes> createConsumer(Properties consumerProp) {
-        Consumer<String, Bytes> mockConsumer = mock(Consumer.class);
+      protected Consumer<Bytes, Bytes> createConsumer(Properties consumerProp) {
+        Consumer<Bytes, Bytes> mockConsumer = mock(Consumer.class);
         // Mock records
-        ConsumerRecord<String, Bytes> record1 =
+        ConsumerRecord<Bytes, Bytes> record1 =
             new ConsumerRecord<>("test-topic", 0, 0L, NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE, NULL_CHECKSUM, 4,
-                5, "key1", new Bytes("value1".getBytes(StandardCharsets.UTF_8)));
-        ConsumerRecord<String, Bytes> record2 =
+                5, new Bytes("key1".getBytes(StandardCharsets.UTF_8)),
+                new Bytes("value1".getBytes(StandardCharsets.UTF_8)));
+        ConsumerRecord<Bytes, Bytes> record2 =
             new ConsumerRecord<>("test-topic", 0, 0L, NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE, NULL_CHECKSUM, 4,
-                9, "key2", new Bytes("value2".getBytes(StandardCharsets.UTF_8)));
-        ConsumerRecord<String, Bytes> record3 =
+                9, new Bytes("key2".getBytes(StandardCharsets.UTF_8)),
+                new Bytes("value2".getBytes(StandardCharsets.UTF_8)));
+        ConsumerRecord<Bytes, Bytes> record3 =
             new ConsumerRecord<>("test-topic", 0, 0L, NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE, NULL_CHECKSUM, 4,
-                -1, "key2", new Bytes("value2".getBytes(StandardCharsets.UTF_8)));
+                -1, new Bytes("key2".getBytes(StandardCharsets.UTF_8)),
+                new Bytes("value2".getBytes(StandardCharsets.UTF_8)));
         // Mock return of poll()
-        ConsumerRecords<String, Bytes> consumerRecords = new ConsumerRecords<>(
+        ConsumerRecords<Bytes, Bytes> consumerRecords = new ConsumerRecords<>(
             Map.of(topicPartition, List.of(record1, record2, record3))
         );
         when(mockConsumer.poll(any(Duration.class))).thenReturn(consumerRecords);
diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConnectionHandler.java b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConnectionHandler.java
index 36c24f43771..ae5d8b753b0 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConnectionHandler.java
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConnectionHandler.java
@@ -36,7 +36,6 @@ import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.serialization.BytesDeserializer;
-import org.apache.kafka.common.serialization.StringDeserializer;
 import org.apache.kafka.common.utils.Bytes;
 import org.apache.pinot.plugin.stream.kafka.KafkaAdminClientManager;
 import org.apache.pinot.plugin.stream.kafka.KafkaPartitionLevelStreamConfig;
@@ -63,7 +62,7 @@ public abstract class KafkaPartitionLevelConnectionHandler {
   protected final String _clientId;
   protected final int _partition;
   protected final String _topic;
-  protected final Consumer<String, Bytes> _consumer;
+  protected final Consumer<Bytes, Bytes> _consumer;
   protected final TopicPartition _topicPartition;
   protected final Properties _consumerProp;
   protected volatile KafkaAdminClientManager.AdminClientReference _sharedAdminClientRef;
@@ -93,7 +92,7 @@ public abstract class KafkaPartitionLevelConnectionHandler {
     Properties consumerProp = new Properties();
     consumerProp.putAll(streamConfig.getStreamConfigsMap());
     consumerProp.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, _config.getBootstrapHosts());
-    consumerProp.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+    consumerProp.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class.getName());
     consumerProp.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class.getName());
     if (_config.getKafkaIsolationLevel() != null) {
       consumerProp.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, _config.getKafkaIsolationLevel());
@@ -120,8 +119,8 @@ public abstract class KafkaPartitionLevelConnectionHandler {
     return filteredProps;
   }
 
-  private Consumer<String, Bytes> createConsumer(Properties consumerProp, RetryPolicy retryPolicy) {
-    AtomicReference<Consumer<String, Bytes>> consumer = new AtomicReference<>();
+  private Consumer<Bytes, Bytes> createConsumer(Properties consumerProp, RetryPolicy retryPolicy) {
+    AtomicReference<Consumer<Bytes, Bytes>> consumer = new AtomicReference<>();
     try {
       retryPolicy.attempt(() -> {
         try {
@@ -140,7 +139,7 @@ public abstract class KafkaPartitionLevelConnectionHandler {
   }
 
   @VisibleForTesting
-  protected Consumer<String, Bytes> createConsumer(Properties consumerProp) {
+  protected Consumer<Bytes, Bytes> createConsumer(Properties consumerProp) {
     return retry(() -> new KafkaConsumer<>(filterKafkaProperties(consumerProp, CONSUMER_CONFIG_NAMES)), 5);
   }
 
diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumer.java b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumer.java
index 589736ef444..e5d28be8031 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumer.java
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/main/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumer.java
@@ -18,7 +18,6 @@
  */
 package org.apache.pinot.plugin.stream.kafka40;
 
-import java.nio.charset.StandardCharsets;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.List;
@@ -71,8 +70,8 @@ public class KafkaPartitionLevelConsumer extends KafkaPartitionLevelConnectionHa
       _consumer.seek(_topicPartition, startOffset);
     }
 
-    ConsumerRecords<String, Bytes> consumerRecords = _consumer.poll(Duration.ofMillis(timeoutMs));
-    List<ConsumerRecord<String, Bytes>> records = consumerRecords.records(_topicPartition);
+    ConsumerRecords<Bytes, Bytes> consumerRecords = _consumer.poll(Duration.ofMillis(timeoutMs));
+    List<ConsumerRecord<Bytes, Bytes>> records = consumerRecords.records(_topicPartition);
     List<BytesStreamMessage> filteredRecords = new ArrayList<>(records.size());
     long firstOffset = -1;
     long offsetOfNextBatch = startOffset;
@@ -82,12 +81,12 @@ public class KafkaPartitionLevelConsumer extends KafkaPartitionLevelConnectionHa
       firstOffset = records.get(0).offset();
       _lastFetchedOffset = records.get(records.size() - 1).offset();
       offsetOfNextBatch = _lastFetchedOffset + 1;
-      for (ConsumerRecord<String, Bytes> record : records) {
+      for (ConsumerRecord<Bytes, Bytes> record : records) {
         StreamMessageMetadata messageMetadata = extractMessageMetadata(record);
         Bytes message = record.value();
         if (message != null) {
-          String key = record.key();
-          byte[] keyBytes = key != null ? key.getBytes(StandardCharsets.UTF_8) : null;
+          Bytes key = record.key();
+          byte[] keyBytes = key != null ? key.get() : null;
           filteredRecords.add(new BytesStreamMessage(keyBytes, message.get(), messageMetadata));
           if (messageMetadata.getRecordSerializedSize() > 0) {
             batchSizeInBytes += messageMetadata.getRecordSerializedSize();
@@ -111,7 +110,7 @@ public class KafkaPartitionLevelConsumer extends KafkaPartitionLevelConnectionHa
         hasDataLoss, batchSizeInBytes);
   }
 
-  private StreamMessageMetadata extractMessageMetadata(ConsumerRecord<String, Bytes> record) {
+  private StreamMessageMetadata extractMessageMetadata(ConsumerRecord<Bytes, Bytes> record) {
     long timestamp = record.timestamp();
     long offset = record.offset();
 
diff --git a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/test/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumerTest.java b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/test/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumerTest.java
index 34852964e6e..3584595f870 100644
--- a/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/test/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumerTest.java
+++ b/pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/src/test/java/org/apache/pinot/plugin/stream/kafka40/KafkaPartitionLevelConsumerTest.java
@@ -524,20 +524,23 @@ public class KafkaPartitionLevelConsumerTest {
       }
 
       @Override
-      protected Consumer<String, Bytes> createConsumer(Properties consumerProp) {
-        Consumer<String, Bytes> mockConsumer = mock(Consumer.class);
+      protected Consumer<Bytes, Bytes> createConsumer(Properties consumerProp) {
+        Consumer<Bytes, Bytes> mockConsumer = mock(Consumer.class);
         // Mock records using Kafka 4.x compatible constructor (headers cannot be null in Kafka 4.x)
-        ConsumerRecord<String, Bytes> record1 =
+        ConsumerRecord<Bytes, Bytes> record1 =
             new ConsumerRecord<>("test-topic", 0, 0L, NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE, 4,
-                5, "key1", new Bytes("value1".getBytes(StandardCharsets.UTF_8)), new RecordHeaders(), null);
-        ConsumerRecord<String, Bytes> record2 =
+                5, new Bytes("key1".getBytes(StandardCharsets.UTF_8)),
+                new Bytes("value1".getBytes(StandardCharsets.UTF_8)), new RecordHeaders(), null);
+        ConsumerRecord<Bytes, Bytes> record2 =
             new ConsumerRecord<>("test-topic", 0, 0L, NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE, 4,
-                9, "key2", new Bytes("value2".getBytes(StandardCharsets.UTF_8)), new RecordHeaders(), null);
-        ConsumerRecord<String, Bytes> record3 =
+                9, new Bytes("key2".getBytes(StandardCharsets.UTF_8)),
+                new Bytes("value2".getBytes(StandardCharsets.UTF_8)), new RecordHeaders(), null);
+        ConsumerRecord<Bytes, Bytes> record3 =
             new ConsumerRecord<>("test-topic", 0, 0L, NO_TIMESTAMP, TimestampType.NO_TIMESTAMP_TYPE, 4,
-                -1, "key2", new Bytes("value2".getBytes(StandardCharsets.UTF_8)), new RecordHeaders(), null);
+                -1, new Bytes("key2".getBytes(StandardCharsets.UTF_8)),
+                new Bytes("value2".getBytes(StandardCharsets.UTF_8)), new RecordHeaders(), null);
         // Mock return of poll()
-        ConsumerRecords<String, Bytes> consumerRecords = new ConsumerRecords<>(
+        ConsumerRecords<Bytes, Bytes> consumerRecords = new ConsumerRecords<>(
             Map.of(topicPartition, List.of(record1, record2, record3))
         );
         when(mockConsumer.poll(any(Duration.class))).thenReturn(consumerRecords);


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


(pinot) 20/25: Add dropRecordOnPartitionMismatch config to StreamIngestionConfig (#18066)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit fa4d759404521d10f1c782beda57ca830918ded2
Author: Xiaotian (Jackie) Jiang <17...@users.noreply.github.com>
AuthorDate: Thu Apr 2 00:36:32 2026 -0700

    Add dropRecordOnPartitionMismatch config to StreamIngestionConfig (#18066)
---
 .../realtime/RealtimeSegmentDataManager.java       |   5 +-
 .../indexsegment/mutable/MutableSegmentImpl.java   |  53 +++++----
 .../local/realtime/impl/RealtimeSegmentConfig.java |  17 ++-
 .../writer/StatelessRealtimeSegmentWriter.java     |   9 +-
 ...gmentImplDropRecordOnPartitionMismatchTest.java | 131 +++++++++++++++++++++
 .../mutable/MutableSegmentImplTestUtils.java       |  26 ++++
 .../table/ingestion/StreamIngestionConfig.java     |  12 ++
 7 files changed, 226 insertions(+), 27 deletions(-)

diff --git a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
index 8bf0a6c2f9b..871cc9ec8b3 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
@@ -1791,7 +1791,10 @@ public class RealtimeSegmentDataManager extends SegmentDataManager {
         .setPartitionUpsertMetadataManager(partitionUpsertMetadataManager)
         .setPartitionDedupMetadataManager(partitionDedupMetadataManager)
         .setConsumerDir(consumerDir)
-        .setTextIndexConfig(_tableConfig.getIndexingConfig().getMultiColumnTextIndexConfig());
+        .setTextIndexConfig(_tableConfig.getIndexingConfig().getMultiColumnTextIndexConfig())
+        .setDropRecordOnPartitionMismatch(ingestionConfig != null
+            && ingestionConfig.getStreamIngestionConfig() != null
+            && ingestionConfig.getStreamIngestionConfig().isDropRecordOnPartitionMismatch());
 
     // Create message decoder
     Set<String> fieldsToRead = IngestionUtils.getFieldsForRecordExtractor(_tableConfig, _schema);
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
index 7b50b1b3d52..7645967cf4e 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
@@ -155,6 +155,7 @@ public class MutableSegmentImpl implements MutableSegment {
   private final String _partitionColumn;
   private final PartitionFunction _partitionFunction;
   private final int _mainPartitionId; // partition id designated for this consuming segment
+  private final boolean _dropRecordOnPartitionMismatch;
   private final boolean _defaultNullHandlingEnabled;
   private final File _consumerDir;
 
@@ -248,6 +249,7 @@ public class MutableSegmentImpl implements MutableSegment {
     _partitionColumn = config.getPartitionColumn();
     _partitionFunction = config.getPartitionFunction();
     _mainPartitionId = config.getPartitionId();
+    _dropRecordOnPartitionMismatch = config.isDropRecordOnPartitionMismatch();
     _defaultNullHandlingEnabled = config.isNullHandlingEnabled();
     _consumerDir = new File(config.getConsumerDir());
 
@@ -624,8 +626,27 @@ public class MutableSegmentImpl implements MutableSegment {
   @Override
   public boolean index(GenericRow row, @Nullable StreamMessageMetadata metadata)
       throws IOException {
-    boolean canTakeMore;
-    int numDocsIndexed = _numDocsIndexed;
+    if (_partitionColumn != null) {
+      Object value = row.getValue(_partitionColumn);
+      Preconditions.checkState(value != null, "Failed to find value for partition column: %s", _partitionColumn);
+      IndexContainer indexContainer = _indexContainerMap.get(_partitionColumn);
+      String stringValue = indexContainer._fieldSpec.getDataType().toString(value);
+      int partition = _partitionFunction.getPartition(stringValue);
+      if (partition != _mainPartitionId) {
+        if (_serverMetrics != null) {
+          _serverMetrics.addMeteredTableValue(_realtimeTableName, ServerMeter.REALTIME_PARTITION_MISMATCH, 1);
+        }
+        if (_dropRecordOnPartitionMismatch) {
+          updateIndexedAndIngestionTime(metadata);
+          return true;
+        }
+        if (indexContainer._partitions.add(partition)) {
+          // for every partition other than mainPartitionId, log a warning once
+          _logger.warn("Found new partition: {} from partition column: {}, value: {}", partition, _partitionColumn,
+              stringValue);
+        }
+      }
+    }
 
     if (isDedupEnabled()) {
       DedupRecordInfo dedupRecordInfo = getDedupRecordInfo(row);
@@ -633,6 +654,7 @@ public class MutableSegmentImpl implements MutableSegment {
         if (_serverMetrics != null) {
           _serverMetrics.addMeteredTableValue(_realtimeTableName, ServerMeter.REALTIME_DEDUP_DROPPED, 1);
         }
+        updateIndexedAndIngestionTime(metadata);
         return true;
       }
     }
@@ -644,6 +666,8 @@ public class MutableSegmentImpl implements MutableSegment {
     // NOTE: We must do this before we index a single column to avoid partially indexing the row
     validateLengthOfMVColumns(row);
 
+    boolean canTakeMore;
+    int numDocsIndexed = _numDocsIndexed;
     if (isUpsertEnabled()) {
       RecordInfo recordInfo = getRecordInfo(row, numDocsIndexed);
       GenericRow updatedRow = _partitionUpsertMetadataManager.updateRecord(row, recordInfo);
@@ -704,7 +728,11 @@ public class MutableSegmentImpl implements MutableSegment {
       _numDocsIndexed = numDocsIndexed;
     }
 
-    // Update last indexed time and latest ingestion time
+    updateIndexedAndIngestionTime(metadata);
+    return canTakeMore;
+  }
+
+  private void updateIndexedAndIngestionTime(@Nullable StreamMessageMetadata metadata) {
     _lastIndexedTimeMs = System.currentTimeMillis();
     if (metadata != null) {
       _latestIngestionTimeMs = Math.max(_latestIngestionTimeMs, metadata.getRecordIngestionTimeMs());
@@ -713,8 +741,6 @@ public class MutableSegmentImpl implements MutableSegment {
       long ingestionLagMs = Math.max(0, _lastIndexedTimeMs - _latestIngestionTimeMs);
       _minimumIngestionLagMs = Math.min(_minimumIngestionLagMs, ingestionLagMs);
     }
-
-    return canTakeMore;
   }
 
   private boolean isUpsertEnabled() {
@@ -894,23 +920,6 @@ public class MutableSegmentImpl implements MutableSegment {
       DataType dataType = fieldSpec.getDataType();
 
       if (fieldSpec.isSingleValueField()) {
-        // Check partitions
-        if (column.equals(_partitionColumn)) {
-          String stringValue = dataType.toString(value);
-          int partition = _partitionFunction.getPartition(stringValue);
-          if (partition != _mainPartitionId) {
-            if (indexContainer._partitions.add(partition)) {
-              // for every partition other than mainPartitionId, log a warning once
-              _logger.warn("Found new partition: {} from partition column: {}, value: {}", partition, column,
-                  stringValue);
-            }
-            // always emit a metric when a partition other than mainPartitionId is detected
-            if (_serverMetrics != null) {
-              _serverMetrics.addMeteredTableValue(_realtimeTableName, ServerMeter.REALTIME_PARTITION_MISMATCH, 1);
-            }
-          }
-        }
-
         // Update numValues info
         indexContainer._valuesInfo.updateSVNumValues();
 
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/RealtimeSegmentConfig.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/RealtimeSegmentConfig.java
index 712e8ce5ffc..48738d240db 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/RealtimeSegmentConfig.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/RealtimeSegmentConfig.java
@@ -71,6 +71,7 @@ public class RealtimeSegmentConfig {
   private final String _consumerDir;
   @Nullable
   private final MultiColumnTextIndexConfig _multiColIndexConfig;
+  private final boolean _dropRecordOnPartitionMismatch;
 
   // TODO: Clean up this constructor. Most of these things can be extracted from tableConfig.
 
@@ -99,7 +100,8 @@ public class RealtimeSegmentConfig {
       @Nullable PartitionUpsertMetadataManager partitionUpsertMetadataManager,
       @Nullable PartitionDedupMetadataManager partitionDedupMetadataManager,
       String consumerDir,
-      @Nullable MultiColumnTextIndexConfig textIndexConfig) {
+      @Nullable MultiColumnTextIndexConfig textIndexConfig,
+      boolean dropRecordOnPartitionMismatch) {
     _tableNameWithType = tableNameWithType;
     _segmentName = segmentName;
     _streamName = streamName;
@@ -122,6 +124,7 @@ public class RealtimeSegmentConfig {
     _partitionDedupMetadataManager = partitionDedupMetadataManager;
     _consumerDir = consumerDir;
     _multiColIndexConfig = textIndexConfig;
+    _dropRecordOnPartitionMismatch = dropRecordOnPartitionMismatch;
   }
 
   public String getTableNameWithType() {
@@ -217,6 +220,10 @@ public class RealtimeSegmentConfig {
     return _multiColIndexConfig;
   }
 
+  public boolean isDropRecordOnPartitionMismatch() {
+    return _dropRecordOnPartitionMismatch;
+  }
+
   public static class Builder {
     private String _tableNameWithType;
     private String _segmentName;
@@ -244,6 +251,7 @@ public class RealtimeSegmentConfig {
     private PartitionDedupMetadataManager _partitionDedupMetadataManager;
     private String _consumerDir;
     private MultiColumnTextIndexConfig _textIndexConfig;
+    private boolean _dropRecordOnPartitionMismatch;
 
     public Builder() {
       _indexConfigByCol = new HashMap<>();
@@ -409,6 +417,11 @@ public class RealtimeSegmentConfig {
       return this;
     }
 
+    public Builder setDropRecordOnPartitionMismatch(boolean dropRecordOnPartitionMismatch) {
+      _dropRecordOnPartitionMismatch = dropRecordOnPartitionMismatch;
+      return this;
+    }
+
     public RealtimeSegmentConfig build() {
       Map<String, FieldIndexConfigs> indexConfigByCol = Maps.newHashMapWithExpectedSize(_indexConfigByCol.size());
       for (Map.Entry<String, FieldIndexConfigs.Builder> entry : _indexConfigByCol.entrySet()) {
@@ -419,7 +432,7 @@ public class RealtimeSegmentConfig {
           _capacity, _avgNumMultiValues, Collections.unmodifiableMap(indexConfigByCol), _segmentZKMetadata, _offHeap,
           _memoryManager, _statsHistory, _partitionColumn, _partitionFunction, _partitionId, _aggregateMetrics,
           _ingestionAggregationConfigs, _defaultNullHandlingEnabled, _partitionUpsertMetadataManager,
-          _partitionDedupMetadataManager, _consumerDir, _textIndexConfig);
+          _partitionDedupMetadataManager, _consumerDir, _textIndexConfig, _dropRecordOnPartitionMismatch);
     }
   }
 }
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
index cbece4ddd5b..c08af0b0ea2 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
@@ -49,6 +49,7 @@ import org.apache.pinot.spi.config.table.SegmentPartitionConfig;
 import org.apache.pinot.spi.config.table.SegmentZKPropsConfig;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.config.table.ingestion.IngestionConfig;
 import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.data.readers.GenericRow;
 import org.apache.pinot.spi.plugin.PluginManager;
@@ -180,6 +181,7 @@ public class StatelessRealtimeSegmentWriter implements Closeable {
     RealtimeSegmentStatsHistory statsHistory = RealtimeSegmentStatsHistory.deserializeFrom(statsHistoryFile);
 
     // Initialize mutable segment with configurations
+    IngestionConfig ingestionConfig = _tableConfig.getIngestionConfig();
     RealtimeSegmentConfig.Builder realtimeSegmentConfigBuilder = new RealtimeSegmentConfig.Builder(indexLoadingConfig)
         .setTableNameWithType(_tableNameWithType)
         .setSegmentName(_segmentName)
@@ -191,7 +193,10 @@ public class StatelessRealtimeSegmentWriter implements Closeable {
         .setOffHeap(indexLoadingConfig.isRealtimeOffHeapAllocation())
         .setMemoryManager(new MmapMemoryManager(FileUtils.getTempDirectory().getAbsolutePath(), _segmentName, null))
         .setStatsHistory(statsHistory)
-        .setConsumerDir(_resourceDataDir.getAbsolutePath());
+        .setConsumerDir(_resourceDataDir.getAbsolutePath())
+        .setDropRecordOnPartitionMismatch(ingestionConfig != null
+            && ingestionConfig.getStreamIngestionConfig() != null
+            && ingestionConfig.getStreamIngestionConfig().isDropRecordOnPartitionMismatch());
 
     setPartitionParameters(realtimeSegmentConfigBuilder, _tableConfig.getIndexingConfig().getSegmentPartitionConfig());
 
@@ -395,7 +400,7 @@ public class StatelessRealtimeSegmentWriter implements Closeable {
    *  - partition group id
    */
   private void setPartitionParameters(RealtimeSegmentConfig.Builder realtimeSegmentConfigBuilder,
-      SegmentPartitionConfig segmentPartitionConfig) {
+      @Nullable SegmentPartitionConfig segmentPartitionConfig) {
     if (segmentPartitionConfig != null) {
       Map<String, ColumnPartitionConfig> columnPartitionMap = segmentPartitionConfig.getColumnPartitionMap();
       if (columnPartitionMap.size() == 1) {
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplDropRecordOnPartitionMismatchTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplDropRecordOnPartitionMismatchTest.java
new file mode 100644
index 00000000000..400788c1b2c
--- /dev/null
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplDropRecordOnPartitionMismatchTest.java
@@ -0,0 +1,131 @@
+/**
+ * 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.local.indexsegment.mutable;
+
+import java.io.IOException;
+import org.apache.pinot.segment.spi.partition.ModuloPartitionFunction;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+/// Tests for the [MutableSegmentImpl#index] behavior when `dropRecordOnPartitionMismatch` is enabled.
+public class MutableSegmentImplDropRecordOnPartitionMismatchTest {
+  private static final String PARTITION_COLUMN = "memberId";
+  private static final String VALUE_COLUMN = "teamId";
+
+  // Modulo partition function with 4 partitions; main partition is 0
+  private static final int NUM_PARTITIONS = 4;
+  private static final int MAIN_PARTITION_ID = 0;
+
+  private static final Schema SCHEMA = new Schema.SchemaBuilder()
+      .addSingleValueDimension(PARTITION_COLUMN, FieldSpec.DataType.INT)
+      .addSingleValueDimension(VALUE_COLUMN, FieldSpec.DataType.INT)
+      .build();
+
+  private MutableSegmentImpl _segment;
+
+  @AfterMethod
+  public void tearDown() {
+    if (_segment != null) {
+      _segment.destroy();
+      _segment = null;
+    }
+  }
+
+  @Test
+  public void testRecordsMatchingPartitionAreIndexed()
+      throws IOException {
+    _segment = MutableSegmentImplTestUtils.createMutableSegmentImpl(SCHEMA, PARTITION_COLUMN,
+        new ModuloPartitionFunction(NUM_PARTITIONS), MAIN_PARTITION_ID, true);
+
+    // memberId values 0, 4, 8 all map to partition 0
+    indexRow(_segment, 0, 100);
+    indexRow(_segment, 4, 101);
+    indexRow(_segment, 8, 102);
+
+    assertEquals(_segment.getNumDocsIndexed(), 3);
+  }
+
+  @Test
+  public void testRecordsMismatchingPartitionAreDropped()
+      throws IOException {
+    _segment = MutableSegmentImplTestUtils.createMutableSegmentImpl(SCHEMA, PARTITION_COLUMN,
+        new ModuloPartitionFunction(NUM_PARTITIONS), MAIN_PARTITION_ID, true);
+
+    // memberId values 1, 2, 3 map to partitions 1, 2, 3 — all mismatches
+    indexRow(_segment, 1, 200);
+    indexRow(_segment, 2, 201);
+    indexRow(_segment, 3, 202);
+
+    assertEquals(_segment.getNumDocsIndexed(), 0);
+  }
+
+  @Test
+  public void testMixedPartitionsOnlyIndexMatchingRecords()
+      throws IOException {
+    _segment = MutableSegmentImplTestUtils.createMutableSegmentImpl(SCHEMA, PARTITION_COLUMN,
+        new ModuloPartitionFunction(NUM_PARTITIONS), MAIN_PARTITION_ID, true);
+
+    indexRow(_segment, 0, 100);  // partition 0 — indexed
+    indexRow(_segment, 1, 101);  // partition 1 — dropped
+    indexRow(_segment, 4, 102);  // partition 0 — indexed
+    indexRow(_segment, 7, 103);  // partition 3 — dropped
+
+    assertEquals(_segment.getNumDocsIndexed(), 2);
+  }
+
+  @Test
+  public void testConfigDisabledIndexesAllRecordsRegardlessOfPartition()
+      throws IOException {
+    _segment = MutableSegmentImplTestUtils.createMutableSegmentImpl(SCHEMA, PARTITION_COLUMN,
+        new ModuloPartitionFunction(NUM_PARTITIONS), MAIN_PARTITION_ID, false);
+
+    indexRow(_segment, 0, 100);  // partition 0
+    indexRow(_segment, 1, 101);  // partition 1
+    indexRow(_segment, 2, 102);  // partition 2
+    indexRow(_segment, 3, 103);  // partition 3
+
+    assertEquals(_segment.getNumDocsIndexed(), 4);
+  }
+
+  @Test(expectedExceptions = IllegalStateException.class)
+  public void testNullPartitionColumnValueThrowsException()
+      throws IOException {
+    _segment = MutableSegmentImplTestUtils.createMutableSegmentImpl(SCHEMA, PARTITION_COLUMN,
+        new ModuloPartitionFunction(NUM_PARTITIONS), MAIN_PARTITION_ID, true);
+
+    GenericRow row = new GenericRow();
+    row.putValue(PARTITION_COLUMN, null);
+    row.putValue(VALUE_COLUMN, 999);
+    _segment.index(row, null);
+  }
+
+  private void indexRow(MutableSegmentImpl segment, int partitionColumnValue, int valueColumnValue)
+      throws IOException {
+    GenericRow row = new GenericRow();
+    row.putValue(PARTITION_COLUMN, partitionColumnValue);
+    row.putValue(VALUE_COLUMN, valueColumnValue);
+    segment.index(row, null);
+  }
+}
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTestUtils.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTestUtils.java
index d549b045fa9..eddc42718cf 100644
--- a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTestUtils.java
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTestUtils.java
@@ -34,6 +34,7 @@ import org.apache.pinot.segment.local.realtime.impl.RealtimeSegmentStatsHistory;
 import org.apache.pinot.segment.local.upsert.PartitionUpsertMetadataManager;
 import org.apache.pinot.segment.spi.index.DictionaryIndexConfig;
 import org.apache.pinot.segment.spi.index.StandardIndexes;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
 import org.apache.pinot.spi.config.table.IndexConfig;
 import org.apache.pinot.spi.config.table.JsonIndexConfig;
 import org.apache.pinot.spi.config.table.ingestion.AggregationConfig;
@@ -142,4 +143,29 @@ public class MutableSegmentImplTestUtils {
     RealtimeSegmentConfig realtimeSegmentConfig = segmentConfBuilder.build();
     return new MutableSegmentImpl(realtimeSegmentConfig, serverMetrics);
   }
+
+  public static MutableSegmentImpl createMutableSegmentImpl(Schema schema, String partitionColumn,
+      PartitionFunction partitionFunction, int partitionId, boolean dropRecordOnPartitionMismatch) {
+    RealtimeSegmentStatsHistory statsHistory = mock(RealtimeSegmentStatsHistory.class);
+    when(statsHistory.getEstimatedCardinality(anyString())).thenReturn(200);
+    when(statsHistory.getEstimatedAvgColSize(anyString())).thenReturn(32);
+
+    RealtimeSegmentConfig realtimeSegmentConfig = new RealtimeSegmentConfig.Builder()
+        .setTableNameWithType(TABLE_NAME_WITH_TYPE)
+        .setSegmentName(SEGMENT_NAME)
+        .setStreamName(STREAM_NAME)
+        .setSchema(schema)
+        .setCapacity(100000)
+        .setAvgNumMultiValues(2)
+        .setSegmentZKMetadata(new SegmentZKMetadata(SEGMENT_NAME))
+        .setMemoryManager(new DirectMemoryManager(SEGMENT_NAME))
+        .setStatsHistory(statsHistory)
+        .setPartitionColumn(partitionColumn)
+        .setPartitionFunction(partitionFunction)
+        .setPartitionId(partitionId)
+        .setDropRecordOnPartitionMismatch(dropRecordOnPartitionMismatch)
+        .setConsumerDir(TEMP_DIR.getAbsolutePath() + "/" + UUID.randomUUID() + "/consumerDir")
+        .build();
+    return new MutableSegmentImpl(realtimeSegmentConfig, null);
+  }
 }
diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/StreamIngestionConfig.java b/pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/StreamIngestionConfig.java
index dda082c80d2..2cc00498b0c 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/StreamIngestionConfig.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/config/table/ingestion/StreamIngestionConfig.java
@@ -62,6 +62,10 @@ public class StreamIngestionConfig extends BaseJsonConfig {
   @JsonPropertyDescription("Class to handle realtime offset auto reset")
   private String _realtimeOffsetAutoResetHandlerClass;
 
+  @JsonPropertyDescription("If true, drop records whose partition column value does not map to the segment's designated"
+      + " partition during realtime ingestion. Defaults to false.")
+  private boolean _dropRecordOnPartitionMismatch;
+
   @JsonCreator
   public StreamIngestionConfig(@JsonProperty("streamConfigMaps") List<Map<String, String>> streamConfigMaps) {
     _streamConfigMaps = streamConfigMaps;
@@ -136,4 +140,12 @@ public class StreamIngestionConfig extends BaseJsonConfig {
   public void setRealtimeOffsetAutoResetHandlerClass(String realtimeOffsetAutoResetHandlerClass) {
     _realtimeOffsetAutoResetHandlerClass = realtimeOffsetAutoResetHandlerClass;
   }
+
+  public boolean isDropRecordOnPartitionMismatch() {
+    return _dropRecordOnPartitionMismatch;
+  }
+
+  public void setDropRecordOnPartitionMismatch(boolean dropRecordOnPartitionMismatch) {
+    _dropRecordOnPartitionMismatch = dropRecordOnPartitionMismatch;
+  }
 }


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


(pinot) 22/25: Fix multi-controller race conditions in ResponseStoreCleaner cursor cleanup (#18113) (#487)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 68bd37ad6a1937fd8f1203fb3ca5a81e53b4d23f
Author: Yash Mayya <ya...@gmail.com>
AuthorDate: Wed Apr 8 07:23:45 2026 -0700

    Fix multi-controller race conditions in ResponseStoreCleaner cursor cleanup (#18113) (#487)
---
 .../org/apache/pinot/broker/cursors/FsResponseStore.java | 10 ++++++++--
 .../pinot/common/cursors/AbstractResponseStore.java      | 16 ++++++++++++++--
 .../pinot/controller/cursors/ResponseStoreCleaner.java   | 16 ++++++++++++++--
 3 files changed, 36 insertions(+), 6 deletions(-)

diff --git a/pinot-broker/src/main/java/org/apache/pinot/broker/cursors/FsResponseStore.java b/pinot-broker/src/main/java/org/apache/pinot/broker/cursors/FsResponseStore.java
index 8da7b0a33c8..9204e69d614 100644
--- a/pinot-broker/src/main/java/org/apache/pinot/broker/cursors/FsResponseStore.java
+++ b/pinot-broker/src/main/java/org/apache/pinot/broker/cursors/FsResponseStore.java
@@ -159,11 +159,17 @@ public class FsResponseStore extends AbstractResponseStore {
       throws Exception {
     PinotFS pinotFS = PinotFSFactory.create(_dataDir.getScheme());
     URI queryDir = combinePath(_dataDir, requestId);
-    if (pinotFS.exists(queryDir)) {
+    try {
       pinotFS.delete(queryDir, true);
       return true;
+    } catch (Exception e) {
+      // Directory may have been deleted concurrently. If it's gone, treat as success.
+      if (!pinotFS.exists(queryDir)) {
+        LOGGER.debug("Directory already deleted for requestId={} (likely concurrent deletion)", requestId);
+        return true;
+      }
+      throw e;
     }
-    return false;
   }
 
   @Override
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/cursors/AbstractResponseStore.java b/pinot-common/src/main/java/org/apache/pinot/common/cursors/AbstractResponseStore.java
index 2095d007aa9..14aea7bbf67 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/cursors/AbstractResponseStore.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/cursors/AbstractResponseStore.java
@@ -29,9 +29,12 @@ import org.apache.pinot.common.response.broker.ResultTable;
 import org.apache.pinot.spi.cursors.ResponseStore;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.TimeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 public abstract class AbstractResponseStore implements ResponseStore {
+  private static final Logger LOGGER = LoggerFactory.getLogger(AbstractResponseStore.class);
 
   protected String _brokerHost;
   protected int _brokerPort;
@@ -233,9 +236,18 @@ public abstract class AbstractResponseStore implements ResponseStore {
       return false;
     }
 
-    long bytesWritten = readResponse(requestId).getBytesWritten();
+    // Read bytesWritten for metrics tracking. The response may be deleted concurrently between exists() and
+    // readResponse() (TOCTOU race), so handle that gracefully.
+    long bytesWritten = 0;
+    try {
+      bytesWritten = readResponse(requestId).getBytesWritten();
+    } catch (Exception e) {
+      LOGGER.debug("Could not read response metadata for requestId={} (may have been deleted concurrently)",
+          requestId, e);
+    }
+
     boolean isSucceeded = deleteResponseImpl(requestId);
-    if (isSucceeded) {
+    if (isSucceeded && bytesWritten > 0) {
       _brokerMetrics.addMeteredGlobalValue(BrokerMeter.CURSOR_RESPONSE_STORE_SIZE, bytesWritten * -1);
     }
     return isSucceeded;
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java b/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
index b7bd65667d5..56cb0ba2824 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
@@ -63,6 +63,7 @@ import org.slf4j.LoggerFactory;
  */
 public class ResponseStoreCleaner extends ControllerPeriodicTask<Void> {
   private static final Logger LOGGER = LoggerFactory.getLogger(ResponseStoreCleaner.class);
+  private static final String TASK_NAME = "ResponseStoreCleaner";
   // Increased timeout to handle large response stores
   private static final int GET_TIMEOUT_MS = 60_000;
   private static final int DELETE_TIMEOUT_MS = 10_000;
@@ -78,7 +79,7 @@ public class ResponseStoreCleaner extends ControllerPeriodicTask<Void> {
   public ResponseStoreCleaner(ControllerConf config, PinotHelixResourceManager pinotHelixResourceManager,
       LeadControllerManager leadControllerManager, ControllerMetrics controllerMetrics, Executor executor,
       PoolingHttpClientConnectionManager connectionManager) {
-    super("ResponseStoreCleaner", getFrequencyInSeconds(config), getInitialDelayInSeconds(config),
+    super(TASK_NAME, getFrequencyInSeconds(config), getInitialDelayInSeconds(config),
         pinotHelixResourceManager, leadControllerManager, controllerMetrics);
     _controllerConf = config;
     _executor = executor;
@@ -112,6 +113,16 @@ public class ResponseStoreCleaner extends ControllerPeriodicTask<Void> {
     return frequencyInSeconds;
   }
 
+  /**
+   * Returns a singleton list with the task name as a pseudo-table so that the standard leadership gating in
+   * {@link ControllerPeriodicTask#runTask} ensures exactly one controller runs cleanup, independent of actual
+   * table distribution.
+   */
+  @Override
+  protected List<String> getTablesToProcess(Properties periodicTaskProperties) {
+    return List.of(TASK_NAME);
+  }
+
   @Override
   protected void processTables(List<String> tableNamesWithType, Properties periodicTaskProperties) {
     long cleanAtMs = System.currentTimeMillis();
@@ -226,7 +237,8 @@ public class ResponseStoreCleaner extends ControllerPeriodicTask<Void> {
     }
 
     if (!errMessages.isEmpty()) {
-      throw new RuntimeException("Some delete operations failed: " + StringUtils.join(errMessages, ", "));
+      LOGGER.warn("Some delete operations failed ({}): {}", errMessages.size(),
+          StringUtils.join(errMessages, ", "));
     }
     return responseMap;
   }


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


(pinot) 11/25: Add additional pruning step for Upsert Tables (#17898)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit f21c705d777ca71e41fa16d21af53b07e228ceb7
Author: Chaitanya Deepthi <45...@users.noreply.github.com>
AuthorDate: Thu Mar 19 13:16:30 2026 -0700

    Add additional pruning step for Upsert Tables (#17898)
    
    * Add additional pruning condition for Upsert Tables
    
    * Fix the no broker query options
    
    * Change the pruning to take in queryable docids as well
    
    * Change the code to reuse from Utility class
    
    * Checkstyle exceptions
---
 .../core/query/pruner/SegmentPrunerService.java    |  26 +++-
 .../query/pruner/SegmentPrunerServiceTest.java     | 145 +++++++++++++++++++++
 2 files changed, 166 insertions(+), 5 deletions(-)

diff --git a/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java b/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java
index a426cb7abea..084a00f9351 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java
@@ -25,11 +25,14 @@ import java.util.Map;
 import java.util.concurrent.ExecutorService;
 import java.util.function.BiConsumer;
 import javax.annotation.Nullable;
+import org.apache.pinot.common.utils.config.QueryOptionsUtils;
 import org.apache.pinot.core.query.config.SegmentPrunerConfig;
 import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.local.upsert.UpsertUtils;
 import org.apache.pinot.segment.spi.IndexSegment;
 import org.apache.pinot.spi.trace.InvocationScope;
 import org.apache.pinot.spi.trace.Tracing;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -105,7 +108,7 @@ public class SegmentPrunerService {
   public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query, SegmentPrunerStatistics stats,
       @Nullable ExecutorService executorService) {
     try (InvocationScope scope = Tracing.getTracer().createScope(SegmentPrunerService.class)) {
-      segments = removeEmptySegments(segments);
+      segments = removeEmptySegments(segments, query);
       int invokedPrunersCount = 0;
       for (SegmentPruner segmentPruner : _segmentPruners) {
         if (segmentPruner.isApplicableTo(query)) {
@@ -134,19 +137,32 @@ public class SegmentPrunerService {
    *
    * @param segments the list of segments to be pruned. This is a destructive operation that may modify this list in an
    *                 undefined way. Therefore, this list should not be used after calling this method.
+   * @param query    query context; when non-null and skipUpsert=true, segments with 0 queryable/valid docs are not
+   *                 treated as empty (they contribute replaced rows to the result). When queryable doc ids exist,
+   *                 emptiness is determined from them; otherwise {@link IndexSegment#getValidDocIds()} is used.
    * @return the new list with filtered elements. This is the list that have to be used.
    */
-  private static List<IndexSegment> removeEmptySegments(List<IndexSegment> segments) {
+  private static List<IndexSegment> removeEmptySegments(List<IndexSegment> segments, @Nullable QueryContext query) {
     int selected = 0;
     for (IndexSegment segment : segments) {
-      if (!isEmptySegment(segment)) {
+      if (!isEmptySegment(segment, query)) {
         segments.set(selected++, segment);
       }
     }
     return segments.subList(0, selected);
   }
 
-  private static boolean isEmptySegment(IndexSegment segment) {
-    return segment.getSegmentMetadata().getTotalDocs() == 0;
+  private static boolean isEmptySegment(IndexSegment segment, @Nullable QueryContext query) {
+    if (segment.getSegmentMetadata().getTotalDocs() == 0) {
+      return true;
+    }
+    // For upsert tables, treat segments with 0 docs to query as empty only when the query does not skip upsert.
+    // When skipUpsert=true, the query returns all docs (including replaced), so the segment contributes rows.
+    // Use query options map directly: _skipUpsert is only set on the server; the broker has options in the map.
+    if (query != null && query.getQueryOptions() != null && QueryOptionsUtils.isSkipUpsert(query.getQueryOptions())) {
+      return false;
+    }
+    MutableRoaringBitmap queryableDocIds = UpsertUtils.getQueryableDocIdsSnapshotFromSegment(segment);
+    return queryableDocIds != null && queryableDocIds.isEmpty();
   }
 }
diff --git a/pinot-core/src/test/java/org/apache/pinot/core/query/pruner/SegmentPrunerServiceTest.java b/pinot-core/src/test/java/org/apache/pinot/core/query/pruner/SegmentPrunerServiceTest.java
index c18c670c57c..93e382b4765 100644
--- a/pinot-core/src/test/java/org/apache/pinot/core/query/pruner/SegmentPrunerServiceTest.java
+++ b/pinot-core/src/test/java/org/apache/pinot/core/query/pruner/SegmentPrunerServiceTest.java
@@ -29,6 +29,7 @@ import org.apache.pinot.core.query.request.context.QueryContext;
 import org.apache.pinot.core.query.request.context.utils.QueryContextConverterUtils;
 import org.apache.pinot.segment.spi.IndexSegment;
 import org.apache.pinot.segment.spi.SegmentMetadata;
+import org.apache.pinot.segment.spi.index.mutable.ThreadSafeMutableRoaringBitmap;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.CommonConstants.Server;
 import org.testng.Assert;
@@ -87,6 +88,135 @@ public class SegmentPrunerServiceTest {
     Assert.assertEquals(stats.getInvalidSegments(), 0);
   }
 
+  @Test
+  public void emptyValidPruned() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    IndexSegment segment = mockUpsertIndexSegment(10, new ThreadSafeMutableRoaringBitmap(), null);
+
+    List<IndexSegment> segments = new ArrayList<>();
+    segments.add(segment);
+    QueryContext queryContext = QueryContextConverterUtils.getQueryContext("select col1 from t1");
+
+    List<IndexSegment> actual = service.prune(segments, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, Collections.emptyList());
+  }
+
+  @Test
+  public void emptyValidRetainedWithSkipUpsert() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    IndexSegment segment = mockUpsertIndexSegment(10, new ThreadSafeMutableRoaringBitmap(), null);
+
+    List<IndexSegment> segments = new ArrayList<>();
+    segments.add(segment);
+    QueryContext queryContext =
+        QueryContextConverterUtils.getQueryContext("select col1 from t1 option(skipUpsert=true)");
+
+    List<IndexSegment> actual = service.prune(segments, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, segments);
+  }
+
+  @Test
+  public void nonEmptyValidNotPrunedWhenQueryableNull() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    IndexSegment segment = mockUpsertIndexSegment(10, new ThreadSafeMutableRoaringBitmap(0), null);
+
+    List<IndexSegment> indexes = new ArrayList<>();
+    indexes.add(segment);
+    QueryContext queryContext = QueryContextConverterUtils.getQueryContext("select col1 from t1");
+
+    List<IndexSegment> actual = service.prune(indexes, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, indexes);
+  }
+
+  @Test
+  public void nonUpsertSegmentWithNullDocIdBitmapsNotPruned() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    IndexSegment segment = mockUpsertIndexSegment(5, null, null);
+
+    List<IndexSegment> segments = new ArrayList<>();
+    segments.add(segment);
+    QueryContext queryContext = QueryContextConverterUtils.getQueryContext("select col1 from t1");
+
+    List<IndexSegment> actual = service.prune(segments, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, segments);
+  }
+
+  /**
+   * When queryable doc ids exist, a segment with no queryable rows is pruned even if valid doc ids still hold
+   * replaced rows (matches normal upsert query semantics).
+   */
+  @Test
+  public void emptyQueryablePruned() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    ThreadSafeMutableRoaringBitmap valid = new ThreadSafeMutableRoaringBitmap(0);
+    ThreadSafeMutableRoaringBitmap queryable = new ThreadSafeMutableRoaringBitmap();
+    IndexSegment segment = mockUpsertIndexSegment(10, valid, queryable);
+
+    List<IndexSegment> segments = new ArrayList<>();
+    segments.add(segment);
+    QueryContext queryContext = QueryContextConverterUtils.getQueryContext("select col1 from t1");
+
+    List<IndexSegment> actual = service.prune(segments, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, Collections.emptyList());
+  }
+
+  @Test
+  public void emptyQueryableRetainedWithSkipUpsert() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    ThreadSafeMutableRoaringBitmap valid = new ThreadSafeMutableRoaringBitmap(0);
+    ThreadSafeMutableRoaringBitmap queryable = new ThreadSafeMutableRoaringBitmap();
+    IndexSegment segment = mockUpsertIndexSegment(10, valid, queryable);
+
+    List<IndexSegment> segments = new ArrayList<>();
+    segments.add(segment);
+    QueryContext queryContext =
+        QueryContextConverterUtils.getQueryContext("select col1 from t1 option(skipUpsert=true)");
+
+    List<IndexSegment> actual = service.prune(segments, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, segments);
+  }
+
+  @Test
+  public void nonEmptyQueryableNotPruned() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    ThreadSafeMutableRoaringBitmap valid = new ThreadSafeMutableRoaringBitmap(0);
+    ThreadSafeMutableRoaringBitmap queryable = new ThreadSafeMutableRoaringBitmap(0);
+    IndexSegment segment = mockUpsertIndexSegment(10, valid, queryable);
+
+    List<IndexSegment> indexes = new ArrayList<>();
+    indexes.add(segment);
+    QueryContext queryContext = QueryContextConverterUtils.getQueryContext("select col1 from t1");
+
+    List<IndexSegment> actual = service.prune(indexes, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, indexes);
+  }
+
+  /**
+   * Queryable bitmap takes precedence over valid when both are present.
+   */
+  @Test
+  public void nonEmptyQueryableOverridesEmptyValid() {
+    SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
+    ThreadSafeMutableRoaringBitmap valid = new ThreadSafeMutableRoaringBitmap();
+    ThreadSafeMutableRoaringBitmap queryable = new ThreadSafeMutableRoaringBitmap(0);
+    IndexSegment segment = mockUpsertIndexSegment(10, valid, queryable);
+
+    List<IndexSegment> indexes = new ArrayList<>();
+    indexes.add(segment);
+    QueryContext queryContext = QueryContextConverterUtils.getQueryContext("select col1 from t1");
+
+    List<IndexSegment> actual = service.prune(indexes, queryContext, new SegmentPrunerStatistics());
+
+    Assert.assertEquals(actual, indexes);
+  }
+
   private IndexSegment mockIndexSegment(int totalDocs, String... columns) {
     IndexSegment indexSegment = mock(IndexSegment.class);
     when(indexSegment.getColumnNames()).thenReturn(new HashSet<>(Arrays.asList(columns)));
@@ -95,4 +225,19 @@ public class SegmentPrunerServiceTest {
     when(indexSegment.getSegmentMetadata()).thenReturn(segmentMetadata);
     return indexSegment;
   }
+
+  /**
+   * Segment with upsert-style doc id bitmaps (valid and optional queryable).
+   */
+  private IndexSegment mockUpsertIndexSegment(int totalDocs,
+      ThreadSafeMutableRoaringBitmap validDocIds, ThreadSafeMutableRoaringBitmap queryableDocIds) {
+    IndexSegment indexSegment = mock(IndexSegment.class);
+    when(indexSegment.getColumnNames()).thenReturn(new HashSet<>(Arrays.asList("col1")));
+    SegmentMetadata segmentMetadata = mock(SegmentMetadata.class);
+    when(segmentMetadata.getTotalDocs()).thenReturn(totalDocs);
+    when(indexSegment.getSegmentMetadata()).thenReturn(segmentMetadata);
+    when(indexSegment.getValidDocIds()).thenReturn(validDocIds);
+    when(indexSegment.getQueryableDocIds()).thenReturn(queryableDocIds);
+    return indexSegment;
+  }
 }


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


(pinot) 02/25: Fix binary key stream decoder (#17927)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 205b54a3caba6b686b4bc340233f79c599a61102
Author: NOOB <43...@users.noreply.github.com>
AuthorDate: Sat Mar 21 04:41:07 2026 +0530

    Fix binary key stream decoder (#17927)
---
 .../realtime/RealtimeSegmentDataManager.java       |  3 +-
 .../writer/StatelessRealtimeSegmentWriter.java     |  3 +-
 .../pinot/spi/stream/StreamDataDecoderImpl.java    | 20 ++++++++++-
 .../spi/stream/StreamDataDecoderImplTest.java      | 41 ++++++++++++++++++++++
 4 files changed, 64 insertions(+), 3 deletions(-)

diff --git a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
index 37c9511d2bb..0660cdfb9d8 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
@@ -1800,7 +1800,8 @@ public class RealtimeSegmentDataManager extends SegmentDataManager {
       retryPolicy.attempt(() -> {
         try {
           StreamMessageDecoder streamMessageDecoder = createMessageDecoder(fieldsToRead);
-          localStreamDataDecoder.set(new StreamDataDecoderImpl(streamMessageDecoder));
+          boolean isKeyBytesType = StreamDataDecoderImpl.isKeyBytesType(_schema);
+          localStreamDataDecoder.set(new StreamDataDecoderImpl(streamMessageDecoder, isKeyBytesType));
           return true;
         } catch (Exception e) {
           _segmentLogger.warn("Failed to initialize the StreamMessageDecoder: ", e);
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
index 10d37a945a3..cc0c9e92887 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
@@ -221,7 +221,8 @@ public class StatelessRealtimeSegmentWriter implements Closeable {
     retryPolicy.attempt(() -> {
       try {
         StreamMessageDecoder streamMessageDecoder = createMessageDecoder(fieldsToRead);
-        localStreamDataDecoder.set(new StreamDataDecoderImpl(streamMessageDecoder));
+        boolean isKeyBytesType = StreamDataDecoderImpl.isKeyBytesType(_schema);
+        localStreamDataDecoder.set(new StreamDataDecoderImpl(streamMessageDecoder, isKeyBytesType));
         return true;
       } catch (Exception e) {
         _logger.warn("Failed to create StreamMessageDecoder. Retrying...", e);
diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
index 96073ace839..62a51c3c1d9 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
@@ -20,6 +20,8 @@ package org.apache.pinot.spi.stream;
 
 import java.nio.charset.StandardCharsets;
 import java.util.Map;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.data.readers.GenericRow;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -35,6 +37,7 @@ public class StreamDataDecoderImpl implements StreamDataDecoder {
   public static final String RECORD_SERIALIZED_VALUE_SIZE_KEY = METADATA_KEY_PREFIX + "recordSerializedValueSize";
 
   private final StreamMessageDecoder _valueDecoder;
+  private final boolean _isKeyBytesType;
   private final GenericRow _reuse = new GenericRow();
 
   /**
@@ -44,8 +47,21 @@ public class StreamDataDecoderImpl implements StreamDataDecoder {
     return key.equals(KEY) || key.startsWith(HEADER_KEY_PREFIX) || key.startsWith(METADATA_KEY_PREFIX);
   }
 
+  /**
+   * @return Whether the __key column is defined as BYTES type in the schema.
+   */
+  public static boolean isKeyBytesType(Schema schema) {
+    FieldSpec fieldSpec = schema.getFieldSpecFor(KEY);
+    return fieldSpec != null && fieldSpec.getDataType() == FieldSpec.DataType.BYTES;
+  }
+
   public StreamDataDecoderImpl(StreamMessageDecoder valueDecoder) {
+    this(valueDecoder, false);
+  }
+
+  public StreamDataDecoderImpl(StreamMessageDecoder valueDecoder, boolean isKeyBytesType) {
     _valueDecoder = valueDecoder;
+    _isKeyBytesType = isKeyBytesType;
   }
 
   @Override
@@ -58,7 +74,9 @@ public class StreamDataDecoderImpl implements StreamDataDecoder {
       GenericRow row = _valueDecoder.decode(value, 0, length, _reuse);
       if (row != null) {
         if (message.getKey() != null) {
-          row.putValue(KEY, new String(message.getKey(), StandardCharsets.UTF_8));
+          row.putValue(KEY, _isKeyBytesType
+              ? message.getKey()
+              : new String(message.getKey(), StandardCharsets.UTF_8));
         }
         StreamMessageMetadata metadata = message.getMetadata();
         GenericRow headers = metadata.getHeaders();
diff --git a/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java b/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
index 0096691cc13..1819a57b4ec 100644
--- a/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
+++ b/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
@@ -82,6 +82,47 @@ public class StreamDataDecoderImplTest {
     Assert.assertEquals(row.getValue(StreamDataDecoderImpl.RECORD_SERIALIZED_VALUE_SIZE_KEY), value.length());
   }
 
+  /**
+   * Demonstrates that binary keys (e.g. Confluent Avro wire format with 0x00 magic byte)
+   * were previously corrupted when decoded as UTF-8 string, and now work correctly when
+   * the __key column is defined as BYTES type.
+   */
+  @Test
+  public void testBinaryKeyCorruptedAsString() {
+    TestDecoder messageDecoder = new TestDecoder();
+    messageDecoder.init(Map.of(), Set.of(NAME_FIELD), "");
+    String value = "Alice";
+    // Simulate binary key with bytes that are invalid UTF-8 sequences.
+    // 0xFE and 0xFF are never valid in UTF-8; 0x80 is an invalid start byte.
+    // A UTF-8 round-trip will replace these with the replacement character U+FFFD,
+    // corrupting the original bytes.
+    byte[] avroKey = new byte[]{(byte) 0xFE, (byte) 0xFF, (byte) 0x80, 0x01, 0x02};
+    StreamMessageMetadata metadata = new StreamMessageMetadata.Builder().setRecordIngestionTimeMs(1234L)
+        .setOffset(new LongMsgOffset(0), new LongMsgOffset(1))
+        .build();
+    BytesStreamMessage message =
+        new BytesStreamMessage(avroKey, value.getBytes(StandardCharsets.UTF_8), metadata);
+
+    // Old behavior (isKeyBytesType=false): binary key is decoded as UTF-8 string.
+    // The leading 0x00 byte and other non-printable bytes produce a corrupted string
+    // that does NOT round-trip back to the original bytes.
+    StreamDataDecoderResult stringResult = new StreamDataDecoderImpl(messageDecoder).decode(message);
+    Assert.assertNotNull(stringResult.getResult());
+    Object stringKey = stringResult.getResult().getValue(StreamDataDecoderImpl.KEY);
+    Assert.assertTrue(stringKey instanceof String);
+    // The UTF-8 round-trip corrupts the binary data
+    Assert.assertNotEquals(((String) stringKey).getBytes(StandardCharsets.UTF_8), avroKey,
+        "Binary key should be corrupted when decoded as UTF-8 string");
+
+    // New behavior (isKeyBytesType=true): binary key bytes are preserved as-is
+    StreamDataDecoderResult bytesResult = new StreamDataDecoderImpl(messageDecoder, true).decode(message);
+    Assert.assertNotNull(bytesResult.getResult());
+    Object bytesKey = bytesResult.getResult().getValue(StreamDataDecoderImpl.KEY);
+    Assert.assertTrue(bytesKey instanceof byte[]);
+    Assert.assertEquals((byte[]) bytesKey, avroKey,
+        "Binary key should be preserved losslessly when __key is BYTES type");
+  }
+
   @Test
   public void testNoExceptionIsThrown() {
     ThrowingDecoder messageDecoder = new ThrowingDecoder();


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


(pinot) 12/25: Upserts Pruning Optimization - Do not clone MutableRoaringBitmap for each segment (#17920)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 1307cb3a66975c98e613738776c9dc6135513c45
Author: Chaitanya Deepthi <45...@users.noreply.github.com>
AuthorDate: Mon Mar 23 11:30:53 2026 -0700

    Upserts Pruning Optimization - Do not clone MutableRoaringBitmap for each segment  (#17920)
---
 .../pinot/core/query/pruner/SegmentPrunerService.java  | 18 ++++++------------
 .../apache/pinot/segment/local/upsert/UpsertUtils.java | 12 ++++++++++++
 .../index/mutable/ThreadSafeMutableRoaringBitmap.java  |  4 ++++
 3 files changed, 22 insertions(+), 12 deletions(-)

diff --git a/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java b/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java
index 084a00f9351..5707ef698a0 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/SegmentPrunerService.java
@@ -32,7 +32,6 @@ import org.apache.pinot.segment.local.upsert.UpsertUtils;
 import org.apache.pinot.segment.spi.IndexSegment;
 import org.apache.pinot.spi.trace.InvocationScope;
 import org.apache.pinot.spi.trace.Tracing;
-import org.roaringbitmap.buffer.MutableRoaringBitmap;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -142,27 +141,22 @@ public class SegmentPrunerService {
    *                 emptiness is determined from them; otherwise {@link IndexSegment#getValidDocIds()} is used.
    * @return the new list with filtered elements. This is the list that have to be used.
    */
-  private static List<IndexSegment> removeEmptySegments(List<IndexSegment> segments, @Nullable QueryContext query) {
+  private static List<IndexSegment> removeEmptySegments(List<IndexSegment> segments, QueryContext query) {
     int selected = 0;
+    boolean skipUpsert = QueryOptionsUtils.isSkipUpsert(query.getQueryOptions());
     for (IndexSegment segment : segments) {
-      if (!isEmptySegment(segment, query)) {
+      if (!isEmptySegment(segment, skipUpsert)) {
         segments.set(selected++, segment);
       }
     }
     return segments.subList(0, selected);
   }
 
-  private static boolean isEmptySegment(IndexSegment segment, @Nullable QueryContext query) {
+  private static boolean isEmptySegment(IndexSegment segment, boolean skipUpsert) {
     if (segment.getSegmentMetadata().getTotalDocs() == 0) {
       return true;
     }
-    // For upsert tables, treat segments with 0 docs to query as empty only when the query does not skip upsert.
-    // When skipUpsert=true, the query returns all docs (including replaced), so the segment contributes rows.
-    // Use query options map directly: _skipUpsert is only set on the server; the broker has options in the map.
-    if (query != null && query.getQueryOptions() != null && QueryOptionsUtils.isSkipUpsert(query.getQueryOptions())) {
-      return false;
-    }
-    MutableRoaringBitmap queryableDocIds = UpsertUtils.getQueryableDocIdsSnapshotFromSegment(segment);
-    return queryableDocIds != null && queryableDocIds.isEmpty();
+    // Check if the segment has 0 queryable docIds while skipUpsert=false
+    return !skipUpsert && UpsertUtils.hasNoQueryableDocs(segment);
   }
 }
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/UpsertUtils.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/UpsertUtils.java
index b508a02aeb0..990dadb9074 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/UpsertUtils.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/UpsertUtils.java
@@ -57,6 +57,18 @@ public class UpsertUtils {
         : (useEmptyForNull ? new MutableRoaringBitmap() : null);
   }
 
+  /**
+   * Returns whether the segment has no queryable documents, when no delete record column we look into validDocIds
+   * for an upsert table
+   */
+  public static boolean hasNoQueryableDocs(IndexSegment segment) {
+    ThreadSafeMutableRoaringBitmap queryableDocIds = segment.getQueryableDocIds();
+    if (queryableDocIds != null) {
+      return queryableDocIds.isEmpty();
+    }
+    ThreadSafeMutableRoaringBitmap validDocIds = segment.getValidDocIds();
+    return validDocIds != null && validDocIds.isEmpty();
+  }
 
   public static void doReplaceDocId(ThreadSafeMutableRoaringBitmap validDocIds,
       @Nullable ThreadSafeMutableRoaringBitmap queryableDocIds, int oldDocId, int newDocId, RecordInfo recordInfo) {
diff --git a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java
index 05ab86628d5..470913fd4ce 100644
--- a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java
+++ b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/mutable/ThreadSafeMutableRoaringBitmap.java
@@ -60,4 +60,8 @@ public class ThreadSafeMutableRoaringBitmap {
   public synchronized MutableRoaringBitmap getMutableRoaringBitmap() {
     return _mutableRoaringBitmap.clone();
   }
+
+  public synchronized boolean isEmpty() {
+    return _mutableRoaringBitmap.isEmpty();
+  }
 }


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


(pinot) 10/25: Merge pull request #475 from startreedata/fix/lz4-classpath-conflict-2.134.x

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 0f000cb1db7841f4cd97b2c3473977711e5802cb
Merge: 18e464389eb 5c33c2b475a
Author: Jinesh Parakh <50...@users.noreply.github.com>
AuthorDate: Tue Mar 31 02:38:01 2026 +0530

    Merge pull request #475 from startreedata/fix/lz4-classpath-conflict-2.134.x
    
    fix: Exclude transitive org.lz4:lz4-java to prevent LZ4 classpath conflict (2.134.x)

 pinot-connectors/pinot-flink-connector/pom.xml                      | 6 ++++++
 pinot-connectors/pinot-spark-2-connector/pom.xml                    | 4 ++++
 pinot-connectors/pinot-spark-3-connector/pom.xml                    | 6 ++++++
 pinot-integration-tests/pom.xml                                     | 6 ++++++
 .../pinot-batch-ingestion/pinot-batch-ingestion-spark-2.4/pom.xml   | 4 ++++
 .../pinot-batch-ingestion/pinot-batch-ingestion-spark-3/pom.xml     | 4 ++++
 pinot-plugins/pinot-stream-ingestion/pinot-kafka-4.0/pom.xml        | 6 ++++++
 pom.xml                                                             | 2 ++
 8 files changed, 38 insertions(+)



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


(pinot) 05/25: Add tests for partition function config preservation in realtime segments

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 780f7a366ddc308c17a2e458433dbde8758d2bd1
Author: Xiang Fu <xi...@startree.ai>
AuthorDate: Sun Mar 22 02:50:49 2026 -0700

    Add tests for partition function config preservation in realtime segments
    
    Also fix two additional bugs found during investigation:
    
    1. MutableSegmentImpl.getSegmentPartitionConfig() was not including
       the function config when constructing ColumnPartitionConfig, causing
       the config to be dropped during realtime-to-immutable conversion.
    
    2. Murmur3PartitionFunction did not implement getFunctionConfig(),
       so its config (seed, variant) was silently lost when persisting
       segment metadata.
    
    Added two tests in RealtimeSegmentConverterTest:
    - testPartitionFunctionConfigPreservedInConvertedSegment: verifies
      BoundedColumnValue function config survives realtime segment conversion
    - testMurmur3PartitionFunctionConfigPreservedInConvertedSegment: verifies
      Murmur3 function config (seed, variant) survives conversion
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <no...@anthropic.com>
---
 .../indexsegment/mutable/MutableSegmentImpl.java   |   3 +-
 .../converter/RealtimeSegmentConverterTest.java    | 181 +++++++++++++++++++++
 2 files changed, 183 insertions(+), 1 deletion(-)

diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
index 43150d61c59..7b50b1b3d52 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
@@ -590,7 +590,8 @@ public class MutableSegmentImpl implements MutableSegment {
   public SegmentPartitionConfig getSegmentPartitionConfig() {
     if (_partitionColumn != null) {
       return new SegmentPartitionConfig(Collections.singletonMap(_partitionColumn,
-          new ColumnPartitionConfig(_partitionFunction.getName(), _partitionFunction.getNumPartitions())));
+          new ColumnPartitionConfig(_partitionFunction.getName(), _partitionFunction.getNumPartitions(),
+              _partitionFunction.getFunctionConfig())));
     } else {
       return null;
     }
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/converter/RealtimeSegmentConverterTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/converter/RealtimeSegmentConverterTest.java
index 30951a1d606..3d8ec0af274 100644
--- a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/converter/RealtimeSegmentConverterTest.java
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/converter/RealtimeSegmentConverterTest.java
@@ -57,9 +57,13 @@ import org.apache.pinot.segment.spi.index.TextIndexConfig;
 import org.apache.pinot.segment.spi.index.column.ColumnIndexContainer;
 import org.apache.pinot.segment.spi.index.metadata.SegmentMetadataImpl;
 import org.apache.pinot.segment.spi.index.reader.TextIndexReader;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionFunctionFactory;
 import org.apache.pinot.segment.spi.store.SegmentDirectory;
+import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
 import org.apache.pinot.spi.config.table.FieldConfig;
 import org.apache.pinot.spi.config.table.IndexConfig;
+import org.apache.pinot.spi.config.table.SegmentPartitionConfig;
 import org.apache.pinot.spi.config.table.SegmentZKPropsConfig;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.config.table.TableType;
@@ -78,6 +82,7 @@ import org.testng.annotations.Test;
 import static org.mockito.Mockito.mock;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNotEquals;
+import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertTrue;
 
 
@@ -716,6 +721,182 @@ public class RealtimeSegmentConverterTest implements PinotBuffersAfterMethodChec
     }
   }
 
+  @Test
+  public void testPartitionFunctionConfigPreservedInConvertedSegment()
+      throws Exception {
+    File tmpDir = new File(TMP_DIR, "tmp_" + System.currentTimeMillis());
+
+    // Create a partition function config with BoundedColumnValue
+    Map<String, String> functionConfig = new HashMap<>();
+    functionConfig.put("columnValues", "Hello0,Hello1,Hello2");
+    functionConfig.put("columnValuesDelimiter", ",");
+
+    SegmentPartitionConfig segmentPartitionConfig = new SegmentPartitionConfig(
+        Collections.singletonMap(STRING_COLUMN1,
+            new ColumnPartitionConfig("BoundedColumnValue", 4, functionConfig)));
+
+    TableConfig tableConfig =
+        new TableConfigBuilder(TableType.REALTIME).setTableName("testTable")
+            .setTimeColumnName(DATE_TIME_COLUMN)
+            .setSegmentPartitionConfig(segmentPartitionConfig)
+            .setColumnMajorSegmentBuilderEnabled(false)
+            .build();
+    Schema schema = new Schema.SchemaBuilder()
+        .addSingleValueDimension(STRING_COLUMN1, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(STRING_COLUMN2, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(STRING_COLUMN3, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(STRING_COLUMN4, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(LONG_COLUMN1, FieldSpec.DataType.LONG)
+        .addSingleValueDimension(LONG_COLUMN2, FieldSpec.DataType.LONG)
+        .addSingleValueDimension(LONG_COLUMN3, FieldSpec.DataType.LONG)
+        .addMultiValueDimension(MV_INT_COLUMN, FieldSpec.DataType.INT)
+        .addMetric(LONG_COLUMN4, FieldSpec.DataType.LONG)
+        .addDateTime(DATE_TIME_COLUMN, FieldSpec.DataType.LONG, "1:MILLISECONDS:EPOCH", "1:MILLISECONDS")
+        .build();
+
+    String tableNameWithType = tableConfig.getTableName();
+    String segmentName = "testTable__0__0__123456";
+
+    PartitionFunction partitionFunction = PartitionFunctionFactory.getPartitionFunction(
+        "BoundedColumnValue", 4, functionConfig);
+
+    RealtimeSegmentConfig.Builder realtimeSegmentConfigBuilder =
+        new RealtimeSegmentConfig.Builder().setTableNameWithType(tableNameWithType).setSegmentName(segmentName)
+            .setStreamName(tableNameWithType).setSchema(schema).setTimeColumnName(DATE_TIME_COLUMN).setCapacity(1000)
+            .setAvgNumMultiValues(3)
+            .setPartitionColumn(STRING_COLUMN1)
+            .setPartitionFunction(partitionFunction)
+            .setPartitionId(0)
+            .setSegmentZKMetadata(getSegmentZKMetadata(segmentName)).setOffHeap(true)
+            .setMemoryManager(new DirectMemoryManager(segmentName))
+            .setStatsHistory(RealtimeSegmentStatsHistory.deserializeFrom(new File(tmpDir, "stats")))
+            .setConsumerDir(new File(tmpDir, "consumerDir").getAbsolutePath());
+
+    MutableSegmentImpl mutableSegmentImpl = new MutableSegmentImpl(realtimeSegmentConfigBuilder.build(), null);
+    try {
+      List<GenericRow> rows = generateTestData();
+      for (GenericRow row : rows) {
+        mutableSegmentImpl.index(row, null);
+      }
+
+      // Verify the mutable segment's partition config includes function config
+      SegmentPartitionConfig mutablePartitionConfig = mutableSegmentImpl.getSegmentPartitionConfig();
+      assertNotNull(mutablePartitionConfig);
+      ColumnPartitionConfig columnPartitionConfig =
+          mutablePartitionConfig.getColumnPartitionMap().get(STRING_COLUMN1);
+      assertNotNull(columnPartitionConfig);
+      assertEquals(columnPartitionConfig.getFunctionName(), "BoundedColumnValue");
+      assertEquals(columnPartitionConfig.getNumPartitions(), 4);
+      assertEquals(columnPartitionConfig.getFunctionConfig(), functionConfig);
+
+      // Convert to immutable segment
+      File outputDir = new File(tmpDir, "outputDir");
+      SegmentZKPropsConfig segmentZKPropsConfig = new SegmentZKPropsConfig();
+      segmentZKPropsConfig.setStartOffset("1");
+      segmentZKPropsConfig.setEndOffset("100");
+      RealtimeSegmentConverter converter =
+          new RealtimeSegmentConverter(mutableSegmentImpl, segmentZKPropsConfig, outputDir.getAbsolutePath(), schema,
+              tableNameWithType, tableConfig, segmentName, false);
+      converter.build(SegmentVersion.v3, null);
+
+      // Verify the converted segment metadata preserves the partition function config
+      File indexDir = new File(outputDir, segmentName);
+      SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(indexDir);
+
+      ColumnMetadata col1Meta = segmentMetadata.getColumnMetadataFor(STRING_COLUMN1);
+      assertNotNull(col1Meta.getPartitionFunction(), "Partition function should be present in converted segment");
+      assertEquals(col1Meta.getPartitionFunction().getName(), "BoundedColumnValue");
+      assertEquals(col1Meta.getPartitionFunction().getNumPartitions(), 4);
+      assertEquals(col1Meta.getPartitionFunction().getFunctionConfig(), functionConfig,
+          "Function config should be preserved in converted segment metadata");
+    } finally {
+      mutableSegmentImpl.destroy();
+    }
+  }
+
+  @Test
+  public void testMurmur3PartitionFunctionConfigPreservedInConvertedSegment()
+      throws Exception {
+    File tmpDir = new File(TMP_DIR, "tmp_" + System.currentTimeMillis());
+
+    // Create a Murmur3 partition function config with seed and variant
+    Map<String, String> functionConfig = new HashMap<>();
+    functionConfig.put("seed", "9001");
+    functionConfig.put("variant", "x64_32");
+
+    SegmentPartitionConfig segmentPartitionConfig = new SegmentPartitionConfig(
+        Collections.singletonMap(STRING_COLUMN1,
+            new ColumnPartitionConfig("Murmur3", 5, functionConfig)));
+
+    TableConfig tableConfig =
+        new TableConfigBuilder(TableType.REALTIME).setTableName("testTable")
+            .setTimeColumnName(DATE_TIME_COLUMN)
+            .setSegmentPartitionConfig(segmentPartitionConfig)
+            .setColumnMajorSegmentBuilderEnabled(false)
+            .build();
+    Schema schema = new Schema.SchemaBuilder()
+        .addSingleValueDimension(STRING_COLUMN1, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(STRING_COLUMN2, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(STRING_COLUMN3, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(STRING_COLUMN4, FieldSpec.DataType.STRING)
+        .addSingleValueDimension(LONG_COLUMN1, FieldSpec.DataType.LONG)
+        .addSingleValueDimension(LONG_COLUMN2, FieldSpec.DataType.LONG)
+        .addSingleValueDimension(LONG_COLUMN3, FieldSpec.DataType.LONG)
+        .addMultiValueDimension(MV_INT_COLUMN, FieldSpec.DataType.INT)
+        .addMetric(LONG_COLUMN4, FieldSpec.DataType.LONG)
+        .addDateTime(DATE_TIME_COLUMN, FieldSpec.DataType.LONG, "1:MILLISECONDS:EPOCH", "1:MILLISECONDS")
+        .build();
+
+    String tableNameWithType = tableConfig.getTableName();
+    String segmentName = "testTable__0__0__123456";
+
+    PartitionFunction partitionFunction = PartitionFunctionFactory.getPartitionFunction(
+        "Murmur3", 5, functionConfig);
+
+    RealtimeSegmentConfig.Builder realtimeSegmentConfigBuilder =
+        new RealtimeSegmentConfig.Builder().setTableNameWithType(tableNameWithType).setSegmentName(segmentName)
+            .setStreamName(tableNameWithType).setSchema(schema).setTimeColumnName(DATE_TIME_COLUMN).setCapacity(1000)
+            .setAvgNumMultiValues(3)
+            .setPartitionColumn(STRING_COLUMN1)
+            .setPartitionFunction(partitionFunction)
+            .setPartitionId(0)
+            .setSegmentZKMetadata(getSegmentZKMetadata(segmentName)).setOffHeap(true)
+            .setMemoryManager(new DirectMemoryManager(segmentName))
+            .setStatsHistory(RealtimeSegmentStatsHistory.deserializeFrom(new File(tmpDir, "stats")))
+            .setConsumerDir(new File(tmpDir, "consumerDir").getAbsolutePath());
+
+    MutableSegmentImpl mutableSegmentImpl = new MutableSegmentImpl(realtimeSegmentConfigBuilder.build(), null);
+    try {
+      List<GenericRow> rows = generateTestData();
+      for (GenericRow row : rows) {
+        mutableSegmentImpl.index(row, null);
+      }
+
+      // Convert to immutable segment
+      File outputDir = new File(tmpDir, "outputDir");
+      SegmentZKPropsConfig segmentZKPropsConfig = new SegmentZKPropsConfig();
+      segmentZKPropsConfig.setStartOffset("1");
+      segmentZKPropsConfig.setEndOffset("100");
+      RealtimeSegmentConverter converter =
+          new RealtimeSegmentConverter(mutableSegmentImpl, segmentZKPropsConfig, outputDir.getAbsolutePath(), schema,
+              tableNameWithType, tableConfig, segmentName, false);
+      converter.build(SegmentVersion.v3, null);
+
+      // Verify the converted segment metadata preserves the Murmur3 function config
+      File indexDir = new File(outputDir, segmentName);
+      SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(indexDir);
+
+      ColumnMetadata col1Meta = segmentMetadata.getColumnMetadataFor(STRING_COLUMN1);
+      assertNotNull(col1Meta.getPartitionFunction(), "Partition function should be present in converted segment");
+      assertEquals(col1Meta.getPartitionFunction().getName(), "Murmur3");
+      assertEquals(col1Meta.getPartitionFunction().getNumPartitions(), 5);
+      assertEquals(col1Meta.getPartitionFunction().getFunctionConfig(), functionConfig,
+          "Murmur3 function config (seed, variant) should be preserved in converted segment metadata");
+    } finally {
+      mutableSegmentImpl.destroy();
+    }
+  }
+
   private List<GenericRow> generateTestData() {
     LinkedList<GenericRow> rows = new LinkedList<>();
 


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


(pinot) 23/25: Fix compilation issue in ResponseStoreCleaner (#496)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 2c02c75fbd91fe2b12fd04eaafbbed888593dc10
Author: Yash Mayya <ya...@gmail.com>
AuthorDate: Thu Apr 9 07:15:43 2026 -0700

    Fix compilation issue in ResponseStoreCleaner (#496)
---
 .../pinot/controller/cursors/ResponseStoreCleaner.java    | 15 +++++----------
 1 file changed, 5 insertions(+), 10 deletions(-)

diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java b/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
index 56cb0ba2824..2c101495607 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
@@ -113,18 +113,13 @@ public class ResponseStoreCleaner extends ControllerPeriodicTask<Void> {
     return frequencyInSeconds;
   }
 
-  /**
-   * Returns a singleton list with the task name as a pseudo-table so that the standard leadership gating in
-   * {@link ControllerPeriodicTask#runTask} ensures exactly one controller runs cleanup, independent of actual
-   * table distribution.
-   */
-  @Override
-  protected List<String> getTablesToProcess(Properties periodicTaskProperties) {
-    return List.of(TASK_NAME);
-  }
-
   @Override
   protected void processTables(List<String> tableNamesWithType, Properties periodicTaskProperties) {
+    // Make it so that only one controller is responsible for cleaning up minion instances.
+    if (!_leadControllerManager.isLeaderForTable(TASK_NAME)) {
+      return;
+    }
+
     long cleanAtMs = System.currentTimeMillis();
     String cleanAtMsStr = periodicTaskProperties.getProperty(CLEAN_AT_TIME);
     if (cleanAtMsStr != null) {


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


(pinot) 13/25: Give out clear message when coordinate is NULL - H3 Index (#17967)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit ef5c51f668b878763c1ffae19c11c59afbc4f7b5
Author: Chaitanya Deepthi <45...@users.noreply.github.com>
AuthorDate: Wed Mar 25 02:58:52 2026 -0700

    Give out clear message when coordinate is NULL - H3 Index (#17967)
    
    * Fix the null coordinate issue
    
    * Revert back the condition
---
 .../local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java    | 1 +
 1 file changed, 1 insertion(+)

diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java
index 888d5cbb004..5daa0ff163f 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/inv/geospatial/BaseH3IndexCreator.java
@@ -127,6 +127,7 @@ public abstract class BaseH3IndexCreator implements GeoSpatialIndexCreator {
     Preconditions.checkState(geometry instanceof Point, "H3 index can only be applied to Point, got: %s",
         geometry.getGeometryType());
     Coordinate coordinate = geometry.getCoordinate();
+    Preconditions.checkState(coordinate != null, "Point has null coordinate and continueOnError is disabled");
     // TODO: support multiple resolutions
     long h3Id = H3Utils.H3_CORE.latLngToCell(coordinate.y, coordinate.x, _lowestResolution);
     RoaringBitmapWriter<RoaringBitmap> bitmapWriter = _postingListMap.get(h3Id);


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


(pinot) 16/25: Merge pull request #481 from startreedata/hotfix-merge

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 6f8896432a7c084c978848747e310ca1bd05b16b
Merge: 0f000cb1db7 474e2f98ef6
Author: Chaitanya Deepthi <45...@users.noreply.github.com>
AuthorDate: Wed Apr 1 19:27:48 2026 -0700

    Merge pull request #481 from startreedata/hotfix-merge
    
    Upserts Pruning Optimizations, H3 Index NPE fix, Memory leak and Upserts Bitmap optimizations

 .../core/query/pruner/SegmentPrunerService.java    |  20 ++-
 .../query/pruner/SegmentPrunerServiceTest.java     | 145 +++++++++++++++++++++
 .../immutable/ImmutableSegmentImpl.java            |  38 +++---
 .../impl/inv/geospatial/BaseH3IndexCreator.java    |  26 +++-
 .../segment/local/segment/readers/LazyRow.java     |   1 +
 .../upsert/BasePartitionUpsertMetadataManager.java |  71 +++++-----
 ...oncurrentMapPartitionUpsertMetadataManager.java |  10 +-
 ...nUpsertMetadataManagerForConsistentDeletes.java |  10 +-
 .../pinot/segment/local/upsert/UpsertUtils.java    |  12 ++
 .../segment/local/segment/index/H3IndexTest.java   |  88 +++++++++++++
 .../BasePartitionUpsertMetadataManagerTest.java    |  50 +++----
 .../mutable/ThreadSafeMutableRoaringBitmap.java    |  45 +++++++
 12 files changed, 426 insertions(+), 90 deletions(-)


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


(pinot) 24/25: Always emit COMMITTING_SEGMENT_SIZE and NUM_ROWS_THRESHOLD regardless of the threshold update type (#18137) (#501)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit 4aa0f7695b0c588403bdd0133fbc19e49e90bd21
Author: Xiaotian (Jackie) Jiang <17...@users.noreply.github.com>
AuthorDate: Thu Apr 9 14:45:50 2026 -0700

    Always emit COMMITTING_SEGMENT_SIZE and NUM_ROWS_THRESHOLD regardless of the threshold update type (#18137) (#501)
---
 .../realtime/PinotLLCRealtimeSegmentManager.java   |  50 ++-
 .../segment/CommittingSegmentDescriptor.java       |  23 +-
 .../segment/FlushThresholdUpdateManager.java       |   4 +-
 .../SegmentSizeBasedFlushThresholdUpdater.java     |  19 +-
 .../PinotLLCRealtimeSegmentManagerTest.java        | 409 +++++++++------------
 .../segment/FlushThresholdUpdaterTest.java         |  15 +-
 6 files changed, 232 insertions(+), 288 deletions(-)

diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java
index 7913e88c07c..b6630828feb 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManager.java
@@ -607,8 +607,7 @@ public class PinotLLCRealtimeSegmentManager {
     // Copy the segment file to the controller
     String segmentLocation = committingSegmentDescriptor.getSegmentLocation();
     Preconditions.checkArgument(segmentLocation != null, "Segment location must be provided");
-    if (segmentLocation.regionMatches(true, 0, CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME, 0,
-        CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME.length())) {
+    if (isPeerUrl(segmentLocation)) {
       LOGGER.info("No moving needed for segment on peer servers: {}", segmentLocation);
       return;
     }
@@ -632,6 +631,11 @@ public class PinotLLCRealtimeSegmentManager {
     committingSegmentDescriptor.setSegmentLocation(uriToMoveTo);
   }
 
+  private boolean isPeerUrl(String segmentLocation) {
+    return segmentLocation.regionMatches(true, 0, CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME, 0,
+        CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME.length());
+  }
+
   /**
    * This method is invoked after the realtime segment is uploaded but before a response is sent to the server.
    * It updates the propertystore segment metadata from IN_PROGRESS to DONE, and also creates new propertystore
@@ -671,9 +675,9 @@ public class PinotLLCRealtimeSegmentManager {
     // Step-1: Update PROPERTYSTORE
     LOGGER.info("Committing segment metadata for segment: {}", committingSegmentName);
     long startTimeNs1 = System.nanoTime();
-    SegmentZKMetadata committingSegmentZKMetadata =
-        toCommitting ? updateSegmentZKMetadataToCommitting(realtimeTableName, committingSegmentDescriptor)
-            : updateSegmentZKMetadataToDone(realtimeTableName, committingSegmentDescriptor, Status.IN_PROGRESS);
+    SegmentZKMetadata committingSegmentZKMetadata = toCommitting
+        ? updateSegmentZKMetadataToCommitting(realtimeTableName, committingSegmentDescriptor)
+        : updateSegmentZKMetadataToDone(realtimeTableName, committingSegmentDescriptor, Status.IN_PROGRESS);
 
     preProcessNewSegmentZKMetadata();
 
@@ -689,7 +693,7 @@ public class PinotLLCRealtimeSegmentManager {
     LOGGER.info("Updating Idealstate for previous: {} and new segment: {}", committingSegmentName,
         newConsumingSegmentName);
     long startTimeNs3 = System.nanoTime();
-    Map<String, Map<String, String>> instanceStatesMapAfterStep3 = Collections.emptyMap();
+    Map<String, Map<String, String>> instanceStatesMapAfterStep3;
     boolean newConsumingSegmentInIdealState = false;
 
     // When multiple segments of the same table complete around the same time it is possible that
@@ -788,8 +792,10 @@ public class PinotLLCRealtimeSegmentManager {
     Preconditions.checkState(segmentMetadata != null, "Failed to find segment metadata from descriptor for segment: %s",
         segmentName);
     String segmentLocation = committingSegmentDescriptor.getSegmentLocation();
-    String downloadUrl =
-        isPeerURL(segmentLocation) ? CommonConstants.Segment.METADATA_URI_FOR_PEER_DOWNLOAD : segmentLocation;
+    Preconditions.checkArgument(segmentLocation != null, "Segment location must be provided");
+    String downloadUrl = isPeerUrl(segmentLocation)
+        ? CommonConstants.Segment.METADATA_URI_FOR_PEER_DOWNLOAD
+        : segmentLocation;
     SegmentZKMetadataUtils.updateCommittingSegmentZKMetadata(realtimeTableName, segmentZKMetadata, segmentMetadata,
         downloadUrl, committingSegmentDescriptor.getSegmentSizeBytes(), committingSegmentDescriptor.getNextOffset());
     persistSegmentZKMetadata(realtimeTableName, segmentZKMetadata, stat.getVersion());
@@ -976,6 +982,7 @@ public class PinotLLCRealtimeSegmentManager {
         FlushThresholdUpdater flushThresholdUpdater =
             _flushThresholdUpdateManager.getFlushThresholdUpdater(streamConfig);
         flushThresholdUpdater.onSegmentCommit(streamConfig, committingSegmentDescriptor, committingSegmentZKMetadata);
+        updateCommittingSegmentSizeGauge(streamConfig, committingSegmentDescriptor.getSegmentSizeBytes());
       } catch (Exception e) {
         LOGGER.error("Caught exception while updating flush threshold for table: {}, segment: {}", realtimeTableName,
             segmentName, e);
@@ -985,11 +992,6 @@ public class PinotLLCRealtimeSegmentManager {
     }
   }
 
-  private boolean isPeerURL(String segmentLocation) {
-    return segmentLocation != null && segmentLocation.toLowerCase()
-        .startsWith(CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME);
-  }
-
   /**
    * Creates and persists segment ZK metadata for the new CONSUMING segment.
    */
@@ -1038,13 +1040,35 @@ public class PinotLLCRealtimeSegmentManager {
     FlushThresholdUpdater flushThresholdUpdater = _flushThresholdUpdateManager.getFlushThresholdUpdater(streamConfig);
     if (committingSegmentZKMetadata != null) {
       flushThresholdUpdater.onSegmentCommit(streamConfig, committingSegmentDescriptor, committingSegmentZKMetadata);
+      long segmentSize = committingSegmentDescriptor.getSegmentSizeBytes();
+      // Segment size might not be available for pauseless ingestion
+      if (segmentSize > 0) {
+        updateCommittingSegmentSizeGauge(streamConfig, segmentSize);
+      }
     }
     flushThresholdUpdater.updateFlushThreshold(streamConfig, newSegmentZKMetadata,
         getMaxNumPartitionsPerInstance(instancePartitions, numPartitions, numReplicas));
+    updateFlushThresholdGauge(streamConfig, newSegmentZKMetadata.getSizeThresholdToFlushSegment());
 
     persistSegmentZKMetadata(realtimeTableName, newSegmentZKMetadata, -1);
   }
 
+  private void updateCommittingSegmentSizeGauge(StreamConfig streamConfig, long segmentSize) {
+    String realtimeTableName = streamConfig.getTableNameWithType();
+    String topicName = streamConfig.getTopicName();
+    _controllerMetrics.setOrUpdateTableGauge(realtimeTableName, ControllerGauge.COMMITTING_SEGMENT_SIZE, segmentSize);
+    _controllerMetrics.setOrUpdateTableGauge(realtimeTableName, topicName,
+        ControllerGauge.COMMITTING_SEGMENT_SIZE_WITH_TOPIC, segmentSize);
+  }
+
+  private void updateFlushThresholdGauge(StreamConfig streamConfig, int flushThreshold) {
+    String realtimeTableName = streamConfig.getTableNameWithType();
+    String topicName = streamConfig.getTopicName();
+    _controllerMetrics.setOrUpdateTableGauge(realtimeTableName, ControllerGauge.NUM_ROWS_THRESHOLD, flushThreshold);
+    _controllerMetrics.setOrUpdateTableGauge(realtimeTableName, topicName,
+        ControllerGauge.NUM_ROWS_THRESHOLD_WITH_TOPIC, flushThreshold);
+  }
+
   private String computeStartOffset(String nextOffset, StreamConfig streamConfig, int partitionId) {
     if (!streamConfig.isEnableOffsetAutoReset() || streamConfig.isBackfillTopic()) {
       return nextOffset;
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/CommittingSegmentDescriptor.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/CommittingSegmentDescriptor.java
index ba89389c654..12c865bbcc7 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/CommittingSegmentDescriptor.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/CommittingSegmentDescriptor.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.controller.helix.core.realtime.segment;
 
+import javax.annotation.Nullable;
 import org.apache.pinot.common.protocols.SegmentCompletionProtocol;
 import org.apache.pinot.segment.spi.index.metadata.SegmentMetadataImpl;
 
@@ -26,10 +27,11 @@ import org.apache.pinot.segment.spi.index.metadata.SegmentMetadataImpl;
  * Class to hold properties of the committing segment
  */
 public class CommittingSegmentDescriptor {
-  private String _segmentName;
-  private long _segmentSizeBytes;
+  private final String _segmentName;
+  private final String _nextOffset;
+  private final long _segmentSizeBytes;
+
   private String _segmentLocation;
-  private String _nextOffset;
   private SegmentMetadataImpl _segmentMetadata;
   private String _stopReason;
   private int _preCommitRowCount;
@@ -70,18 +72,15 @@ public class CommittingSegmentDescriptor {
     return _segmentName;
   }
 
-  public void setSegmentName(String segmentName) {
-    _segmentName = segmentName;
+  public String getNextOffset() {
+    return _nextOffset;
   }
 
   public long getSegmentSizeBytes() {
     return _segmentSizeBytes;
   }
 
-  public void setSegmentSizeBytes(long segmentSizeBytes) {
-    _segmentSizeBytes = segmentSizeBytes;
-  }
-
+  @Nullable
   public String getSegmentLocation() {
     return _segmentLocation;
   }
@@ -90,10 +89,7 @@ public class CommittingSegmentDescriptor {
     _segmentLocation = segmentLocation;
   }
 
-  public String getNextOffset() {
-    return _nextOffset;
-  }
-
+  @Nullable
   public SegmentMetadataImpl getSegmentMetadata() {
     return _segmentMetadata;
   }
@@ -102,6 +98,7 @@ public class CommittingSegmentDescriptor {
     _segmentMetadata = segmentMetadata;
   }
 
+  @Nullable
   public String getStopReason() {
     return _stopReason;
   }
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdateManager.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdateManager.java
index b4476e3bac1..119698f981b 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdateManager.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdateManager.java
@@ -47,7 +47,6 @@ public class FlushThresholdUpdateManager {
    */
   public FlushThresholdUpdater getFlushThresholdUpdater(StreamConfig streamConfig) {
     String tableTopicKey = getKey(streamConfig);
-    String realtimeTableName = streamConfig.getTableNameWithType();
     int flushThresholdRows = streamConfig.getFlushThresholdRows();
     if (flushThresholdRows > 0) {
       _flushThresholdUpdaterMap.remove(tableTopicKey);
@@ -61,8 +60,7 @@ public class FlushThresholdUpdateManager {
     // Legacy behavior: when flush threshold rows is explicitly set to 0, use segment size based flush threshold
     long flushThresholdSegmentSizeBytes = streamConfig.getFlushThresholdSegmentSizeBytes();
     if (flushThresholdRows == 0 || flushThresholdSegmentSizeBytes > 0) {
-      return _flushThresholdUpdaterMap.computeIfAbsent(tableTopicKey,
-          k -> new SegmentSizeBasedFlushThresholdUpdater(realtimeTableName, streamConfig.getTopicName()));
+      return _flushThresholdUpdaterMap.computeIfAbsent(tableTopicKey, k -> new SegmentSizeBasedFlushThresholdUpdater());
     } else {
       _flushThresholdUpdaterMap.remove(tableTopicKey);
       return new DefaultFlushThresholdUpdater(StreamConfig.DEFAULT_FLUSH_THRESHOLD_ROWS);
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/SegmentSizeBasedFlushThresholdUpdater.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/SegmentSizeBasedFlushThresholdUpdater.java
index 4f76a3382f3..c3bdb0ac81d 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/SegmentSizeBasedFlushThresholdUpdater.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/realtime/segment/SegmentSizeBasedFlushThresholdUpdater.java
@@ -19,8 +19,6 @@
 package org.apache.pinot.controller.helix.core.realtime.segment;
 
 import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
-import org.apache.pinot.common.metrics.ControllerGauge;
-import org.apache.pinot.common.metrics.ControllerMetrics;
 import org.apache.pinot.spi.stream.StreamConfig;
 
 
@@ -34,25 +32,14 @@ import org.apache.pinot.spi.stream.StreamConfig;
  */
 public class SegmentSizeBasedFlushThresholdUpdater implements FlushThresholdUpdater {
   private final SizeBasedSegmentFlushThresholdComputer _flushThresholdComputer;
-  private final String _realtimeTableName;
-  private final String _topicName;
 
-  private final ControllerMetrics _controllerMetrics = ControllerMetrics.get();
-
-  public SegmentSizeBasedFlushThresholdUpdater(String realtimeTableName, String topicName) {
+  public SegmentSizeBasedFlushThresholdUpdater() {
     _flushThresholdComputer = new SizeBasedSegmentFlushThresholdComputer();
-    _realtimeTableName = realtimeTableName;
-    _topicName = topicName;
   }
 
   @Override
   public void onSegmentCommit(StreamConfig streamConfig, CommittingSegmentDescriptor committingSegmentDescriptor,
       SegmentZKMetadata committingSegmentZKMetadata) {
-    long segmentSize = committingSegmentDescriptor.getSegmentSizeBytes();
-    _controllerMetrics.setOrUpdateTableGauge(_realtimeTableName, ControllerGauge.COMMITTING_SEGMENT_SIZE, segmentSize);
-    _controllerMetrics.setOrUpdateTableGauge(_realtimeTableName, _topicName,
-        ControllerGauge.COMMITTING_SEGMENT_SIZE_WITH_TOPIC, segmentSize);
-
     _flushThresholdComputer.onSegmentCommit(committingSegmentDescriptor, committingSegmentZKMetadata);
   }
 
@@ -61,9 +48,5 @@ public class SegmentSizeBasedFlushThresholdUpdater implements FlushThresholdUpda
       int maxNumPartitionsPerInstance) {
     int threshold = _flushThresholdComputer.computeThreshold(streamConfig, newSegmentZKMetadata.getSegmentName());
     newSegmentZKMetadata.setSizeThresholdToFlushSegment(threshold);
-
-    _controllerMetrics.setOrUpdateTableGauge(_realtimeTableName, ControllerGauge.NUM_ROWS_THRESHOLD, threshold);
-    _controllerMetrics.setOrUpdateTableGauge(_realtimeTableName, _topicName,
-        ControllerGauge.NUM_ROWS_THRESHOLD_WITH_TOPIC, threshold);
   }
 }
diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManagerTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManagerTest.java
index eecad3d22c4..eab937c82f0 100644
--- a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManagerTest.java
+++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/PinotLLCRealtimeSegmentManagerTest.java
@@ -124,21 +124,22 @@ public class PinotLLCRealtimeSegmentManagerTest {
   private static final String CLUSTER_NAME = "testCluster";
   private static final String RAW_TABLE_NAME = "testTable";
   private static final String REALTIME_TABLE_NAME = TableNameBuilder.REALTIME.tableNameWithType(RAW_TABLE_NAME);
-
-  private static final long RANDOM_SEED = System.currentTimeMillis();
-  private static final Random RANDOM = new Random(RANDOM_SEED);
-  static final LongMsgOffset PARTITION_OFFSET = new LongMsgOffset(RANDOM.nextInt(Integer.MAX_VALUE));
-  static final long CURRENT_TIME_MS = System.currentTimeMillis();
-  static final long START_TIME_MS = CURRENT_TIME_MS - TimeUnit.HOURS.toMillis(RANDOM.nextInt(24) + 24);
-  static final long END_TIME_MS = START_TIME_MS + TimeUnit.HOURS.toMillis(RANDOM.nextInt(24) + 1);
-  static final Interval INTERVAL = new Interval(START_TIME_MS, END_TIME_MS);
+  private static final String SEGMENT_LOCATION_PREFIX = "http://control_vip/segments/";
+  private static final int SEGMENT_SIZE_IN_BYTES = 100000000;
+
+  private static final long CURRENT_TIME_MS = System.currentTimeMillis();
+  private static final Random RANDOM = new Random(CURRENT_TIME_MS);
+  private static final LongMsgOffset PARTITION_OFFSET = new LongMsgOffset(RANDOM.nextInt(Integer.MAX_VALUE));
+  private static final int NUM_DOCS = RANDOM.nextInt(Integer.MAX_VALUE) + 1;
+  private static final String NEXT_OFFSET = new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString();
+  private static final long LATEST_OFFSET = PARTITION_OFFSET.getOffset() * 2 + NUM_DOCS;
+  private static final long START_TIME_MS = CURRENT_TIME_MS - TimeUnit.HOURS.toMillis(RANDOM.nextInt(24) + 24);
+  private static final long END_TIME_MS = START_TIME_MS + TimeUnit.HOURS.toMillis(RANDOM.nextInt(24) + 1);
+  private static final Interval INTERVAL = new Interval(START_TIME_MS, END_TIME_MS);
   // NOTE: CRC is always non-negative
-  static final String CRC = Long.toString(RANDOM.nextLong() & 0xFFFFFFFFL);
-  static final String DATA_CRC = Long.toString(RANDOM.nextLong() & 0xFFFFFFFFL);
-  static final SegmentVersion SEGMENT_VERSION = RANDOM.nextBoolean() ? SegmentVersion.v1 : SegmentVersion.v3;
-  static final int NUM_DOCS = RANDOM.nextInt(Integer.MAX_VALUE) + 1;
-  static final long LATEST_OFFSET = PARTITION_OFFSET.getOffset() * 2 + NUM_DOCS;
-  static final int SEGMENT_SIZE_IN_BYTES = 100000000;
+  private static final String CRC = Long.toString(RANDOM.nextLong() & 0xFFFFFFFFL);
+  private static final String DATA_CRC = Long.toString(RANDOM.nextLong() & 0xFFFFFFFFL);
+  private static final SegmentVersion SEGMENT_VERSION = RANDOM.nextBoolean() ? SegmentVersion.v1 : SegmentVersion.v3;
 
   @AfterClass
   public void tearDown()
@@ -156,6 +157,22 @@ public class PinotLLCRealtimeSegmentManagerTest {
     return segmentMetadata;
   }
 
+  private CommittingSegmentDescriptor createCommittingSegmentDescriptor(String segmentName, String nextOffset,
+      String segmentLocation) {
+    CommittingSegmentDescriptor committingSegmentDescriptor =
+        new CommittingSegmentDescriptor(segmentName, nextOffset, SEGMENT_SIZE_IN_BYTES, segmentLocation);
+    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    return committingSegmentDescriptor;
+  }
+
+  private CommittingSegmentDescriptor createCommittingSegmentDescriptor(String segmentName, String nextOffset) {
+    return createCommittingSegmentDescriptor(segmentName, nextOffset, SEGMENT_LOCATION_PREFIX + segmentName);
+  }
+
+  private CommittingSegmentDescriptor createCommittingSegmentDescriptor(String segmentName) {
+    return createCommittingSegmentDescriptor(segmentName, NEXT_OFFSET);
+  }
+
   /**
    * Test cases for new table being created, and initial segments setup that follows.
    */
@@ -226,8 +243,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     IdealState idealState = new IdealState(REALTIME_TABLE_NAME);
     List<StreamMetadata> streamMetadataList = Collections.singletonList(
         new StreamMetadata(segmentManager._streamConfigs.get(0), 3,
-            Arrays.asList(
-                new PartitionGroupMetadata(0, PARTITION_OFFSET, 5),
+            Arrays.asList(new PartitionGroupMetadata(0, PARTITION_OFFSET, 5),
                 new PartitionGroupMetadata(1, PARTITION_OFFSET, 10),
                 new PartitionGroupMetadata(2, PARTITION_OFFSET, 0))));
     segmentManager.setUpNewTable(segmentManager._tableConfig, idealState, streamMetadataList);
@@ -264,8 +280,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     IdealState idealState = new IdealState(REALTIME_TABLE_NAME);
     List<StreamMetadata> streamMetadataList = Collections.singletonList(
         new StreamMetadata(segmentManager._streamConfigs.get(0), 2,
-            Arrays.asList(
-                new PartitionGroupMetadata(0, PARTITION_OFFSET),
+            Arrays.asList(new PartitionGroupMetadata(0, PARTITION_OFFSET),
                 new PartitionGroupMetadata(1, PARTITION_OFFSET))));
     segmentManager.setUpNewTable(segmentManager._tableConfig, idealState, streamMetadataList);
 
@@ -301,10 +316,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     // Commit a segment for partition group 0
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    String nextOffset = new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString();
-    CommittingSegmentDescriptor committingSegmentDescriptor =
-        new CommittingSegmentDescriptor(committingSegment, nextOffset, SEGMENT_SIZE_IN_BYTES);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     // Verify instance states for committed segment and new consuming segment
@@ -323,7 +335,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     SegmentZKMetadata committedSegmentZKMetadata = segmentManager._segmentZKMetadataMap.get(committingSegment);
     assertEquals(committedSegmentZKMetadata.getStatus(), Status.DONE);
     assertEquals(committedSegmentZKMetadata.getStartOffset(), PARTITION_OFFSET.toString());
-    assertEquals(committedSegmentZKMetadata.getEndOffset(), nextOffset);
+    assertEquals(committedSegmentZKMetadata.getEndOffset(), NEXT_OFFSET);
     assertEquals(committedSegmentZKMetadata.getCreationTime(), CURRENT_TIME_MS);
     assertEquals(committedSegmentZKMetadata.getCrc(), Long.parseLong(CRC));
     assertEquals(committedSegmentZKMetadata.getDataCrc(), Long.parseLong(DATA_CRC));
@@ -333,15 +345,14 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     SegmentZKMetadata consumingSegmentZKMetadata = segmentManager._segmentZKMetadataMap.get(consumingSegment);
     assertEquals(consumingSegmentZKMetadata.getStatus(), Status.IN_PROGRESS);
-    assertEquals(consumingSegmentZKMetadata.getStartOffset(), nextOffset);
+    assertEquals(consumingSegmentZKMetadata.getStartOffset(), NEXT_OFFSET);
     assertEquals(committedSegmentZKMetadata.getCreationTime(), CURRENT_TIME_MS);
 
     // Turn one instance of the consuming segment OFFLINE and commit the segment
     consumingSegmentInstanceStateMap.entrySet().iterator().next().setValue(SegmentStateModel.OFFLINE);
     committingSegment = consumingSegment;
-    committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS + NUM_DOCS).toString(), 0L);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment,
+        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS + NUM_DOCS).toString());
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     // Verify instance states for committed segment and new consuming segment
@@ -373,17 +384,14 @@ public class PinotLLCRealtimeSegmentManagerTest {
     List<PartitionGroupMetadata> filteredList = new ArrayList<>(originalSm.getPartitionGroupMetadataList());
     filteredList.remove(0);
     segmentManager._streamMetadataList = Collections.singletonList(
-        new StreamMetadata(originalSm.getStreamConfig(),
-            originalSm.getNumPartitions(), filteredList));
+        new StreamMetadata(originalSm.getStreamConfig(), originalSm.getNumPartitions(), filteredList));
 
     // Commit a segment for partition 0 - No new entries created for partition which reached end of life
     committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 2, CURRENT_TIME_MS).getSegmentName();
     String committingSegmentStartOffset = segmentManager._segmentZKMetadataMap.get(committingSegment).getStartOffset();
     String committingSegmentEndOffset =
         new LongMsgOffset(Long.parseLong(committingSegmentStartOffset) + NUM_DOCS).toString();
-    committingSegmentDescriptor =
-        new CommittingSegmentDescriptor(committingSegment, committingSegmentEndOffset, SEGMENT_SIZE_IN_BYTES);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment, committingSegmentEndOffset);
     int instanceStateMapSize = instanceStatesMap.size();
     int metadataMapSize = segmentManager._segmentZKMetadataMap.size();
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
@@ -431,8 +439,8 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     // Provide a segment that is not in CONSUMING state (non-existent); should be ignored without exception
     String nonConsumingSegment = "nonExistingSegment";
-    Set<String> committed = segmentManager.forceCommit(REALTIME_TABLE_NAME, null, nonConsumingSegment,
-        BatchConfig.of(1, 1, 5));
+    Set<String> committed =
+        segmentManager.forceCommit(REALTIME_TABLE_NAME, null, nonConsumingSegment, BatchConfig.of(1, 1, 5));
     assertTrue(committed.isEmpty(), "Expected no segments to be committed when only non-consuming segments provided");
   }
 
@@ -452,8 +460,8 @@ public class PinotLLCRealtimeSegmentManagerTest {
     segmentManager._idealState.setPartitionState(consumingSegment, "Server_0", SegmentStateModel.CONSUMING);
 
     try {
-      Set<String> committed = segmentManager.forceCommit(REALTIME_TABLE_NAME, null, consumingSegment,
-          BatchConfig.of(1, 1, 5));
+      Set<String> committed =
+          segmentManager.forceCommit(REALTIME_TABLE_NAME, null, consumingSegment, BatchConfig.of(1, 1, 5));
       assertFalse(committed.isEmpty(), "Expected segments to be committed");
       // If we reach here without exception, test passes
     } catch (IllegalStateException e) {
@@ -495,8 +503,8 @@ public class PinotLLCRealtimeSegmentManagerTest {
     String consumingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
     pausedIdealState.setPartitionState(consumingSegment, "Server_0", SegmentStateModel.CONSUMING);
 
-    doReturn(pausedIdealState).when(segmentManager).updatePauseStateInIdealState(eq(tableNameWithType), eq(true),
-        eq(PauseState.ReasonCode.ADMINISTRATIVE), any());
+    doReturn(pausedIdealState).when(segmentManager)
+        .updatePauseStateInIdealState(eq(tableNameWithType), eq(true), eq(PauseState.ReasonCode.ADMINISTRATIVE), any());
 
     BatchConfig batchConfig = BatchConfig.of(2, 3, 10);
     final BatchConfig[] capturedConfig = new BatchConfig[1];
@@ -544,10 +552,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
       // Commit a segment for partition group 0
       String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-      String endOffset = new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString();
-      CommittingSegmentDescriptor committingSegmentDescriptor =
-          new CommittingSegmentDescriptor(committingSegment, endOffset, SEGMENT_SIZE_IN_BYTES);
-      committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+      CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
       // Verify instance states for committed segment and new consuming segment
@@ -566,7 +571,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
       SegmentZKMetadata committedSegmentZKMetadata = segmentManager._segmentZKMetadataMap.get(committingSegment);
       assertEquals(committedSegmentZKMetadata.getStatus(), Status.DONE);
       assertEquals(committedSegmentZKMetadata.getStartOffset(), PARTITION_OFFSET.toString());
-      assertEquals(committedSegmentZKMetadata.getEndOffset(), endOffset);
+      assertEquals(committedSegmentZKMetadata.getEndOffset(), NEXT_OFFSET);
       assertEquals(committedSegmentZKMetadata.getCreationTime(), CURRENT_TIME_MS);
       assertEquals(committedSegmentZKMetadata.getCrc(), Long.parseLong(CRC));
       assertEquals(committedSegmentZKMetadata.getIndexVersion(), SEGMENT_VERSION.name());
@@ -611,10 +616,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
       // Commit a segment for partition group 0
       String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-      String endOffset = new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString();
-      CommittingSegmentDescriptor committingSegmentDescriptor =
-          new CommittingSegmentDescriptor(committingSegment, endOffset, SEGMENT_SIZE_IN_BYTES);
-      committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+      CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
       // Verify instance states for committed segment and new consuming segment
@@ -633,7 +635,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
       SegmentZKMetadata committedSegmentZKMetadata = segmentManager._segmentZKMetadataMap.get(committingSegment);
       assertEquals(committedSegmentZKMetadata.getStatus(), Status.DONE);
       assertEquals(committedSegmentZKMetadata.getStartOffset(), PARTITION_OFFSET.toString());
-      assertEquals(committedSegmentZKMetadata.getEndOffset(), endOffset);
+      assertEquals(committedSegmentZKMetadata.getEndOffset(), NEXT_OFFSET);
       assertEquals(committedSegmentZKMetadata.getCreationTime(), CURRENT_TIME_MS);
       assertEquals(committedSegmentZKMetadata.getCrc(), Long.parseLong(CRC));
       assertEquals(committedSegmentZKMetadata.getIndexVersion(), SEGMENT_VERSION.name());
@@ -674,9 +676,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     // 2 partitions commit segment
     for (int partitionGroupId = 0; partitionGroupId < 2; partitionGroupId++) {
       String segmentName = new LLCSegmentName(RAW_TABLE_NAME, partitionGroupId, 0, CURRENT_TIME_MS).getSegmentName();
-      CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(segmentName,
-          new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L);
-      committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+      CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(segmentName);
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
     }
     testSetUpNewPartitions(segmentManager, false);
@@ -848,9 +848,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     // 2 partitions commit segment
     for (int partitionGroupId = 0; partitionGroupId < 2; partitionGroupId++) {
       String segmentName = new LLCSegmentName(RAW_TABLE_NAME, partitionGroupId, 0, CURRENT_TIME_MS).getSegmentName();
-      CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(segmentName,
-          new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L);
-      committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+      CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(segmentName);
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
     }
 
@@ -891,9 +889,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
       int sequenceNumber = partitionGroupId == 0 ? 2 : 0;
       String segmentName =
           new LLCSegmentName(RAW_TABLE_NAME, partitionGroupId, sequenceNumber, CURRENT_TIME_MS).getSegmentName();
-      CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(segmentName,
-          new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L);
-      committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+      CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(segmentName);
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
     }
 
@@ -931,17 +927,15 @@ public class PinotLLCRealtimeSegmentManagerTest {
     List<PartitionGroupMetadata> filteredPgList = new ArrayList<>(origSm.getPartitionGroupMetadataList());
     filteredPgList.remove(1);
     segmentManager._streamMetadataList = Collections.singletonList(
-        new StreamMetadata(origSm.getStreamConfig(),
-            origSm.getNumPartitions(), filteredPgList));
+        new StreamMetadata(origSm.getStreamConfig(), origSm.getNumPartitions(), filteredPgList));
     // noop
     testRepairs(segmentManager, Collections.emptyList());
 
     // 1 commits segment - should not create new metadata or CONSUMING segment
     String segmentName = new LLCSegmentName(RAW_TABLE_NAME, 1, 1, CURRENT_TIME_MS).getSegmentName();
     String startOffset = segmentManager._segmentZKMetadataMap.get(segmentName).getStartOffset();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(segmentName,
-        new LongMsgOffset(Long.parseLong(startOffset) + NUM_DOCS).toString(), 0L);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(segmentName,
+        new LongMsgOffset(Long.parseLong(startOffset) + NUM_DOCS).toString());
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
     // ONLINE in IS and metadata DONE, but end of shard (not present in partition group list), so don't repair
     testRepairs(segmentManager, Lists.newArrayList(1));
@@ -975,10 +969,10 @@ public class PinotLLCRealtimeSegmentManagerTest {
     consumingSegmentInstanceStateMap.put(offlineInstance, SegmentStateModel.OFFLINE);
 
     // Verify we have mixed state: 2 CONSUMING, 1 OFFLINE
-    long consumingCount = consumingSegmentInstanceStateMap.values().stream()
-        .filter(s -> s.equals(SegmentStateModel.CONSUMING)).count();
-    long offlineCount = consumingSegmentInstanceStateMap.values().stream()
-        .filter(s -> s.equals(SegmentStateModel.OFFLINE)).count();
+    long consumingCount =
+        consumingSegmentInstanceStateMap.values().stream().filter(s -> s.equals(SegmentStateModel.CONSUMING)).count();
+    long offlineCount =
+        consumingSegmentInstanceStateMap.values().stream().filter(s -> s.equals(SegmentStateModel.OFFLINE)).count();
     assertEquals(consumingCount, 2);
     assertEquals(offlineCount, 1);
 
@@ -1115,8 +1109,8 @@ public class PinotLLCRealtimeSegmentManagerTest {
       Map<String, String> instanceStateMap = entry.getValue();
 
       // Skip segments with all instances OFFLINE
-      if (instanceStateMap.containsValue(SegmentStateModel.ONLINE) || instanceStateMap
-          .containsValue(SegmentStateModel.CONSUMING)) {
+      if (instanceStateMap.containsValue(SegmentStateModel.ONLINE) || instanceStateMap.containsValue(
+          SegmentStateModel.CONSUMING)) {
         LLCSegmentName llcSegmentName = new LLCSegmentName(segmentName);
         int partitionsId = llcSegmentName.getPartitionGroupId();
         Map<Integer, String> sequenceNumberToSegmentMap = partitionGroupIdToSegmentsMap.get(partitionsId);
@@ -1182,9 +1176,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     // Commit a segment for partition group 0
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
 
     try {
       segmentManager1.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
@@ -1287,8 +1279,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
       // Expected
     }
     try {
-      segmentManager.reduceSegmentSizeAndReset(new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS),
-          1000);
+      segmentManager.reduceSegmentSizeAndReset(new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS), 1000);
       fail();
     } catch (IllegalStateException e) {
       // Expected
@@ -1312,22 +1303,18 @@ public class PinotLLCRealtimeSegmentManagerTest {
     // Test case 1: segment location with vip format.
     // Commit a segment for partition group 0
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    String segmentLocationVIP = "http://control_vip/segments/segment1";
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, segmentLocationVIP);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     SegmentZKMetadata segmentZKMetadata =
         segmentManager.getSegmentZKMetadata(REALTIME_TABLE_NAME, committingSegment, null);
-    Assert.assertEquals(segmentZKMetadata.getDownloadUrl(), segmentLocationVIP);
+    Assert.assertEquals(segmentZKMetadata.getDownloadUrl(), SEGMENT_LOCATION_PREFIX + committingSegment);
 
-    // Test case 2: segment location with peer format: peer://segment1, verify that an empty string is stored in zk.
+    // Test case 2: segment location with peer format: peer://segment, verify that an empty string is stored in zk.
     committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 1, CURRENT_TIME_MS).getSegmentName();
-    String peerSegmentLocation = CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME + "/segment1";
-    committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, peerSegmentLocation);
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    String peerSegmentLocation = CommonConstants.Segment.PEER_SEGMENT_DOWNLOAD_SCHEME + "/" + committingSegment;
+    committingSegmentDescriptor =
+        createCommittingSegmentDescriptor(committingSegment, NEXT_OFFSET, peerSegmentLocation);
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     segmentZKMetadata = segmentManager.getSegmentZKMetadata(REALTIME_TABLE_NAME, committingSegment, null);
@@ -1342,9 +1329,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     setUpNewTable(segmentManager, 2, 5, 4);
 
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, "http://control_vip/segments/1");
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
 
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
@@ -1358,15 +1343,12 @@ public class PinotLLCRealtimeSegmentManagerTest {
         spy(new FakePinotLLCRealtimeSegmentManager(mockHelixResourceManager));
     setUpNewTable(segmentManager, 2, 5, 4);
     segmentManager._streamMetadataList = Collections.singletonList(
-        new StreamMetadata(segmentManager._streamConfigs.get(0), 4,
-            IntStream.range(0, 4)
-                .mapToObj(partition -> new PartitionGroupMetadata(partition, PARTITION_OFFSET))
-                .collect(Collectors.toList())));
+        new StreamMetadata(segmentManager._streamConfigs.get(0), 4, IntStream.range(0, 4)
+            .mapToObj(partition -> new PartitionGroupMetadata(partition, PARTITION_OFFSET))
+            .collect(Collectors.toList())));
 
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, "http://control_vip/segments/1");
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
 
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
@@ -1378,29 +1360,24 @@ public class PinotLLCRealtimeSegmentManagerTest {
     FakePinotLLCRealtimeSegmentManager segmentManager = spy(new FakePinotLLCRealtimeSegmentManager());
     setUpNewTable(segmentManager, 2, 5, 4);
     segmentManager._streamMetadataList = Collections.singletonList(
-        new StreamMetadata(segmentManager._streamConfigs.get(0), 4,
-            IntStream.range(0, 4)
-                .mapToObj(partition -> new PartitionGroupMetadata(partition, PARTITION_OFFSET))
-                .collect(Collectors.toList())));
+        new StreamMetadata(segmentManager._streamConfigs.get(0), 4, IntStream.range(0, 4)
+            .mapToObj(partition -> new PartitionGroupMetadata(partition, PARTITION_OFFSET))
+            .collect(Collectors.toList())));
 
-    PauseState pauseState =
-        new PauseState(false, PauseState.ReasonCode.ADMINISTRATIVE, "pause-topic-for-test",
-            Long.toString(CURRENT_TIME_MS), Collections.singletonList(0));
-    segmentManager._idealState.getRecord().setSimpleField(PinotLLCRealtimeSegmentManager.PAUSE_STATE,
-        pauseState.toJsonString());
+    PauseState pauseState = new PauseState(false, PauseState.ReasonCode.ADMINISTRATIVE, "pause-topic-for-test",
+        Long.toString(CURRENT_TIME_MS), Collections.singletonList(0));
+    segmentManager._idealState.getRecord()
+        .setSimpleField(PinotLLCRealtimeSegmentManager.PAUSE_STATE, pauseState.toJsonString());
 
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, "http://control_vip/segments/1");
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
 
     String expectedNewConsumingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 1, CURRENT_TIME_MS).getSegmentName();
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     assertFalse(segmentManager._segmentZKMetadataMap.containsKey(expectedNewConsumingSegment));
     assertFalse(segmentManager._idealState.getRecord().getMapFields().containsKey(expectedNewConsumingSegment));
-    ZkHelixPropertyStore<ZNRecord> propertyStore =
-        segmentManager._mockResourceManager.getPropertyStore();
+    ZkHelixPropertyStore<ZNRecord> propertyStore = segmentManager._mockResourceManager.getPropertyStore();
     verify(propertyStore, never()).remove(anyString(), eq(AccessOption.PERSISTENT));
   }
 
@@ -1408,21 +1385,19 @@ public class PinotLLCRealtimeSegmentManagerTest {
   public void testCommitSegmentMetadataCleansUpMetadataWhenTablePaused() {
     FakePinotLLCRealtimeSegmentManager segmentManager = new FakePinotLLCRealtimeSegmentManager();
     setUpNewTable(segmentManager, 2, 5, 4);
-    ZkHelixPropertyStore<ZNRecord> propertyStore =
-        segmentManager._mockResourceManager.getPropertyStore();
+    ZkHelixPropertyStore<ZNRecord> propertyStore = segmentManager._mockResourceManager.getPropertyStore();
     when(propertyStore.remove(anyString(), eq(AccessOption.PERSISTENT))).thenReturn(true);
 
-    PauseState pauseState = new PauseState(true, PauseState.ReasonCode.ADMINISTRATIVE, "pause-for-test",
-        Long.toString(CURRENT_TIME_MS), Collections.emptyList());
-    segmentManager._idealState.getRecord().setSimpleField(PinotLLCRealtimeSegmentManager.PAUSE_STATE,
-        pauseState.toJsonString());
+    PauseState pauseState =
+        new PauseState(true, PauseState.ReasonCode.ADMINISTRATIVE, "pause-for-test", Long.toString(CURRENT_TIME_MS),
+            Collections.emptyList());
+    segmentManager._idealState.getRecord()
+        .setSimpleField(PinotLLCRealtimeSegmentManager.PAUSE_STATE, pauseState.toJsonString());
     segmentManager._idealState.getRecord()
         .setSimpleField(PinotLLCRealtimeSegmentManager.IS_TABLE_PAUSED, Boolean.TRUE.toString());
 
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, "http://control_vip/segments/1");
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     String newConsumingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 1, CURRENT_TIME_MS).getSegmentName();
@@ -1436,20 +1411,16 @@ public class PinotLLCRealtimeSegmentManagerTest {
   public void testCommitSegmentMetadataCleansUpMetadataWhenTopicPaused() {
     FakePinotLLCRealtimeSegmentManager segmentManager = new FakePinotLLCRealtimeSegmentManager();
     setUpNewTable(segmentManager, 2, 5, 4);
-    ZkHelixPropertyStore<ZNRecord> propertyStore =
-        segmentManager._mockResourceManager.getPropertyStore();
+    ZkHelixPropertyStore<ZNRecord> propertyStore = segmentManager._mockResourceManager.getPropertyStore();
     when(propertyStore.remove(anyString(), eq(AccessOption.PERSISTENT))).thenReturn(true);
 
-    PauseState pauseState =
-        new PauseState(false, PauseState.ReasonCode.ADMINISTRATIVE, "pause-topic-for-test",
-            Long.toString(CURRENT_TIME_MS), Collections.singletonList(0));
-    segmentManager._idealState.getRecord().setSimpleField(PinotLLCRealtimeSegmentManager.PAUSE_STATE,
-        pauseState.toJsonString());
+    PauseState pauseState = new PauseState(false, PauseState.ReasonCode.ADMINISTRATIVE, "pause-topic-for-test",
+        Long.toString(CURRENT_TIME_MS), Collections.singletonList(0));
+    segmentManager._idealState.getRecord()
+        .setSimpleField(PinotLLCRealtimeSegmentManager.PAUSE_STATE, pauseState.toJsonString());
 
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, "http://control_vip/segments/1");
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
     segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
 
     String newConsumingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 1, CURRENT_TIME_MS).getSegmentName();
@@ -1463,17 +1434,16 @@ public class PinotLLCRealtimeSegmentManagerTest {
   public void testCommitSegmentMetadataCleansUpMetadataWhenCommittingSegmentNotConsuming() {
     FakePinotLLCRealtimeSegmentManager segmentManager = new FakePinotLLCRealtimeSegmentManager();
     setUpNewTable(segmentManager, 2, 5, 4);
-    ZkHelixPropertyStore<ZNRecord> propertyStore =
-        segmentManager._mockResourceManager.getPropertyStore();
+    ZkHelixPropertyStore<ZNRecord> propertyStore = segmentManager._mockResourceManager.getPropertyStore();
     when(propertyStore.remove(anyString(), eq(AccessOption.PERSISTENT))).thenReturn(true);
 
     String committingSegment = new LLCSegmentName(RAW_TABLE_NAME, 0, 0, CURRENT_TIME_MS).getSegmentName();
-    segmentManager._idealState.getRecord().getMapFields().get(committingSegment)
+    segmentManager._idealState.getRecord()
+        .getMapFields()
+        .get(committingSegment)
         .replaceAll((instance, state) -> SegmentStateModel.ONLINE);
 
-    CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(committingSegment,
-        new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L, "http://control_vip/segments/1");
-    committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+    CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(committingSegment);
     try {
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
       fail("Expected commitSegmentMetadata to fail when committing segment has no CONSUMING instance");
@@ -1892,11 +1862,13 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     SegmentZKMetadata segZKMeta = mock(SegmentZKMetadata.class);
     PinotHelixResourceManager helixResourceManager = mock(PinotHelixResourceManager.class);
-    when(helixResourceManager.getTableConfig(REALTIME_TABLE_NAME))
-        .thenReturn(new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME).setLLC(true)
-            .setStreamConfigs(FakeStreamConfigUtils.getDefaultLowLevelStreamConfigs().getStreamConfigsMap()).build());
-    PinotLLCRealtimeSegmentManager segmentManager = new FakePinotLLCRealtimeSegmentManager(
-        helixResourceManager, config);
+    when(helixResourceManager.getTableConfig(REALTIME_TABLE_NAME)).thenReturn(
+        new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME)
+            .setLLC(true)
+            .setStreamConfigs(FakeStreamConfigUtils.getDefaultLowLevelStreamConfigs().getStreamConfigsMap())
+            .build());
+    PinotLLCRealtimeSegmentManager segmentManager =
+        new FakePinotLLCRealtimeSegmentManager(helixResourceManager, config);
 
     int numDeletedTmpSegments;
     // case 1: the segmentMetadata download uri is identical to the uri of the tmp segment. Should not delete
@@ -1934,10 +1906,9 @@ public class PinotLLCRealtimeSegmentManagerTest {
             new PartitionGroupConsumptionStatus(1, 12, new LongMsgOffset(123), new LongMsgOffset(345), "ONLINE"));
     doReturn(partitionGroupConsumptionStatusList).when(segmentManagerSpy)
         .getPartitionGroupConsumptionStatusList(idealState, streamConfigs);
-    List<StreamMetadata> streamMetadataList =
-        List.of(new StreamMetadata(streamConfigs.get(0), 2,
-            List.of(new PartitionGroupMetadata(0, new LongMsgOffset(234)),
-                new PartitionGroupMetadata(1, new LongMsgOffset(345)))));
+    List<StreamMetadata> streamMetadataList = List.of(new StreamMetadata(streamConfigs.get(0), 2,
+        List.of(new PartitionGroupMetadata(0, new LongMsgOffset(234)),
+            new PartitionGroupMetadata(1, new LongMsgOffset(345)))));
     doReturn(streamMetadataList).when(segmentManagerSpy)
         .getNewStreamMetadataList(streamConfigs, partitionGroupConsumptionStatusList, idealState);
     partitionIds = segmentManagerSpy.getPartitionIds(streamConfigs, idealState);
@@ -1959,9 +1930,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     // Commit segments for partitions 0 and 1 to get a mix of ONLINE (DONE) and CONSUMING (IN_PROGRESS) segments
     for (int partitionGroupId = 0; partitionGroupId < 2; partitionGroupId++) {
       String segmentName = new LLCSegmentName(RAW_TABLE_NAME, partitionGroupId, 0, CURRENT_TIME_MS).getSegmentName();
-      CommittingSegmentDescriptor committingSegmentDescriptor = new CommittingSegmentDescriptor(segmentName,
-          new LongMsgOffset(PARTITION_OFFSET.getOffset() + NUM_DOCS).toString(), 0L);
-      committingSegmentDescriptor.setSegmentMetadata(mockSegmentMetadata());
+      CommittingSegmentDescriptor committingSegmentDescriptor = createCommittingSegmentDescriptor(segmentName);
       segmentManager.commitSegmentMetadata(REALTIME_TABLE_NAME, committingSegmentDescriptor);
     }
 
@@ -1970,12 +1939,11 @@ public class PinotLLCRealtimeSegmentManagerTest {
     for (Map.Entry<String, SegmentZKMetadata> entry : segmentManager._segmentZKMetadataMap.entrySet()) {
       LLCSegmentName llcSegmentName = new LLCSegmentName(entry.getKey());
       int partitionId = llcSegmentName.getPartitionGroupId();
-      latestSegmentZKMetadataMap.merge(partitionId, entry.getValue(),
-          (existing, candidate) -> {
-            int existingSeq = new LLCSegmentName(existing.getSegmentName()).getSequenceNumber();
-            int candidateSeq = new LLCSegmentName(candidate.getSegmentName()).getSequenceNumber();
-            return candidateSeq > existingSeq ? candidate : existing;
-          });
+      latestSegmentZKMetadataMap.merge(partitionId, entry.getValue(), (existing, candidate) -> {
+        int existingSeq = new LLCSegmentName(existing.getSegmentName()).getSequenceNumber();
+        int candidateSeq = new LLCSegmentName(candidate.getSegmentName()).getSequenceNumber();
+        return candidateSeq > existingSeq ? candidate : existing;
+      });
     }
 
     // Get results from both methods
@@ -2007,8 +1975,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
           "Start offset mismatch for partition " + isStatus.getPartitionGroupId());
       String zkEnd = zkStatus.getEndOffset() != null ? zkStatus.getEndOffset().toString() : null;
       String isEnd = isStatus.getEndOffset() != null ? isStatus.getEndOffset().toString() : null;
-      assertEquals(zkEnd, isEnd,
-          "End offset mismatch for partition " + isStatus.getPartitionGroupId());
+      assertEquals(zkEnd, isEnd, "End offset mismatch for partition " + isStatus.getPartitionGroupId());
       assertEquals(zkStatus.getStatus(), isStatus.getStatus(),
           "Status mismatch for partition " + isStatus.getPartitionGroupId());
     }
@@ -2028,8 +1995,7 @@ public class PinotLLCRealtimeSegmentManagerTest {
     segmentManager._tableConfig.setValidationConfig(segmentsValidationAndRetentionConfig);
     String segmentName = new ArrayList<>(segmentManager._segmentZKMetadataMap.keySet()).get(0);
 
-    SegmentZKMetadata segmentZKMetadata =
-        segmentManager.getSegmentZKMetadata(REALTIME_TABLE_NAME, segmentName, null);
+    SegmentZKMetadata segmentZKMetadata = segmentManager.getSegmentZKMetadata(REALTIME_TABLE_NAME, segmentName, null);
     int prevRowSize = segmentZKMetadata.getSizeThresholdToFlushSegment();
     segmentManager.reduceSegmentSizeAndReset(new LLCSegmentName(segmentName), 100);
     Assert.assertEquals(Math.min(100 / 2, prevRowSize / 2),
@@ -2042,13 +2008,11 @@ public class PinotLLCRealtimeSegmentManagerTest {
     FakePinotLLCRealtimeSegmentManager realtimeSegmentManager =
         new FakePinotLLCRealtimeSegmentManager(mockHelixResourceManager);
     IdealState idealState = mock(IdealState.class);
-    Map<String, Map<String, String>> map = Map.of(
-        "seg0", Map.of("i1", "CONSUMING", "i4", "ONLINE"),
-        "seg1", Map.of("i2", "CONSUMING"),
-        "seg2", Map.of("i3", "CONSUMING", "i2", "OFFLINE"),
-        "seg3", Map.of("i4", "CONSUMING", "i2", "CONSUMING", "i3", "CONSUMING"),
-        "seg4", Map.of("i5", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING")
-    );
+    Map<String, Map<String, String>> map =
+        Map.of("seg0", Map.of("i1", "CONSUMING", "i4", "ONLINE"), "seg1", Map.of("i2", "CONSUMING"), "seg2",
+            Map.of("i3", "CONSUMING", "i2", "OFFLINE"), "seg3",
+            Map.of("i4", "CONSUMING", "i2", "CONSUMING", "i3", "CONSUMING"), "seg4",
+            Map.of("i5", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING"));
 
     ZNRecord znRecord = mock(ZNRecord.class);
     when(znRecord.getMapFields()).thenReturn(map);
@@ -2058,13 +2022,10 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     Map<String, Queue<String>> instanceToConsumingSegments =
         realtimeSegmentManager.getInstanceToConsumingSegments(idealState, targetConsumingSegment);
-    assertEquals(instanceToConsumingSegments, Map.of(
-        "i1", new LinkedList<>(List.of("seg0", "seg4")),
-        "i2", new LinkedList<>(List.of("seg1", "seg3")),
-        "i3", new LinkedList<>(List.of("seg2", "seg3", "seg4")),
-        "i4", new LinkedList<>(List.of("seg3")),
-        "i5", new LinkedList<>(List.of("seg4"))
-    ));
+    assertEquals(instanceToConsumingSegments,
+        Map.of("i1", new LinkedList<>(List.of("seg0", "seg4")), "i2", new LinkedList<>(List.of("seg1", "seg3")), "i3",
+            new LinkedList<>(List.of("seg2", "seg3", "seg4")), "i4", new LinkedList<>(List.of("seg3")), "i5",
+            new LinkedList<>(List.of("seg4"))));
   }
 
   @Test
@@ -2074,15 +2035,13 @@ public class PinotLLCRealtimeSegmentManagerTest {
         new FakePinotLLCRealtimeSegmentManager(mockHelixResourceManager);
     IdealState idealState = mock(IdealState.class);
 
-    Map<String, Map<String, String>> map = Map.of(
-        "seg0", Map.of("i1", "CONSUMING", "i4", "ONLINE"),
-        "seg1", Map.of("i2", "CONSUMING"),
-        "seg2", Map.of("i3", "CONSUMING", "i2", "OFFLINE"),
-        "seg3", Map.of("i4", "CONSUMING", "i2", "CONSUMING", "i3", "CONSUMING"),
-        "seg4", Map.of("i5", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING"),
-        "seg5", Map.of("i6", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING"),
-        "seg6", Map.of("i7", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING")
-    );
+    Map<String, Map<String, String>> map =
+        Map.of("seg0", Map.of("i1", "CONSUMING", "i4", "ONLINE"), "seg1", Map.of("i2", "CONSUMING"), "seg2",
+            Map.of("i3", "CONSUMING", "i2", "OFFLINE"), "seg3",
+            Map.of("i4", "CONSUMING", "i2", "CONSUMING", "i3", "CONSUMING"), "seg4",
+            Map.of("i5", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING"), "seg5",
+            Map.of("i6", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING"), "seg6",
+            Map.of("i7", "CONSUMING", "i1", "CONSUMING", "i3", "CONSUMING"));
 
     ZNRecord znRecord = mock(ZNRecord.class);
     when(znRecord.getMapFields()).thenReturn(map);
@@ -2092,18 +2051,11 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     List<Set<String>> segmentBatchList =
         realtimeSegmentManager.getSegmentBatchList(idealState, targetConsumingSegment, 2);
-    assertEquals(segmentBatchList, List.of(
-        Set.of("seg0", "seg1"),
-        Set.of("seg2", "seg3"),
-        Set.of("seg4", "seg5"),
-        Set.of("seg6")
-    ));
+    assertEquals(segmentBatchList,
+        List.of(Set.of("seg0", "seg1"), Set.of("seg2", "seg3"), Set.of("seg4", "seg5"), Set.of("seg6")));
 
     segmentBatchList = realtimeSegmentManager.getSegmentBatchList(idealState, targetConsumingSegment, 4);
-    assertEquals(segmentBatchList, List.of(
-        Set.of("seg0", "seg1", "seg2", "seg3"),
-        Set.of("seg4", "seg5", "seg6")
-    ));
+    assertEquals(segmentBatchList, List.of(Set.of("seg0", "seg1", "seg2", "seg3"), Set.of("seg4", "seg5", "seg6")));
   }
 
   @Test
@@ -2158,12 +2110,8 @@ public class PinotLLCRealtimeSegmentManagerTest {
     String realtimeTableName = "githubEvents_2_REALTIME";
 
     // Create test segments
-    List<String> testSegments = List.of(
-        "githubEvents_2__0__0__20250210T1142Z",
-        "githubEvents_2__0__1__20250210T1142Z",
-        "githubEvents_2__0__2__20250210T1142Z",
-        "githubEvents_2__0__3__20250210T1142Z"
-    );
+    List<String> testSegments = List.of("githubEvents_2__0__0__20250210T1142Z", "githubEvents_2__0__1__20250210T1142Z",
+        "githubEvents_2__0__2__20250210T1142Z", "githubEvents_2__0__3__20250210T1142Z");
 
     // mock response of propertyStore
     String committingSegmentsListPath =
@@ -2172,31 +2120,30 @@ public class PinotLLCRealtimeSegmentManagerTest {
     ZNRecord znRecord = new ZNRecord(realtimeTableName);
     znRecord.setListField(COMMITTING_SEGMENTS, testSegments);
 
-    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(znRecord);
+    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT))).thenReturn(
+        znRecord);
 
     // mock response for fetching segmentZKMetadata with different scenarios
     // Segment 0: COMMITTING status
     SegmentZKMetadata segmentZKMetadata0 = mock(SegmentZKMetadata.class);
     when(segmentZKMetadata0.getStatus()).thenReturn(Status.COMMITTING);
-    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(0)))
-        .thenReturn(segmentZKMetadata0);
+    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(0))).thenReturn(
+        segmentZKMetadata0);
 
     // Segment 1: null metadata (deleted)
-    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(1)))
-        .thenReturn(null);
+    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(1))).thenReturn(null);
 
     // Segment 2: DONE status
     SegmentZKMetadata segmentZKMetadata2 = mock(SegmentZKMetadata.class);
     when(segmentZKMetadata2.getStatus()).thenReturn(Status.DONE);
-    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(2)))
-        .thenReturn(segmentZKMetadata2);
+    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(2))).thenReturn(
+        segmentZKMetadata2);
 
     // Segment 3: COMMITTING status
     SegmentZKMetadata segmentZKMetadata3 = mock(SegmentZKMetadata.class);
     when(segmentZKMetadata3.getStatus()).thenReturn(Status.COMMITTING);
-    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(3)))
-        .thenReturn(segmentZKMetadata3);
+    when(pinotHelixResourceManager.getSegmentZKMetadata(realtimeTableName, testSegments.get(3))).thenReturn(
+        segmentZKMetadata3);
 
     // Execute test
     List<String> result = segmentManager.getCommittingSegments(realtimeTableName);
@@ -2210,15 +2157,14 @@ public class PinotLLCRealtimeSegmentManagerTest {
     assertEquals(result, List.of(testSegments.get(3)));
 
     // Test null case
-    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(null);
+    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT))).thenReturn(null);
     result = segmentManager.getCommittingSegments(realtimeTableName);
     assertTrue(result.isEmpty());
 
     // Test empty COMMITTING_SEGMENTS field
     ZNRecord emptyRecord = new ZNRecord("CommittingSegments");
-    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(emptyRecord);
+    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT))).thenReturn(
+        emptyRecord);
     result = segmentManager.getCommittingSegments(realtimeTableName);
     assertTrue(result.isEmpty());
   }
@@ -2271,22 +2217,20 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     // Test 1: Initial creation with mixed status segments
     List<String> newSegments = Arrays.asList(committingSegment1, committingSegment2);
-    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(null);
-    when(zkHelixPropertyStore.create(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(true);
+    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT))).thenReturn(null);
+    when(zkHelixPropertyStore.create(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT))).thenReturn(
+        true);
 
     assertTrue(segmentManager.syncCommittingSegments(realtimeTableName, newSegments));
 
     // Test 2: Syncing with existing segments including DONE and missing metadata
     ZNRecord existingRecord = new ZNRecord(realtimeTableName);
-    existingRecord.setListField(COMMITTING_SEGMENTS,
-        Arrays.asList(committingSegment2, doneSegment));
+    existingRecord.setListField(COMMITTING_SEGMENTS, Arrays.asList(committingSegment2, doneSegment));
 
-    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(existingRecord);
-    when(zkHelixPropertyStore.set(eq(committingSegmentsListPath), any(), anyInt(), eq(AccessOption.PERSISTENT)))
-        .thenReturn(true);
+    when(zkHelixPropertyStore.get(eq(committingSegmentsListPath), any(), eq(AccessOption.PERSISTENT))).thenReturn(
+        existingRecord);
+    when(zkHelixPropertyStore.set(eq(committingSegmentsListPath), any(), anyInt(),
+        eq(AccessOption.PERSISTENT))).thenReturn(true);
 
     // There should not be any duplicates and the doneSegment should be removed from the list
     assertTrue(segmentManager.syncCommittingSegments(realtimeTableName,
@@ -2295,8 +2239,8 @@ public class PinotLLCRealtimeSegmentManagerTest {
         new HashSet<>(List.of(committingSegment1, committingSegment2)));
 
     // Test 3: Error handling during ZooKeeper operations
-    when(zkHelixPropertyStore.set(eq(committingSegmentsListPath), any(), anyInt(), eq(AccessOption.PERSISTENT)))
-        .thenThrow(new RuntimeException("ZooKeeper operation failed"));
+    when(zkHelixPropertyStore.set(eq(committingSegmentsListPath), any(), anyInt(),
+        eq(AccessOption.PERSISTENT))).thenThrow(new RuntimeException("ZooKeeper operation failed"));
     assertFalse(segmentManager.syncCommittingSegments(realtimeTableName, newSegments));
   }
 
@@ -2381,16 +2325,18 @@ public class PinotLLCRealtimeSegmentManagerTest {
 
     void makeTableConfig() {
       Map<String, String> streamConfigs = FakeStreamConfigUtils.getDefaultLowLevelStreamConfigs().getStreamConfigsMap();
-      _tableConfig =
-          new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME).setNumReplicas(_numReplicas)
-              .setStreamConfigs(streamConfigs).build();
+      _tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME)
+          .setNumReplicas(_numReplicas)
+          .setStreamConfigs(streamConfigs)
+          .build();
       _streamConfigs = IngestionConfigUtils.getStreamConfigs(_tableConfig);
     }
 
     void makeTableConfig(Map<String, String> streamConfigMap) {
-      _tableConfig =
-          new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME).setNumReplicas(_numReplicas)
-              .setStreamConfigs(streamConfigMap).build();
+      _tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME)
+          .setNumReplicas(_numReplicas)
+          .setStreamConfigs(streamConfigMap)
+          .build();
       _streamConfigs = IngestionConfigUtils.getStreamConfigs(_tableConfig);
     }
 
@@ -2476,9 +2422,10 @@ public class PinotLLCRealtimeSegmentManagerTest {
         String newSegmentName, SegmentAssignment segmentAssignment,
         Map<InstancePartitionsType, InstancePartitions> instancePartitionsMap) {
       Map<String, String> committingSegmentInstanceStateMap = _idealState.getInstanceStateMap(committingSegmentName);
-      Preconditions.checkState(committingSegmentInstanceStateMap != null && committingSegmentInstanceStateMap
-              .containsValue(SegmentStateModel.CONSUMING),
-          "Failed to find instance in CONSUMING state in IdealState for segment: %s", committingSegmentName);
+      Preconditions.checkState(
+          committingSegmentInstanceStateMap != null && committingSegmentInstanceStateMap.containsValue(
+              SegmentStateModel.CONSUMING), "Failed to find instance in CONSUMING state in IdealState for segment: %s",
+          committingSegmentName);
       updateInstanceStatesForNewConsumingSegment(_idealState.getRecord().getMapFields(), committingSegmentName,
           isTablePaused(_idealState) || isTopicPaused(_idealState, committingSegmentName) ? null : newSegmentName,
           segmentAssignment, instancePartitionsMap);
@@ -2499,9 +2446,9 @@ public class PinotLLCRealtimeSegmentManagerTest {
       if (_streamMetadataList != null) {
         return _streamMetadataList;
       } else {
-        List<PartitionGroupMetadata> partitionGroupMetadataList =
-            IntStream.range(0, _numPartitions).mapToObj(i -> new PartitionGroupMetadata(i, PARTITION_OFFSET))
-                .collect(Collectors.toList());
+        List<PartitionGroupMetadata> partitionGroupMetadataList = IntStream.range(0, _numPartitions)
+            .mapToObj(i -> new PartitionGroupMetadata(i, PARTITION_OFFSET))
+            .collect(Collectors.toList());
         return Collections.singletonList(
             new StreamMetadata(streamConfigs.get(0), _numPartitions, partitionGroupMetadataList));
       }
diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdaterTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdaterTest.java
index 7a9f01b2671..a85f22cd275 100644
--- a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdaterTest.java
+++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/core/realtime/segment/FlushThresholdUpdaterTest.java
@@ -139,8 +139,7 @@ public class FlushThresholdUpdaterTest {
 
     for (long[] segmentSizesMB : Arrays.asList(EXPONENTIAL_GROWTH_SEGMENT_SIZES_MB, LOGARITHMIC_GROWTH_SEGMENT_SIZES_MB,
         STEPS_SEGMENT_SIZES_MB)) {
-      SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater =
-          new SegmentSizeBasedFlushThresholdUpdater(REALTIME_TABLE_NAME, streamConfig.getTopicName());
+      SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater = new SegmentSizeBasedFlushThresholdUpdater();
 
       // Start consumption
       SegmentZKMetadata newSegmentZKMetadata = getNewSegmentZKMetadata(0);
@@ -175,8 +174,7 @@ public class FlushThresholdUpdaterTest {
 
     for (long[] segmentSizesMB : Arrays.asList(EXPONENTIAL_GROWTH_SEGMENT_SIZES_MB, LOGARITHMIC_GROWTH_SEGMENT_SIZES_MB,
         STEPS_SEGMENT_SIZES_MB)) {
-      SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater =
-          new SegmentSizeBasedFlushThresholdUpdater(REALTIME_TABLE_NAME, streamConfig.getTopicName());
+      SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater = new SegmentSizeBasedFlushThresholdUpdater();
 
       // Start consumption
       SegmentZKMetadata newSegmentZKMetadata = getNewSegmentZKMetadata(1);
@@ -235,8 +233,7 @@ public class FlushThresholdUpdaterTest {
   @Test
   public void testTimeThreshold() {
     StreamConfig streamConfig = mockDefaultAutotuneStreamConfig();
-    SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater =
-        new SegmentSizeBasedFlushThresholdUpdater(REALTIME_TABLE_NAME, streamConfig.getTopicName());
+    SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater = new SegmentSizeBasedFlushThresholdUpdater();
 
     // Start consumption
     SegmentZKMetadata newSegmentZKMetadata = getNewSegmentZKMetadata(0);
@@ -267,8 +264,7 @@ public class FlushThresholdUpdaterTest {
   @Test
   public void testMinThreshold() {
     StreamConfig streamConfig = mockDefaultAutotuneStreamConfig();
-    SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater =
-        new SegmentSizeBasedFlushThresholdUpdater(REALTIME_TABLE_NAME, streamConfig.getTopicName());
+    SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater = new SegmentSizeBasedFlushThresholdUpdater();
 
     // Start consumption
     SegmentZKMetadata newSegmentZKMetadata = getNewSegmentZKMetadata(0);
@@ -304,8 +300,7 @@ public class FlushThresholdUpdaterTest {
     int flushAutotuneInitialRows = StreamConfig.DEFAULT_FLUSH_AUTOTUNE_INITIAL_ROWS / 2;
     StreamConfig streamConfig =
         mockAutotuneStreamConfig(flushSegmentDesiredSizeBytes, flushThresholdTimeMillis, flushAutotuneInitialRows);
-    SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater =
-        new SegmentSizeBasedFlushThresholdUpdater(REALTIME_TABLE_NAME, streamConfig.getTopicName());
+    SegmentSizeBasedFlushThresholdUpdater flushThresholdUpdater = new SegmentSizeBasedFlushThresholdUpdater();
 
     // Start consumption
     SegmentZKMetadata newSegmentZKMetadata = getNewSegmentZKMetadata(0);


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


(pinot) 04/25: Fix partition function config not passed in realtime segment creation

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit df4a370141d18ce34492077b2e2823d9f2134e0c
Author: Xiang Fu <xi...@startree.ai>
AuthorDate: Sun Mar 22 02:34:37 2026 -0700

    Fix partition function config not passed in realtime segment creation
    
    The partition function config (functionConfig) was passed as null when
    creating partition functions for realtime segments in both
    RealtimeSegmentDataManager and StatelessRealtimeSegmentWriter. This
    meant custom partition function configurations (e.g., for bounded
    hash partitioning) were silently ignored during realtime ingestion.
    Pass columnPartitionConfig.getFunctionConfig() instead of null.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <no...@anthropic.com>
---
 .../pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java  | 4 +++-
 .../segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java | 3 ++-
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
index 0660cdfb9d8..8bf0a6c2f9b 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
@@ -1404,6 +1404,7 @@ public class RealtimeSegmentDataManager extends SegmentDataManager {
     final Logger _logger;
     final ServerSegmentCompletionProtocolHandler _protocolHandler;
     final String _reason;
+
     private ConsumptionStopIndicator(StreamPartitionMsgOffset offset, String segmentName, String instanceId,
         ServerSegmentCompletionProtocolHandler protocolHandler, String reason, Logger logger) {
       _offset = offset;
@@ -1988,7 +1989,8 @@ public class RealtimeSegmentDataManager extends SegmentDataManager {
 
         realtimeSegmentConfigBuilder.setPartitionColumn(partitionColumn);
         realtimeSegmentConfigBuilder.setPartitionFunction(
-            PartitionFunctionFactory.getPartitionFunction(partitionFunctionName, numPartitions, null));
+            PartitionFunctionFactory.getPartitionFunction(partitionFunctionName, numPartitions,
+                columnPartitionConfig.getFunctionConfig()));
         realtimeSegmentConfigBuilder.setPartitionId(_partitionGroupId);
       } else {
         _segmentLogger.warn("Cannot partition on multiple columns: {}", columnPartitionMap.keySet());
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
index cc0c9e92887..cbece4ddd5b 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
@@ -434,7 +434,8 @@ public class StatelessRealtimeSegmentWriter implements Closeable {
 
         realtimeSegmentConfigBuilder.setPartitionColumn(partitionColumn);
         realtimeSegmentConfigBuilder.setPartitionFunction(
-            PartitionFunctionFactory.getPartitionFunction(partitionFunctionName, numPartitions, null));
+            PartitionFunctionFactory.getPartitionFunction(partitionFunctionName, numPartitions,
+                columnPartitionConfig.getFunctionConfig()));
         realtimeSegmentConfigBuilder.setPartitionId(_partitionGroupId);
       } else {
         _logger.warn("Cannot partition on multiple columns: {}", columnPartitionMap.keySet());


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


(pinot) 25/25: [bugfix] Clear realtime inverted index bitmaps on close (#18204)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit f30d306374b087aba634b1c7aaeed7b4fe0aaf57
Author: Xiang Fu <xi...@apache.org>
AuthorDate: Wed Apr 15 03:06:50 2026 -0700

    [bugfix] Clear realtime inverted index bitmaps on close (#18204)
    
    * Clear realtime inverted index bitmaps on close
    
    * Simplify realtime inverted index close cleanup
    
    * Trim realtime inverted index storage on close
    
    * Clear mutable segment index container map on destroy
---
 .../indexsegment/mutable/MutableSegmentImpl.java   |  1 +
 .../impl/invertedindex/RealtimeInvertedIndex.java  | 10 +++++++--
 .../mutable/MutableSegmentImplTest.java            | 24 ++++++++++++++++++++++
 .../RealtimeInvertedIndexReaderTest.java           | 21 +++++++++++++++++++
 4 files changed, 54 insertions(+), 2 deletions(-)

diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
index 7645967cf4e..65817178176 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java
@@ -1319,6 +1319,7 @@ public class MutableSegmentImpl implements MutableSegment {
     for (IndexContainer indexContainer : _indexContainerMap.values()) {
       indexContainer.close();
     }
+    _indexContainerMap.clear();
 
     if (_multiColumnTextIndex != null) {
       try {
diff --git a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndex.java b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndex.java
index 7aa5f6b34d2..e658849571a 100644
--- a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndex.java
+++ b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndex.java
@@ -19,7 +19,6 @@
 package org.apache.pinot.segment.local.realtime.impl.invertedindex;
 
 import java.util.ArrayList;
-import java.util.List;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 import org.apache.pinot.segment.spi.index.mutable.MutableInvertedIndex;
 import org.apache.pinot.segment.spi.index.mutable.ThreadSafeMutableRoaringBitmap;
@@ -31,7 +30,7 @@ import org.roaringbitmap.buffer.MutableRoaringBitmap;
  * <p>This class is thread-safe for single writer multiple readers.
  */
 public class RealtimeInvertedIndex implements MutableInvertedIndex {
-  private final List<ThreadSafeMutableRoaringBitmap> _bitmaps = new ArrayList<>();
+  private final ArrayList<ThreadSafeMutableRoaringBitmap> _bitmaps = new ArrayList<>();
   private final ReentrantReadWriteLock.ReadLock _readLock;
   private final ReentrantReadWriteLock.WriteLock _writeLock;
 
@@ -82,5 +81,12 @@ public class RealtimeInvertedIndex implements MutableInvertedIndex {
 
   @Override
   public void close() {
+    try {
+      _writeLock.lock();
+      _bitmaps.clear();
+      _bitmaps.trimToSize();
+    } finally {
+      _writeLock.unlock();
+    }
   }
 }
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTest.java
index 43850ae3710..7c36c57c688 100644
--- a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTest.java
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplTest.java
@@ -20,7 +20,9 @@ package org.apache.pinot.segment.local.indexsegment.mutable;
 
 import java.io.File;
 import java.io.IOException;
+import java.lang.reflect.Field;
 import java.net.URL;
+import java.util.Map;
 import org.apache.commons.io.FileUtils;
 import org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader;
 import org.apache.pinot.segment.local.segment.creator.SegmentTestUtils;
@@ -203,6 +205,28 @@ public class MutableSegmentImplTest {
     }
   }
 
+  @Test
+  public void testDestroyClearsIndexContainerMap()
+      throws ReflectiveOperationException {
+    MutableSegmentImpl freshSegment = MutableSegmentImplTestUtils.createMutableSegmentImpl(_schema);
+    boolean destroyed = false;
+    try {
+      Field indexContainerMapField = MutableSegmentImpl.class.getDeclaredField("_indexContainerMap");
+      indexContainerMapField.setAccessible(true);
+      Map<?, ?> indexContainerMap = (Map<?, ?>) indexContainerMapField.get(freshSegment);
+      Assert.assertFalse(indexContainerMap.isEmpty());
+
+      freshSegment.destroy();
+      destroyed = true;
+
+      Assert.assertTrue(indexContainerMap.isEmpty());
+    } finally {
+      if (!destroyed) {
+        freshSegment.destroy();
+      }
+    }
+  }
+
   @AfterClass
   public void tearDown() {
     _mutableSegmentImpl.destroy();
diff --git a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndexReaderTest.java b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndexReaderTest.java
index 94528c90eaf..780057a6197 100644
--- a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndexReaderTest.java
+++ b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeInvertedIndexReaderTest.java
@@ -18,9 +18,12 @@
  */
 package org.apache.pinot.segment.local.realtime.impl.invertedindex;
 
+import java.lang.reflect.Field;
+import java.util.List;
 import org.roaringbitmap.buffer.MutableRoaringBitmap;
 import org.testng.annotations.Test;
 
+import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertTrue;
@@ -103,4 +106,22 @@ public class RealtimeInvertedIndexReaderTest {
     assertFalse(docIds.contains(1));
     assertTrue(docIds.contains(2));
   }
+
+  @Test
+  public void testCloseClearsBitmaps()
+      throws ReflectiveOperationException {
+    RealtimeInvertedIndex realtimeInvertedIndex = new RealtimeInvertedIndex();
+    realtimeInvertedIndex.add(0, 0);
+    realtimeInvertedIndex.add(1, 1);
+
+    realtimeInvertedIndex.close();
+
+    assertTrue(realtimeInvertedIndex.getDocIds(0).isEmpty());
+    assertTrue(realtimeInvertedIndex.getDocIds(1).isEmpty());
+
+    Field bitmapsField = RealtimeInvertedIndex.class.getDeclaredField("_bitmaps");
+    bitmapsField.setAccessible(true);
+    List<?> bitmaps = (List<?>) bitmapsField.get(realtimeInvertedIndex);
+    assertEquals(bitmaps.size(), 0);
+  }
 }


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


(pinot) 17/25: allow enforceConsumptionInOrder to be rewritten at runtime (#18045)

Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch release/1.5.0-STP-2.134.x
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit a02bca26ddbb228d69c781920356ae55d1a3ce6d
Author: Kartik Khare <kh...@gmail.com>
AuthorDate: Wed Apr 1 09:48:54 2026 +0530

    allow enforceConsumptionInOrder to be rewritten at runtime (#18045)
    
    Co-authored-by: Kartik Khare <kh...@kartiks-macbook-pro-3.wyvern-sun.ts.net>
    (cherry picked from commit e23528c04a71598812d328d6cd3fd10c6f8435d9)
---
 .../data/manager/realtime/RealtimeTableDataManager.java     |  7 +++++--
 .../data/manager/realtime/RealtimeTableDataManagerTest.java | 13 +++++++++++++
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
index 3b606ebb949..d3849e49e1b 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManager.java
@@ -832,8 +832,11 @@ public class RealtimeTableDataManager extends BaseTableDataManager {
         k -> new ConsumerCoordinator(_enforceConsumptionInOrder, this));
   }
 
-  @VisibleForTesting
-  void setEnforceConsumptionInOrder(boolean enforceConsumptionInOrder) {
+  public boolean isEnforceConsumptionInOrderEnabled() {
+    return _enforceConsumptionInOrder;
+  }
+
+  public void setEnforceConsumptionInOrder(boolean enforceConsumptionInOrder) {
     _enforceConsumptionInOrder = enforceConsumptionInOrder;
   }
 
diff --git a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
index 1c78091d16f..f2e3955d147 100644
--- a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
+++ b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeTableDataManagerTest.java
@@ -126,4 +126,17 @@ public class RealtimeTableDataManagerTest {
             .equals(streamMetadataProvider1)), 5, 2000, "streamMetadataProvider returned from cache must be new.");
     Assert.assertTrue(fakeRealtimeTableDataManager._cacheEntryRemovalNotified);
   }
+
+  @Test
+  public void testEnforceConsumptionInOrderRuntimeOverride() {
+    RealtimeTableDataManager realtimeTableDataManager = new RealtimeTableDataManager(null);
+
+    Assert.assertFalse(realtimeTableDataManager.isEnforceConsumptionInOrderEnabled());
+
+    realtimeTableDataManager.setEnforceConsumptionInOrder(true);
+    Assert.assertTrue(realtimeTableDataManager.isEnforceConsumptionInOrderEnabled());
+
+    realtimeTableDataManager.setEnforceConsumptionInOrder(false);
+    Assert.assertFalse(realtimeTableDataManager.isEnforceConsumptionInOrderEnabled());
+  }
 }


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