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

xiangfu0 pushed a commit to branch claude/pinot-realtime-multivalue-count-eeff8l
in repository https://gitbox.apache.org/repos/asf/pinot.git

commit c58e57b40789a1507b2718476299f00e28238480
Author: Claude <[email protected]>
AuthorDate: Fri Dec 4 20:00:28 2026 +0000

    Do not trust a stale total number of entries when reloading a raw 
multi-value column
    
    Realtime segments sealed before #20448 record the number of docs as the 
total number of entries of a raw
    multi-value column. Two reload paths trusted that value:
    - Adding a range index sized the creator buffers from it and failed with 
IndexOutOfBoundsException. The handler
      now counts the values when the stored count equals the number of docs, 
and stores the corrected count.
    - Enabling a dictionary wrote the new forward index with the real count but 
left the stale one in the metadata,
      so the reader located values wrongly. The handler now writes the scanned 
count.
---
 .../segment/index/loader/ForwardIndexHandler.java  |   7 +
 .../loader/invertedindex/RangeIndexHandler.java    |  53 ++++++
 .../RawMultiValueStaleTotalEntriesReloadTest.java  | 185 +++++++++++++++++++++
 3 files changed, 245 insertions(+)

diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/ForwardIndexHandler.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/ForwardIndexHandler.java
index 41cc548a58d..ff6f8badb0d 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/ForwardIndexHandler.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/ForwardIndexHandler.java
@@ -1119,6 +1119,13 @@ public class ForwardIndexHandler extends 
BaseIndexHandler {
     metadataProperties.put(getKeyFor(column, CARDINALITY), 
String.valueOf(cardinality));
     metadataProperties.put(getKeyFor(column, BITS_PER_ELEMENT),
         String.valueOf(PinotDataBitSet.getNumBitsPerValue(cardinality - 1)));
+    if (!fieldSpec.isSingleValueField()) {
+      // The new forward index is sized by the number of values just scanned, 
and its reader locates values from this
+      // metadata. Realtime segments sealed before #20448 recorded the number 
of docs here for a raw multi-value
+      // column, so write the scanned count instead of trusting the stored one.
+      metadataProperties.put(getKeyFor(column, TOTAL_NUMBER_OF_ENTRIES),
+          String.valueOf(statsCollector.getTotalNumberOfEntries()));
+    }
     CompressionStatsMetadata compressionMetadata = 
CompressionStatsMetadata.unavailable();
     if (_tableConfig.getIndexingConfig().isCompressionStatsEnabled()) {
       DataType storedType = fieldSpec.getDataType().getStoredType();
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/invertedindex/RangeIndexHandler.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/invertedindex/RangeIndexHandler.java
index a80321d86c8..d6ee5193059 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/invertedindex/RangeIndexHandler.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/loader/invertedindex/RangeIndexHandler.java
@@ -32,6 +32,7 @@ import 
org.apache.pinot.segment.local.segment.index.loader.IndexLoadingConfig;
 import org.apache.pinot.segment.local.segment.index.loader.LoaderUtils;
 import org.apache.pinot.segment.spi.ColumnMetadata;
 import org.apache.pinot.segment.spi.V1Constants;
+import org.apache.pinot.segment.spi.V1Constants.MetadataKeys.Column;
 import org.apache.pinot.segment.spi.creator.IndexCreationContext;
 import org.apache.pinot.segment.spi.creator.SegmentVersion;
 import org.apache.pinot.segment.spi.index.FieldIndexConfigs;
@@ -45,6 +46,7 @@ import 
org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
 import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext;
 import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
 import org.apache.pinot.segment.spi.store.SegmentDirectory;
+import org.apache.pinot.segment.spi.utils.SegmentMetadataUtils;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.data.FieldSpec.DataType;
 import org.apache.pinot.spi.data.Schema;
@@ -346,9 +348,60 @@ public class RangeIndexHandler extends BaseIndexHandler {
         builder.withMinValue(minMax[0]).withMaxValue(minMax[1]);
       }
     }
+    if (!columnMetadata.isSingleValue() && 
columnMetadata.getTotalNumberOfEntries() == numDocs) {
+      // The creator sizes its buffers from the number of values. Realtime 
segments sealed before #20448 recorded the
+      // number of docs for a raw multi-value column, so a stored count equal 
to the number of docs cannot be
+      // trusted. Count the values with one extra scan and store the result, 
so that later reloads and the readers
+      // of the column metadata get the right count as well.
+      int numValues = countRawValues(forwardIndexReader, readerContext, 
columnMetadata, numDocs);
+      if (numValues != numDocs) {
+        LOGGER.info("Correcting total number of entries from {} to {} for 
segment: {}, column: {}", numDocs,
+            numValues, _segmentDirectory.getSegmentMetadata().getName(), 
columnMetadata.getColumnName());
+        builder.withTotalNumberOfEntries(numValues);
+        SegmentMetadataUtils.updateMetadataProperties(_segmentDirectory,
+            Map.of(Column.getKeyFor(columnMetadata.getColumnName(), 
Column.TOTAL_NUMBER_OF_ENTRIES),
+                String.valueOf(numValues)));
+      }
+    }
     return StandardIndexes.range().createIndexCreator(builder.build(), config);
   }
 
+  /// Counts the values of a raw multi-value column by scanning its forward 
index.
+  private static int countRawValues(ForwardIndexReader forwardIndexReader, 
ForwardIndexReaderContext readerContext,
+      ColumnMetadata columnMetadata, int numDocs) {
+    int maxNumValuesPerMVEntry = columnMetadata.getMaxNumberOfMultiValues();
+    int numValues = 0;
+    switch (columnMetadata.getDataType().getStoredType()) {
+      case INT:
+        int[] intValues = new int[maxNumValuesPerMVEntry];
+        for (int i = 0; i < numDocs; i++) {
+          numValues += forwardIndexReader.getIntMV(i, intValues, 
readerContext);
+        }
+        break;
+      case LONG:
+        long[] longValues = new long[maxNumValuesPerMVEntry];
+        for (int i = 0; i < numDocs; i++) {
+          numValues += forwardIndexReader.getLongMV(i, longValues, 
readerContext);
+        }
+        break;
+      case FLOAT:
+        float[] floatValues = new float[maxNumValuesPerMVEntry];
+        for (int i = 0; i < numDocs; i++) {
+          numValues += forwardIndexReader.getFloatMV(i, floatValues, 
readerContext);
+        }
+        break;
+      case DOUBLE:
+        double[] doubleValues = new double[maxNumValuesPerMVEntry];
+        for (int i = 0; i < numDocs; i++) {
+          numValues += forwardIndexReader.getDoubleMV(i, doubleValues, 
readerContext);
+        }
+        break;
+      default:
+        throw new IllegalStateException("Unsupported data type: " + 
columnMetadata.getDataType());
+    }
+    return numValues;
+  }
+
   /// Computes {@code [min, max]} for a single-value INT/LONG no-dictionary 
column by scanning the forward index.
   /// Returns {@code null} for stored types whose BitSliced range index does 
not read min/max (FLOAT/DOUBLE use the
   /// full floating-point ordinal domain) or that do not support it, and for 
empty columns.
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/loader/RawMultiValueStaleTotalEntriesReloadTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/loader/RawMultiValueStaleTotalEntriesReloadTest.java
new file mode 100644
index 00000000000..df32c017c2a
--- /dev/null
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/loader/RawMultiValueStaleTotalEntriesReloadTest.java
@@ -0,0 +1,185 @@
+/**
+ * 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.segment.index.loader;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+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.impl.SegmentIndexCreationDriverImpl;
+import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader;
+import org.apache.pinot.segment.local.segment.store.SegmentLocalFSDirectory;
+import org.apache.pinot.segment.spi.ColumnMetadata;
+import org.apache.pinot.segment.spi.ImmutableSegment;
+import org.apache.pinot.segment.spi.V1Constants.MetadataKeys.Column;
+import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig;
+import org.apache.pinot.segment.spi.datasource.DataSource;
+import org.apache.pinot.segment.spi.index.metadata.SegmentMetadataImpl;
+import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
+import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext;
+import org.apache.pinot.segment.spi.index.reader.RangeIndexReader;
+import org.apache.pinot.segment.spi.store.SegmentDirectory;
+import org.apache.pinot.segment.spi.utils.SegmentMetadataUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.data.readers.GenericRow;
+import org.apache.pinot.spi.utils.ReadMode;
+import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
+import org.testng.annotations.AfterClass;
+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;
+
+
+/// Tests reloading a segment whose raw multi-value column records the number 
of docs as its total number of
+/// entries. Realtime segments sealed before the count was fixed carry that 
value, and a reload must not size a new
+/// index from it or leave it behind for the reader of a rewritten forward 
index.
+public class RawMultiValueStaleTotalEntriesReloadTest {
+  private static final File TEMP_DIR =
+      new File(FileUtils.getTempDirectory(), 
RawMultiValueStaleTotalEntriesReloadTest.class.getSimpleName());
+  private static final String MV_COLUMN = "mvIntCol";
+  private static final int[][] VALUES = {{3, 1}, {7}, {2, 9, 4}, {5, 5}, {8, 
6, 10, 11}};
+  private static final int NUM_VALUES = Arrays.stream(VALUES).mapToInt(values 
-> values.length).sum();
+  private static final Schema SCHEMA = new 
Schema.SchemaBuilder().setSchemaName("testSchema")
+      .addMultiValueDimension(MV_COLUMN, DataType.INT).build();
+
+  @Test
+  public void testAddRangeIndex()
+      throws Exception {
+    File indexDir = buildSegmentWithStaleTotalEntries("addRangeIndex");
+    TableConfig tableConfig =
+        
tableConfigBuilder().setNoDictionaryColumns(List.of(MV_COLUMN)).setRangeIndexColumns(List.of(MV_COLUMN))
+            .build();
+
+    ImmutableSegment segment = ImmutableSegmentLoader.load(indexDir, new 
IndexLoadingConfig(tableConfig, SCHEMA));
+    try {
+      DataSource dataSource = segment.getDataSource(MV_COLUMN);
+      assertEquals(dataSource.getDataSourceMetadata().getNumValues(), 
NUM_VALUES);
+      @SuppressWarnings("unchecked")
+      RangeIndexReader<ImmutableRoaringBitmap> rangeIndex =
+          (RangeIndexReader<ImmutableRoaringBitmap>) 
dataSource.getRangeIndex();
+      assertNotNull(rangeIndex);
+      // The values of the last doc are added last, so an index sized by the 
number of docs cannot hold them
+      for (int docId = 0; docId < VALUES.length; docId++) {
+        for (int value : VALUES[docId]) {
+          assertTrue(rangeCandidates(rangeIndex, value).contains(docId), 
"Missing doc: " + docId + " for: " + value);
+        }
+      }
+    } finally {
+      segment.destroy();
+    }
+    assertEquals(new 
SegmentMetadataImpl(indexDir).getColumnMetadataFor(MV_COLUMN).getTotalNumberOfEntries(),
+        NUM_VALUES);
+  }
+
+  @Test
+  public void testEnableDictionary()
+      throws Exception {
+    File indexDir = buildSegmentWithStaleTotalEntries("enableDictionary");
+    TableConfig tableConfig = tableConfigBuilder().build();
+
+    ImmutableSegment segment = ImmutableSegmentLoader.load(indexDir, new 
IndexLoadingConfig(tableConfig, SCHEMA));
+    try {
+      DataSource dataSource = segment.getDataSource(MV_COLUMN);
+      assertNotNull(dataSource.getDictionary());
+      assertEquals(dataSource.getDataSourceMetadata().getNumValues(), 
NUM_VALUES);
+      ForwardIndexReader forwardIndex = dataSource.getForwardIndex();
+      assertNotNull(forwardIndex);
+      assertTrue(forwardIndex.isDictionaryEncoded());
+      try (ForwardIndexReaderContext context = forwardIndex.createContext()) {
+        int[] dictIds = new 
int[dataSource.getDataSourceMetadata().getMaxNumValuesPerMVEntry()];
+        for (int docId = 0; docId < VALUES.length; docId++) {
+          int numValues = forwardIndex.getDictIdMV(docId, dictIds, context);
+          int[] values = new int[numValues];
+          dataSource.getDictionary().readIntValues(dictIds, numValues, values);
+          assertEquals(values, VALUES[docId], "Wrong values for doc: " + 
docId);
+        }
+      }
+    } finally {
+      segment.destroy();
+    }
+    assertEquals(new 
SegmentMetadataImpl(indexDir).getColumnMetadataFor(MV_COLUMN).getTotalNumberOfEntries(),
+        NUM_VALUES);
+  }
+
+  private static TableConfigBuilder tableConfigBuilder() {
+    return new TableConfigBuilder(TableType.OFFLINE).setTableName("testTable");
+  }
+
+  /// Builds a segment with a raw multi-value column, then overwrites its 
total number of entries with the number of
+  /// docs, the value realtime segments used to record.
+  private static File buildSegmentWithStaleTotalEntries(String segmentName)
+      throws Exception {
+    TableConfig tableConfig = 
tableConfigBuilder().setNoDictionaryColumns(List.of(MV_COLUMN)).build();
+    SegmentGeneratorConfig config = new SegmentGeneratorConfig(tableConfig, 
SCHEMA);
+    config.setOutDir(TEMP_DIR.getAbsolutePath());
+    config.setSegmentName(segmentName);
+
+    List<GenericRow> rows = new ArrayList<>();
+    for (int[] docValues : VALUES) {
+      GenericRow row = new GenericRow();
+      row.putValue(MV_COLUMN, Arrays.stream(docValues).boxed().toArray());
+      rows.add(row);
+    }
+    SegmentIndexCreationDriverImpl driver = new 
SegmentIndexCreationDriverImpl();
+    driver.init(config, new GenericRowRecordReader(rows));
+    driver.build();
+
+    File indexDir = new File(TEMP_DIR, segmentName);
+    SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(indexDir);
+    ColumnMetadata columnMetadata = 
segmentMetadata.getColumnMetadataFor(MV_COLUMN);
+    assertFalse(columnMetadata.hasDictionary());
+    assertEquals(columnMetadata.getTotalNumberOfEntries(), NUM_VALUES);
+    try (SegmentDirectory segmentDirectory = new 
SegmentLocalFSDirectory(indexDir, segmentMetadata, ReadMode.mmap)) {
+      SegmentMetadataUtils.updateMetadataProperties(segmentDirectory,
+          Map.of(Column.getKeyFor(MV_COLUMN, Column.TOTAL_NUMBER_OF_ENTRIES), 
String.valueOf(VALUES.length)));
+    }
+    assertEquals(new 
SegmentMetadataImpl(indexDir).getColumnMetadataFor(MV_COLUMN).getTotalNumberOfEntries(),
+        VALUES.length);
+    return indexDir;
+  }
+
+  /// Docs the range index may match for `value`: its fully matching docs plus 
the ones left for a forward-index check.
+  private static MutableRoaringBitmap 
rangeCandidates(RangeIndexReader<ImmutableRoaringBitmap> rangeIndex,
+      int value) {
+    MutableRoaringBitmap candidates = new MutableRoaringBitmap();
+    for (ImmutableRoaringBitmap docIds : 
Arrays.asList(rangeIndex.getMatchingDocIds(value, value),
+        rangeIndex.getPartiallyMatchingDocIds(value, value))) {
+      if (docIds != null) {
+        candidates.or(docIds);
+      }
+    }
+    return candidates;
+  }
+
+  @AfterClass
+  public void tearDown() {
+    FileUtils.deleteQuietly(TEMP_DIR);
+  }
+}


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

Reply via email to