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

Jackie-Jiang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 76d6f280374 fix(segment): reconcile stale FIXMEs around upsert 
validDocIds and aggr… (#20209)
76d6f280374 is described below

commit 76d6f2803746c38d2adfe38c3a599749198ed0bc
Author: noy-solvin <[email protected]>
AuthorDate: Tue Nov 24 02:10:38 2026 +0200

    fix(segment): reconcile stale FIXMEs around upsert validDocIds and aggr… 
(#20209)
---
 .../indexsegment/mutable/MutableSegmentImpl.java   |  23 ++---
 .../MutableSegmentImplAggregateMetricsTest.java    |  35 +++++--
 .../mutable/MutableSegmentImplUpsertTest.java      | 114 +++++++++++++++++++++
 3 files changed, 150 insertions(+), 22 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 8341d1d80b0..8f42d095e94 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
@@ -188,14 +188,10 @@ public class MutableSegmentImpl implements MutableSegment 
{
   private final String _upsertOutOfOrderRecordColumn;
   private final UpsertConfig.ConsistencyMode _upsertConsistencyMode;
 
-  // The valid doc ids are maintained locally instead of in the upsert 
metadata manager because:
-  // 1. There is only one consuming segment per partition, the committed 
segments do not need to modify the valid doc
-  //    ids for the consuming segment.
-  // 2. During the segment commitment, when loading the immutable version of 
this segment, in order to keep the result
-  //    correct, the valid doc ids should not be changed, only the record 
location should be changed.
-  // FIXME: There is a corner case for this approach which could cause 
inconsistency. When there is segment load during
-  //        consumption with newer timestamp (late event in consuming 
segment), the record location will be updated, but
-  //        the valid doc ids won't be updated.
+  // Maintained by the upsert metadata manager (via getValidDocIds() / 
getQueryableDocIds()) as records are indexed and
+  // as segments are loaded or replaced in the partition. During segment 
commitment (ConsistencyMode.NONE),
+  // replaceSegment() works on a snapshot copy of _validDocIds so the 
consuming segment's bitmap stays intact for
+  // concurrent queries until the immutable replacement is swapped in.
   private final ThreadSafeMutableRoaringBitmap _validDocIds;
   private final ThreadSafeMutableRoaringBitmap _queryableDocIds;
   private boolean _indexCapacityThresholdBreached;
@@ -298,7 +294,7 @@ public class MutableSegmentImpl implements MutableSegment {
     _logger =
         LoggerFactory.getLogger(MutableSegmentImpl.class.getName() + "_" + 
_segmentName + "_" + config.getStreamName());
 
-    // Metric aggregation can be enabled only if config is specified, and all 
dimensions have dictionary,
+    // Metric aggregation can be enabled only if config is specified, all 
dimensions and metrics are single-valued,
     // and no metrics have dictionary. If not enabled, the map returned is 
null.
     _recordIdMap = enableMetricsAggregationIfPossible(config);
 
@@ -1601,12 +1597,11 @@ public class MutableSegmentImpl implements 
MutableSegment {
     }
 
     int i = 0;
-    // Dimension and time columns form the aggregation key. They are always 
dictionary encoded in the consuming
-    // segment (isNoDictionaryColumn forces a dictionary on them when 
aggregation is enabled), so the _dictId read
-    // below is always valid. Keep this set of columns in sync with the field 
types forced there.
+    // Dimension and time columns form the aggregation key. They are always 
single-valued (enforced in
+    // enableMetricsAggregationIfPossible; see 
https://github.com/apache/pinot/issues/3867) and dictionary encoded in
+    // the consuming segment (isNoDictionaryColumn forces a dictionary on them 
when aggregation is enabled), so the
+    // _dictId read below is always valid. Keep this set of columns in sync 
with the field types forced there.
     int[] dictIds = new int[_numKeyColumns]; // dimensions + date time columns 
+ time column.
-
-    // FIXME: this for loop breaks for multi value dimensions. 
https://github.com/apache/pinot/issues/3867
     for (FieldSpec fieldSpec : _physicalDimensionFieldSpecs) {
       dictIds[i++] = _indexContainerMap.get(fieldSpec.getName())._dictId;
     }
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplAggregateMetricsTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplAggregateMetricsTest.java
index 6282a960c75..0ee8f4525a5 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplAggregateMetricsTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplAggregateMetricsTest.java
@@ -21,11 +21,13 @@ package org.apache.pinot.segment.local.indexsegment.mutable;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Random;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.pinot.spi.config.table.ingestion.AggregationConfig;
 import org.apache.pinot.spi.data.DimensionFieldSpec;
 import org.apache.pinot.spi.data.FieldSpec;
 import org.apache.pinot.spi.data.MetricFieldSpec;
@@ -37,6 +39,8 @@ import org.testng.Assert;
 import org.testng.annotations.Test;
 
 import static org.mockito.Mockito.mock;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNull;
 
 
 public class MutableSegmentImplAggregateMetricsTest {
@@ -125,9 +129,9 @@ public class MutableSegmentImplAggregateMetricsTest {
   @Test
   public void testMultiValueDimensionDisablesAggregation()
       throws Exception {
-    // A multi-value dimension cannot be used as an aggregation key (issue 
#3867), so aggregation stays disabled and no
-    // rollup happens even though aggregateMetrics is set. This guards against 
over-broadening the aggregation-enabling
-    // and dictionary-forcing logic to columns that cannot support it.
+    // A multi-value dimension cannot be used as an aggregation key (issue 
#3867), so aggregation stays disabled and
+    // no rollup happens whether configured via aggregateMetrics or 
ingestionAggregationConfigs. This guards against
+    // over-broadening the aggregation-enabling and dictionary-forcing logic 
to columns that cannot support it.
     Schema schema = new Schema.SchemaBuilder().setSchemaName("testSchema")
         .addSingleValueDimension(DIMENSION_1, FieldSpec.DataType.INT)
         .addMultiValueDimension(DIMENSION_2, FieldSpec.DataType.STRING)
@@ -136,10 +140,24 @@ public class MutableSegmentImplAggregateMetricsTest {
         .addDateTime(TIME_COLUMN1, FieldSpec.DataType.INT, "1:DAYS:EPOCH", 
"1:DAYS")
         .addDateTime(TIME_COLUMN2, FieldSpec.DataType.INT, "1:HOURS:EPOCH", 
"1:HOURS")
         .build();
+    Set<String> noDictionaryColumns = Set.of(DIMENSION_1, METRIC, METRIC_2);
+
     MutableSegmentImpl mutableSegmentImpl =
-        MutableSegmentImplTestUtils.createMutableSegmentImpl(schema, 
Set.of(METRIC, METRIC_2), Set.of(), Set.of(),
-            true);
+        MutableSegmentImplTestUtils.createMutableSegmentImpl(schema, 
noDictionaryColumns, Set.of(), Set.of(), true);
+    assertMultiValueDimensionDisablesAggregation(mutableSegmentImpl);
+    mutableSegmentImpl.destroy();
+
+    List<AggregationConfig> aggregationConfigs =
+        List.of(new AggregationConfig(METRIC, "SUM(metric)"), new 
AggregationConfig(METRIC_2, "SUM(metric2)"));
+    mutableSegmentImpl =
+        MutableSegmentImplTestUtils.createMutableSegmentImpl(schema, 
noDictionaryColumns, Set.of(), Set.of(),
+            aggregationConfigs);
+    assertMultiValueDimensionDisablesAggregation(mutableSegmentImpl);
+    mutableSegmentImpl.destroy();
+  }
 
+  private void assertMultiValueDimensionDisablesAggregation(MutableSegmentImpl 
mutableSegmentImpl)
+      throws Exception {
     Random random = new Random();
     for (int i = 0; i < NUM_ROWS; i++) {
       GenericRow row = new GenericRow();
@@ -152,9 +170,10 @@ public class MutableSegmentImplAggregateMetricsTest {
       mutableSegmentImpl.index(row, METADATA);
     }
 
-    // Aggregation is disabled, so every row is stored as its own document (no 
rollup).
-    Assert.assertEquals(mutableSegmentImpl.getNumDocsIndexed(), NUM_ROWS);
-    mutableSegmentImpl.destroy();
+    // Aggregation is disabled, so every row is stored as its own document (no 
rollup) and no-dictionary key columns
+    // stay no-dictionary.
+    assertEquals(mutableSegmentImpl.getNumDocsIndexed(), NUM_ROWS);
+    
assertNull(mutableSegmentImpl.getDataSourceNullable(DIMENSION_1).getDictionary());
   }
 
   private void testAggregateMetrics(MutableSegmentImpl mutableSegmentImpl)
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplUpsertTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplUpsertTest.java
index 2140e7e8d27..467b060f4a0 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplUpsertTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImplUpsertTest.java
@@ -21,22 +21,32 @@ package org.apache.pinot.segment.local.indexsegment.mutable;
 import java.io.File;
 import java.io.IOException;
 import java.net.URL;
+import java.nio.file.Files;
 import java.util.List;
+import org.apache.commons.io.FileUtils;
 import org.apache.pinot.segment.local.data.manager.TableDataManager;
+import 
org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentImpl;
+import 
org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader;
 import org.apache.pinot.segment.local.segment.creator.TransformPipeline;
+import 
org.apache.pinot.segment.local.segment.creator.impl.SegmentIndexCreationDriverImpl;
+import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader;
 import org.apache.pinot.segment.local.upsert.PartitionUpsertMetadataManager;
 import org.apache.pinot.segment.local.upsert.TableUpsertMetadataManager;
 import org.apache.pinot.segment.local.upsert.TableUpsertMetadataManagerFactory;
+import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig;
 import org.apache.pinot.spi.config.table.HashFunction;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.config.table.TableType;
 import org.apache.pinot.spi.config.table.UpsertConfig;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
 import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.data.readers.FileFormat;
 import org.apache.pinot.spi.data.readers.GenericRow;
 import org.apache.pinot.spi.data.readers.RecordReader;
 import org.apache.pinot.spi.data.readers.RecordReaderFactory;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.utils.ReadMode;
 import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
 import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
 import org.testng.annotations.Test;
@@ -55,6 +65,7 @@ public class MutableSegmentImplUpsertTest {
   private static final String TIME_COLUMN = "secondsSinceEpoch";
   private static final String OTHER_COMPARISON_COLUMN = 
"otherComparisonColumn";
   private static final String PRIMARY_KEY_COLUMN = "event_id";
+  private static final String DELETE_RECORD_COLUMN = "is_deleted";
 
   private MutableSegmentImpl _mutableSegmentImpl;
   private PartitionUpsertMetadataManager _partitionUpsertMetadataManager;
@@ -183,6 +194,109 @@ public class MutableSegmentImplUpsertTest {
     return row;
   }
 
+  /// Verifies that loading an immutable segment with a newer comparison value 
while a mutable segment is actively
+  /// consuming invalidates the late event's docId in the consuming segment's 
`_validDocIds` and `_queryableDocIds`,
+  /// and that subsequent consumption with an even newer comparison value 
invalidates the immutable segment's docId.
+  @Test
+  public void testSegmentLoadDuringConsumptionUpdatesValidDocIds()
+      throws Exception {
+    UpsertConfig upsertConfig = createFullUpsertConfig(HashFunction.NONE);
+    upsertConfig.setDeleteRecordColumn(DELETE_RECORD_COLUMN);
+    TableConfig tableConfig = new 
TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME)
+        .setTimeColumnName(TIME_COLUMN)
+        .setUpsertConfig(upsertConfig)
+        .setNullHandlingEnabled(true)
+        .build();
+    URL schemaResourceUrl = 
getClass().getClassLoader().getResource(SCHEMA_FILE_PATH);
+    assertNotNull(schemaResourceUrl);
+    Schema schema = Schema.fromFile(new File(schemaResourceUrl.getFile()));
+    schema.addField(new DimensionFieldSpec(DELETE_RECORD_COLUMN, 
DataType.BOOLEAN, true));
+
+    TableUpsertMetadataManager tableUpsertMetadataManager =
+        TableUpsertMetadataManagerFactory.create(new PinotConfiguration(), 
tableConfig, schema,
+            mock(TableDataManager.class), null);
+    PartitionUpsertMetadataManager partitionUpsertMetadataManager =
+        tableUpsertMetadataManager.getOrCreatePartitionManager(0);
+    MutableSegmentImpl mutableSegment =
+        MutableSegmentImplTestUtils.createMutableSegmentImpl(schema, true, 
TIME_COLUMN,
+            partitionUpsertMetadataManager, null);
+    File tempDir = 
Files.createTempDirectory("MutableSegmentImplUpsertTest").toFile();
+    ImmutableSegmentImpl immutableSegment = null;
+    try {
+      // Consuming segment indexes late events for "aa" (docId 0, 
ts=1567205394) and "cc" (docId 2, ts=1567205394),
+      // and a newer event for "bb" (docId 1, ts=1567205398).
+      mutableSegment.index(createRowWithDelete("aa", 1L, 1567205394L, false), 
null);
+      mutableSegment.index(createRowWithDelete("bb", 1L, 1567205398L, false), 
null);
+      mutableSegment.index(createRowWithDelete("cc", 1L, 1567205394L, false), 
null);
+      ImmutableRoaringBitmap mutableValidDocIds = 
mutableSegment.getValidDocIds().getMutableRoaringBitmap();
+      ImmutableRoaringBitmap mutableQueryableDocIds = 
mutableSegment.getQueryableDocIds().getMutableRoaringBitmap();
+      assertEquals(mutableValidDocIds.toArray(), new int[]{0, 1, 2});
+      assertEquals(mutableQueryableDocIds.toArray(), new int[]{0, 1, 2});
+
+      // Build and load an immutable segment where "aa" has a newer timestamp 
(1567205396), "bb" has an older
+      // timestamp (1567205395), and "cc" is a newer delete record 
(1567205396, isDeleted=true).
+      List<GenericRow> immutableRows = List.of(
+          createRowWithDelete("aa", 1L, 1567205396L, false),
+          createRowWithDelete("bb", 1L, 1567205395L, false),
+          createRowWithDelete("cc", 1L, 1567205396L, true));
+      String segmentName = "testTable__0__1__20260101T0000Z";
+      SegmentGeneratorConfig generatorConfig = new 
SegmentGeneratorConfig(tableConfig, schema);
+      generatorConfig.setOutDir(tempDir.getAbsolutePath());
+      generatorConfig.setSegmentName(segmentName);
+      generatorConfig.setTableName(RAW_TABLE_NAME);
+      SegmentIndexCreationDriverImpl driver = new 
SegmentIndexCreationDriverImpl();
+      driver.init(generatorConfig, new GenericRowRecordReader(immutableRows));
+      driver.build();
+      immutableSegment =
+          (ImmutableSegmentImpl) ImmutableSegmentLoader.load(new File(tempDir, 
segmentName), ReadMode.mmap);
+
+      partitionUpsertMetadataManager.addSegment(immutableSegment);
+
+      // "aa" (doc 0) and "cc" (doc 2) in the consuming segment must be 
invalidated by the newly loaded immutable
+      // segment, while "bb" (doc 1) in the consuming segment remains valid.
+      mutableValidDocIds = 
mutableSegment.getValidDocIds().getMutableRoaringBitmap();
+      mutableQueryableDocIds = 
mutableSegment.getQueryableDocIds().getMutableRoaringBitmap();
+      assertEquals(mutableValidDocIds.toArray(), new int[]{1});
+      assertEquals(mutableQueryableDocIds.toArray(), new int[]{1});
+
+      ImmutableRoaringBitmap immutableValidDocIds = 
immutableSegment.getValidDocIds().getMutableRoaringBitmap();
+      ImmutableRoaringBitmap immutableQueryableDocIds = 
immutableSegment.getQueryableDocIds().getMutableRoaringBitmap();
+      assertEquals(immutableValidDocIds.toArray(), new int[]{0, 2});
+      assertEquals(immutableQueryableDocIds.toArray(), new int[]{0});
+
+      // Subsequent out-of-order event in the consuming segment for "aa" 
(docId 3, ts=1567205395) stays invalid.
+      mutableSegment.index(createRowWithDelete("aa", 1L, 1567205395L, false), 
null);
+      
assertEquals(mutableSegment.getValidDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{1});
+      
assertEquals(mutableSegment.getQueryableDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{1});
+      
assertEquals(immutableSegment.getValidDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{0, 2});
+      
assertEquals(immutableSegment.getQueryableDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{0});
+
+      // Subsequent consumption of a newer event for "aa" (docId 4, 
ts=1567205399) invalidates doc 0 in the immutable
+      // segment and makes doc 4 valid and queryable in the consuming segment.
+      mutableSegment.index(createRowWithDelete("aa", 1L, 1567205399L, false), 
null);
+      
assertEquals(mutableSegment.getValidDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{1, 4});
+      
assertEquals(mutableSegment.getQueryableDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{1, 4});
+      
assertEquals(immutableSegment.getValidDocIds().getMutableRoaringBitmap().toArray(),
 new int[]{2});
+      
assertTrue(immutableSegment.getQueryableDocIds().getMutableRoaringBitmap().isEmpty());
+    } finally {
+      mutableSegment.destroy();
+      if (immutableSegment != null) {
+        partitionUpsertMetadataManager.removeSegment(immutableSegment);
+        immutableSegment.destroy();
+      }
+      partitionUpsertMetadataManager.stop();
+      partitionUpsertMetadataManager.close();
+      FileUtils.deleteQuietly(tempDir);
+    }
+  }
+
+  private static GenericRow createRowWithDelete(String eventId, long 
otherComparisonValue, long timeValue,
+      boolean isDeleted) {
+    GenericRow row = createRow(eventId, otherComparisonValue, timeValue);
+    row.putValue(DELETE_RECORD_COLUMN, isDeleted ? 1 : 0);
+    return row;
+  }
+
   @Test
   public void testMultipleComparisonColumns()
       throws Exception {


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

Reply via email to