xiangfu0 commented on code in PR #19998:
URL: https://github.com/apache/pinot/pull/19998#discussion_r4355997676


##########
pinot-server/src/main/java/org/apache/pinot/server/api/resources/TablesResource.java:
##########
@@ -1101,11 +1108,23 @@ private File createSegmentTarFile(TableDataManager 
tableDataManager, String segm
     File segmentTarFile = 
org.apache.pinot.common.utils.FileUtils.concatAndValidateFile(segmentTarUploadDir,
         tableNameWithType + "_" + segmentName + "_" + UUID.randomUUID() + 
TarCompressionUtils.TAR_GZ_FILE_EXTENSION,
         "Invalid table / segment name: %s, %s", tableNameWithType, 
segmentName);
-    TarCompressionUtils.createCompressedTarFile(new 
File(tableDataManager.getTableDataDir(), segmentName),
-        segmentTarFile);
+    createSegmentTransferTarFile(new File(tableDataManager.getTableDataDir(), 
segmentName), segmentTarFile);
     return segmentTarFile;
   }
 
+  private static void createSegmentTransferTarFile(File segmentDir, File 
segmentTarFile)
+      throws IOException {
+    TarCompressionUtils.createFilteredCompressedTarFile(segmentDir, 
segmentTarFile, file -> {
+      if (!segmentDir.equals(file.getParentFile())) {
+        return true;
+      }
+      // These files are local serving artifacts, rebuilt from 
metadata.properties on the receiving server.
+      String name = file.getName();
+      return !name.equals("segment_metadata.bin")

Review Comment:
   The excluded names here (`segment_metadata.bin` and the 
`.segment_metadata.*.tmp` temp prefix) are string literals that must stay in 
sync with `MappedSegmentMetadataStore.FILE_NAME` and its `createTempFile` 
prefix in another module. They match today, but since the constant is 
package-private in pinot-segment-spi, a rename there would silently leak the 
sidecar into the transfer tar. Worth a shared/visible constant or at least a 
cross-referencing comment.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/metadata/MappedColumnMetadata.java:
##########
@@ -0,0 +1,394 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.index.metadata;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.segment.spi.ColumnMetadata;
+import org.apache.pinot.segment.spi.compression.ChunkCompressionType;
+import org.apache.pinot.segment.spi.index.IndexService;
+import org.apache.pinot.segment.spi.index.IndexType;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionFunctionFactory;
+import org.apache.pinot.spi.config.table.FieldConfig.EncodingType;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.utils.JsonUtils;
+
+/// A small view of one fixed record in [MappedSegmentMetadataStore]. No 
per-column values are copied into this view.
+/// Data-source metadata delegates to this live view. Neither can outlive the 
owning segment: reference-counted

Review Comment:
   The Javadoc says teardown is "reference-counted" so it waits for query 
readers, but this class has no ref-count or read-lock over `_store`/`_buffer`. 
The real guarantee comes from the enclosing `SegmentDataManager` reference 
count (acquire/release around queries and REST), which gates `destroy()` and 
therefore the unmap. Since reads here have no `_closed` guard, a read after 
close is an unmapped-buffer access (SIGSEGV), not a clean exception. Could you 
reword this to describe the actual external contract — callers must hold the 
segment reference for the full duration of any read — so a future caller 
doesn't read mapped metadata off the acquire path and crash the server?



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/metadata/MappedColumnMetadata.java:
##########
@@ -0,0 +1,394 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.index.metadata;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.apache.pinot.segment.spi.ColumnMetadata;
+import org.apache.pinot.segment.spi.compression.ChunkCompressionType;
+import org.apache.pinot.segment.spi.index.IndexService;
+import org.apache.pinot.segment.spi.index.IndexType;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionFunctionFactory;
+import org.apache.pinot.spi.config.table.FieldConfig.EncodingType;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.utils.JsonUtils;
+
+/// A small view of one fixed record in [MappedSegmentMetadataStore]. No 
per-column values are copied into this view.
+/// Data-source metadata delegates to this live view. Neither can outlive the 
owning segment: reference-counted
+/// teardown must wait for query readers before closing the mapping.
+public final class MappedColumnMetadata implements ColumnMetadata {
+  private final MappedSegmentMetadataStore _store;
+  private final int _ordinal;
+  @Nullable
+  private volatile PartitionFunction _partitionFunction;
+  @Nullable
+  private volatile Set<Integer> _partitions;
+  @Nullable
+  private volatile Bounds _bounds;
+  @Nullable
+  private volatile IndexSize[] _indexes;
+
+  private static final class Bounds {
+    @Nullable
+    private final Comparable<?> _minimum;
+    @Nullable
+    private final Comparable<?> _maximum;
+
+    private Bounds(@Nullable Comparable<?> minimum, @Nullable Comparable<?> 
maximum) {
+      _minimum = minimum;
+      _maximum = maximum;
+    }
+  }
+
+  MappedColumnMetadata(MappedSegmentMetadataStore store, int ordinal) {
+    _store = store;
+    _ordinal = ordinal;
+  }
+
+  @Override
+  public FieldSpec getFieldSpec() {
+    // Field specs are shared across mapped segments; callers must treat the 
returned spec as read-only.
+    return _store.fieldSpec(_ordinal);
+  }
+
+  @Override
+  public int getTotalDocs() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.TOTAL_DOCS);
+  }
+
+  @Override
+  public int getCardinality() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.CARDINALITY);
+  }
+
+  @Override
+  public boolean hasDictionary() {
+    return _store.flag(_ordinal, MappedSegmentMetadataStore.HAS_DICTIONARY);
+  }
+
+  @Nullable
+  @Override
+  public EncodingType getForwardIndexEncoding() {
+    switch (_store.getInt(_ordinal, MappedSegmentMetadataStore.ENCODING)) {
+      case 0:
+        return null;
+      case 1:
+        return EncodingType.RAW;
+      case 2:
+        return EncodingType.DICTIONARY;
+      default:
+        throw new IllegalStateException("Invalid forward-index encoding");
+    }
+  }
+
+  @Override
+  public boolean isSorted() {
+    return _store.flag(_ordinal, MappedSegmentMetadataStore.SORTED);
+  }
+
+  @Override
+  public boolean isNonNull() {
+    return _store.flag(_ordinal, MappedSegmentMetadataStore.NON_NULL);
+  }
+
+  @Nullable
+  @Override
+  public Comparable<?> getMinValue() {
+    return bounds()._minimum;
+  }
+
+  @Nullable
+  @Override
+  public Comparable<?> getMaxValue() {
+    return bounds()._maximum;
+  }
+
+  private Bounds bounds() {
+    Bounds bounds = _bounds;
+    if (bounds == null) {
+      synchronized (this) {
+        bounds = _bounds;
+        if (bounds == null) {
+          bounds = new Bounds(_store.value(_ordinal, true), 
_store.value(_ordinal, false));
+          _bounds = bounds;
+        }
+      }
+    }
+    return bounds;
+  }
+
+  @Override
+  public boolean isMinMaxValueInvalid() {
+    return _store.flag(_ordinal, MappedSegmentMetadataStore.INVALID_MIN_MAX);
+  }
+
+  @Override
+  public int getLengthOfShortestElement() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.SHORTEST);
+  }
+
+  @Override
+  public int getLengthOfLongestElement() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.LONGEST);
+  }
+
+  @Override
+  public boolean isAscii() {
+    return _store.flag(_ordinal, MappedSegmentMetadataStore.ASCII);
+  }
+
+  @Override
+  public int getBitsPerElement() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.BITS);
+  }
+
+  @Override
+  public int getTotalNumberOfEntries() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.TOTAL_ENTRIES);
+  }
+
+  @Override
+  public int getMaxNumberOfMultiValues() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.MAX_MV);
+  }
+
+  @Override
+  public int getMaxRowLengthInBytes() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.MAX_ROW);
+  }
+
+  @Nullable
+  @Override
+  public PartitionFunction getPartitionFunction() {
+    PartitionFunction cached = _partitionFunction;
+    if (cached == null) {
+      synchronized (this) {
+        cached = _partitionFunction;
+        if (cached == null) {
+          cached = decodePartitionFunction();
+          _partitionFunction = cached;
+        }
+      }
+    }
+    return cached;
+  }
+
+  @Nullable
+  private PartitionFunction decodePartitionFunction() {
+    byte[] bytes = _store.blob(_ordinal, 
MappedSegmentMetadataStore.PARTITION_FUNCTION);
+    if (bytes == null) {
+      return null;
+    }
+    try (DataInputStream input = new DataInputStream(new 
ByteArrayInputStream(bytes))) {
+      String name = MappedSegmentMetadataStore.readString(input);
+      int numPartitions = input.readInt();
+      int configSize = input.readInt();
+      Map<String, String> config = configSize != 0 ? new HashMap<>(configSize) 
: null;
+      for (int i = 0; i < configSize; i++) {
+        config.put(MappedSegmentMetadataStore.readString(input), 
MappedSegmentMetadataStore.readString(input));
+      }
+      return PartitionFunctionFactory.getPartitionFunction(name, 
numPartitions, config);
+    } catch (IOException e) {
+      throw new IllegalStateException("Cannot decode partition function for " 
+ getColumnName(), e);
+    }
+  }
+
+  @Nullable
+  @Override
+  public Set<Integer> getPartitions() {
+    Set<Integer> cached = _partitions;
+    if (cached == null) {
+      synchronized (this) {
+        cached = _partitions;
+        if (cached == null) {
+          cached = decodePartitions();
+          _partitions = cached;
+        }
+      }
+    }
+    return cached;
+  }
+
+  @Nullable
+  private Set<Integer> decodePartitions() {
+    byte[] bytes = _store.blob(_ordinal, 
MappedSegmentMetadataStore.PARTITIONS);
+    if (bytes == null) {
+      return null;
+    }
+    try (DataInputStream input = new DataInputStream(new 
ByteArrayInputStream(bytes))) {
+      int count = input.readInt();
+      Set<Integer> partitions = new HashSet<>(count);
+      for (int i = 0; i < count; i++) {
+        partitions.add(input.readInt());
+      }
+      return partitions;
+    } catch (IOException e) {
+      throw new IllegalStateException("Cannot decode partitions for " + 
getColumnName(), e);
+    }
+  }
+
+  @Override
+  public boolean isAutoGenerated() {
+    return _store.flag(_ordinal, MappedSegmentMetadataStore.AUTO_GENERATED);
+  }
+
+  @Override
+  public boolean isMaterializedChild() {
+    return getParentColumn() != null;
+  }
+
+  @Nullable
+  @Override
+  public String getParentColumn() {
+    return _store.string(_ordinal, MappedSegmentMetadataStore.PARENT);
+  }
+
+  @Nullable
+  @Override
+  public List<String> getSparseKeys() {
+    return readJson(MappedSegmentMetadataStore.SPARSE_KEYS, new 
TypeReference<List<String>>() { });
+  }
+
+  @Nullable
+  @Override
+  public Map<String, Integer> getSparseMultiValueKeys() {
+    return readJson(MappedSegmentMetadataStore.SPARSE_MULTI_VALUE_KEYS,
+        new TypeReference<Map<String, Integer>>() { });
+  }
+
+  @Nullable
+  @Override
+  public Map<String, DataType> getSparseKeyTypes() {
+    return readJson(MappedSegmentMetadataStore.SPARSE_KEY_TYPES,
+        new TypeReference<Map<String, DataType>>() { });
+  }
+
+  @Nullable
+  private <T> T readJson(int field, TypeReference<T> type) {
+    String json = _store.string(_ordinal, field);
+    if (json == null) {
+      return null;
+    }
+    try {
+      return JsonUtils.stringToObject(json, type);
+    } catch (IOException e) {
+      throw new IllegalStateException("Cannot decode OPEN_STRUCT metadata for 
" + getColumnName(), e);
+    }
+  }
+
+  @Override
+  public int getNumIndexes() {
+    return _store.getInt(_ordinal, MappedSegmentMetadataStore.INDEX_COUNT);
+  }
+
+  @Override
+  public short getIndexType(int position) {
+    return 
IndexService.getInstance().getNumericId(IndexService.getInstance().get(indexAt(position)._type));
+  }
+
+  @Override
+  public long getIndexSize(int position) {
+    return indexAt(position)._size;
+  }
+
+  @Override
+  public long getIndexSizeFor(IndexType type) {
+    for (int i = 0; i < getNumIndexes(); i++) {
+      IndexSize entry = indexAt(i);
+      if (entry._type.equals(type.getId())) {
+        return entry._size;
+      }
+    }
+    return UNAVAILABLE;
+  }
+
+  /// Kept for the segment-metadata REST JSON representation.
+  @SuppressWarnings("unused")
+  public Map<IndexType<?, ?, ?>, Long> getIndexSizeMap() {
+    Map<IndexType<?, ?, ?>, Long> sizes = new HashMap<>();
+    for (int i = 0; i < getNumIndexes(); i++) {
+      IndexSize entry = indexAt(i);
+      sizes.put(IndexService.getInstance().get(entry._type), entry._size);
+    }
+    return sizes;
+  }
+
+  private IndexSize indexAt(int position) {
+    int count = getNumIndexes();
+    if (position < 0 || position >= count) {
+      throw new IndexOutOfBoundsException(position);
+    }
+    IndexSize[] indexes = _indexes;
+    if (indexes == null) {
+      synchronized (this) {
+        indexes = _indexes;
+        if (indexes == null) {
+          byte[] bytes = _store.blob(_ordinal, 
MappedSegmentMetadataStore.INDEXES);
+          indexes = new IndexSize[count];
+          try (DataInputStream input = new DataInputStream(new 
ByteArrayInputStream(bytes))) {

Review Comment:
   `indexAt` assumes `_store.blob(_ordinal, INDEXES)` is non-null whenever 
`getNumIndexes() > 0`. That invariant is guaranteed by `build()`/`validate()` 
today, so this is safe, but a one-line null guard that throws 
`IllegalStateException` would turn a hypothetical 
checksum-colliding-but-corrupt file into a clean failure instead of an NPE.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/immutable/ImmutableSegmentImpl.java:
##########
@@ -115,19 +114,18 @@ public ImmutableSegmentImpl(
     _segmentMetadata = segmentMetadata;
     _indexContainerMap = columnIndexContainerMap;
     _starTreeIndexContainer = starTreeIndexContainer;
-    _dataSources =
-        new 
Object2ObjectOpenHashMap<>(segmentMetadata.getColumnMetadataMap().size());
+    _dataSources = new 
Object2ObjectOpenHashMap<>(columnIndexContainerMap.size());
 
     Map<String, Map<String, DataSource>> openStructDenseChildren = new 
HashMap<>();
     Map<String, DataSource> openStructSparseChildren = new HashMap<>();
     Set<String> openStructParents = new HashSet<>();
 
-    for (Map.Entry<String, ColumnMetadata> entry : 
segmentMetadata.getColumnMetadataMap().entrySet()) {
+    for (Map.Entry<String, ColumnIndexContainer> entry : 
columnIndexContainerMap.entrySet()) {
       String colName = entry.getKey();
-      ColumnMetadata columnMetadata = entry.getValue();
+      ColumnMetadata columnMetadata = 
segmentMetadata.getColumnMetadataFor(colName);
 
-      if (columnMetadata instanceof ColumnMetadataImpl && 
((ColumnMetadataImpl) columnMetadata).isMaterializedChild()) {
-        String parent = ((ColumnMetadataImpl) 
columnMetadata).getParentColumn();
+      if (columnMetadata.isMaterializedChild()) {

Review Comment:
   This now iterates `columnIndexContainerMap` and dereferences 
`segmentMetadata.getColumnMetadataFor(colName)` without a null check, while 
that method is now `@Nullable`. In the normal loader path every container key 
has metadata so it's not reachable today, but a container key without matching 
metadata would NPE here rather than being skipped. A small `if (columnMetadata 
== null) continue;` (or folding the null check into the `isMaterializedChild()` 
guard) keeps it robust against the looser contract.



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

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to