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


##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/metadata/MappedSegmentMetadataStore.java:
##########
@@ -0,0 +1,943 @@
+/**
+ * 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.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.Interner;
+import com.google.common.collect.Interners;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.zip.CRC32C;
+import javax.annotation.Nullable;
+import org.apache.commons.configuration2.Configuration;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.configuration2.ex.ConfigurationException;
+import org.apache.pinot.segment.spi.ColumnMetadata;
+import org.apache.pinot.segment.spi.V1Constants;
+import org.apache.pinot.segment.spi.creator.SegmentVersion;
+import org.apache.pinot.segment.spi.index.IndexService;
+import org.apache.pinot.segment.spi.index.IndexType;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.store.ColumnIndexUtils;
+import org.apache.pinot.segment.spi.store.SegmentDirectoryPaths;
+import org.apache.pinot.segment.spi.utils.SegmentMetadataUtils;
+import org.apache.pinot.spi.config.table.FieldConfig.EncodingType;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.env.CommonsConfigurationUtils;
+import org.apache.pinot.spi.utils.ByteArray;
+import org.apache.pinot.spi.utils.ColumnNameInterner;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.spi.utils.ReadMode;
+
+/// Versioned, file-backed metadata for a sealed segment. The source 
`metadata.properties` remains the canonical
+/// representation for old readers and preprocessing.
+///
+/// The big-endian file starts with a 64-byte header containing the magic, 
format version, total length, source
+/// `metadata.properties` and `index_map` length/CRC fingerprints, registered 
index IDs, payload CRC,
+/// segment-property blob reference,
+/// column count, and record-table bounds. Sorted columns occupy fixed 
180-byte records, followed by variable blobs;
+/// each blob reference is an absolute 32-bit offset and length. Numeric 
column statistics are read directly from the
+/// backing buffer. The column layout retains names and reusable [FieldSpec] 
references on heap.
+///
+/// A stale or corrupt sidecar is rebuilt from the canonical source and 
replaced locally, using atomic rename where
+/// supported. Change `VERSION` whenever the encoding or the values derived 
from canonical metadata change; old
+/// versions are rebuilt rather than migrated.
+final class MappedSegmentMetadataStore implements Closeable {
+  static final String FILE_NAME = "segment_metadata.bin";
+  private static final String TEMP_FILE_PREFIX = ".segment_metadata.";
+  private static final String TEMP_FILE_SUFFIX = ".tmp";
+
+  static boolean isSidecarFileName(String fileName) {
+    return FILE_NAME.equals(fileName)
+        || (fileName.startsWith(TEMP_FILE_PREFIX) && 
fileName.endsWith(TEMP_FILE_SUFFIX));
+  }
+
+  private static final int MAGIC = 0x504d4431; // PMD1
+  private static final int VERSION = 5;
+  private static final int HEADER_SIZE = 64;
+  private static final int RECORD_SIZE = 180;
+
+  static final int NAME = 0;
+  static final int FIELD_SPEC = 8;
+  static final int TOTAL_DOCS = 16;
+  static final int CARDINALITY = 20;
+  static final int FLAGS = 24;
+  static final int ENCODING = 28;
+  static final int SHORTEST = 32;
+  static final int LONGEST = 36;
+  static final int TOTAL_ENTRIES = 40;
+  static final int MAX_MV = 44;
+  static final int MAX_ROW = 48;
+  static final int BITS = 52;
+  static final int MIN_TAG = 56;
+  static final int MIN_RAW = 60;
+  static final int MIN_BLOB = 68;
+  static final int MAX_TAG = 76;
+  static final int MAX_RAW = 80;
+  static final int MAX_BLOB = 88;
+  static final int PARTITION_FUNCTION = 96;
+  static final int PARTITIONS = 104;
+  static final int PARENT = 112;
+  static final int SPARSE_KEYS = 120;
+  static final int SPARSE_MULTI_VALUE_KEYS = 128;
+  static final int SPARSE_KEY_TYPES = 136;
+  static final int RAW_UNCOMPRESSED_SIZE = 144;
+  static final int DICTIONARY_UNCOMPRESSED_SIZE = 152;
+  static final int COMPRESSION_TYPE = 160;
+  static final int INDEXES = 168;
+  static final int INDEX_COUNT = 176;
+
+  static final int HAS_DICTIONARY = 1;
+  static final int SORTED = 1 << 1;
+  static final int NON_NULL = 1 << 2;
+  static final int INVALID_MIN_MAX = 1 << 3;
+  static final int ASCII = 1 << 4;
+  static final int AUTO_GENERATED = 1 << 5;
+
+  private static final int NO_VALUE = 0;
+  private static final int INT_VALUE = 1;
+  private static final int LONG_VALUE = 2;
+  private static final int FLOAT_VALUE = 3;
+  private static final int DOUBLE_VALUE = 4;
+  private static final int DECIMAL_VALUE = 5;
+  private static final int STRING_VALUE = 6;
+  private static final int BYTES_VALUE = 7;
+
+  private static final Interner<FieldSpec> FIELD_SPECS = 
Interners.newWeakInterner();
+  private static final Interner<ColumnLayout> COLUMN_LAYOUTS = 
Interners.newWeakInterner();
+
+  private final PinotDataBuffer _buffer;
+  private final ColumnLayout _columns;
+  private final int _tableOffset;
+  private final int _segmentConfigOffset;
+  private final int _segmentConfigLength;
+  private boolean _closed;
+
+  private MappedSegmentMetadataStore(PinotDataBuffer buffer, ColumnLayout 
columns, int tableOffset,
+      int segmentConfigOffset, int segmentConfigLength) {
+    _buffer = buffer;
+    _columns = columns;
+    _tableOffset = tableOffset;
+    _segmentConfigOffset = segmentConfigOffset;
+    _segmentConfigLength = segmentConfigLength;
+  }
+
+  static MappedSegmentMetadataStore open(File indexDir, ReadMode readMode)
+      throws IOException, ConfigurationException {
+    File source = SegmentDirectoryPaths.findMetadataFile(indexDir);
+    if (source == null) {
+      throw new IOException("Missing metadata.properties in " + indexDir);
+    }
+    File sidecar = new File(indexDir, FILE_NAME);
+    boolean rebuilt = false;
+    for (int attempt = 0; attempt < 3; attempt++) {
+      IndexService indexService = IndexService.getInstance();
+      Fingerprint propertiesFingerprint = Fingerprint.of(source);
+      Fingerprint indexMapFingerprint = indexMapFingerprint(indexDir, 
indexService);
+      // The validated heap copy is transient; the store retains only the 
buffer and shared column layout.
+      byte[] bytes = readValid(sidecar, propertiesFingerprint, 
indexMapFingerprint);
+      if (bytes == null) {
+        writeAtomically(sidecar, build(indexDir, propertiesFingerprint, 
indexMapFingerprint, indexService));
+        rebuilt = true;
+        bytes = readValid(sidecar, propertiesFingerprint, indexMapFingerprint);
+        if (bytes == null) {
+          continue;
+        }
+      }
+      PinotDataBuffer buffer = readMode == ReadMode.heap
+          ? PinotDataBuffer.loadFile(sidecar, 0, bytes.length, 
ByteOrder.BIG_ENDIAN, "segment metadata")
+          : PinotDataBuffer.mapFile(sidecar, true, 0, bytes.length, 
ByteOrder.BIG_ENDIAN, "segment metadata");
+      boolean keepBuffer = false;
+      try {
+        // Another loader may atomically replace the sidecar between 
validation and opening it. Check the exact
+        // buffer bytes and canonical inputs before publishing a view. The 
header alone cannot prove the bytes match.
+        if (!matchesBuffer(buffer, bytes) || 
!propertiesFingerprint.sameAs(Fingerprint.of(source))
+            || indexService != IndexService.getInstance()
+            || !indexMapFingerprint.sameAs(indexMapFingerprint(indexDir, 
indexService))) {
+          continue;
+        }
+        ByteBuffer header = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
+        int count = header.getInt(52);
+        int tableOffset = header.getInt(56);
+        String[] names = new String[count];
+        FieldSpec[] fieldSpecs = new FieldSpec[count];
+        for (int i = 0; i < count; i++) {
+          int record = tableOffset + i * RECORD_SIZE;
+          names[i] = ColumnNameInterner.intern(readString(bytes, 
header.getInt(record + NAME),
+              header.getInt(record + NAME + 4)));
+          FieldSpec parsed = JsonUtils.stringToObject(readString(bytes, 
header.getInt(record + FIELD_SPEC),
+              header.getInt(record + FIELD_SPEC + 4)), FieldSpec.class);
+          fieldSpecs[i] = parsed instanceof ComplexFieldSpec ? parsed : 
FIELD_SPECS.intern(parsed);
+        }
+        ColumnLayout columns = COLUMN_LAYOUTS.intern(new ColumnLayout(names, 
fieldSpecs));
+        MappedSegmentMetadataStore store = new 
MappedSegmentMetadataStore(buffer, columns, tableOffset,
+            header.getInt(44), header.getInt(48));
+        keepBuffer = true;
+        return store;
+      } catch (IOException | RuntimeException e) {
+        if (!rebuilt) {
+          // A checksum-valid older sidecar can still contain FieldSpec JSON 
this reader cannot parse. Rebuild it
+          // once from canonical metadata instead of falling back to eager on 
every load.
+          writeAtomically(sidecar, build(indexDir, propertiesFingerprint, 
indexMapFingerprint, indexService));
+          rebuilt = true;
+          continue;
+        }
+        throw new IOException("Invalid field specs in mapped segment metadata: 
" + sidecar, e);
+      } finally {
+        if (!keepBuffer) {
+          buffer.close();
+        }
+      }
+    }
+    throw new IOException("Metadata changed while opening segment: " + 
indexDir);
+  }
+
+  private static boolean matchesBuffer(PinotDataBuffer buffer, byte[] bytes) {
+    if (buffer.size() != bytes.length) {
+      return false;
+    }
+    byte[] block = new byte[Math.min(8192, bytes.length)];
+    for (int offset = 0; offset < bytes.length; offset += block.length) {
+      int length = Math.min(block.length, bytes.length - offset);
+      buffer.copyTo(offset, block, 0, length);
+      for (int i = 0; i < length; i++) {
+        if (block[i] != bytes[offset + i]) {
+          return false;
+        }
+      }
+    }
+    return true;
+  }
+
+  int size() {
+    return _columns._names.length;
+  }
+
+  String name(int ordinal) {
+    return _columns._names[ordinal];
+  }
+
+  int ordinal(String column) {
+    return Arrays.binarySearch(_columns._names, column);
+  }
+
+  synchronized int getInt(int ordinal, int offset) {
+    ensureOpen();
+    return _buffer.getInt((long) _tableOffset + (long) ordinal * RECORD_SIZE + 
offset);
+  }
+
+  synchronized long getLong(int ordinal, int offset) {
+    ensureOpen();
+    return _buffer.getLong((long) _tableOffset + (long) ordinal * RECORD_SIZE 
+ offset);
+  }
+
+  boolean flag(int ordinal, int flag) {
+    return (getInt(ordinal, FLAGS) & flag) != 0;
+  }
+
+  @Nullable
+  String string(int ordinal, int field) {
+    byte[] bytes = blob(ordinal, field);
+    return bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null;
+  }
+
+  @Nullable
+  synchronized byte[] blob(int ordinal, int field) {
+    int offset = getInt(ordinal, field);
+    if (offset < 0) {
+      return null;
+    }
+    int length = getInt(ordinal, field + 4);
+    byte[] bytes = new byte[length];
+    _buffer.copyTo(offset, bytes);
+    return bytes;
+  }
+
+  FieldSpec fieldSpec(int ordinal) {
+    return _columns._fieldSpecs[ordinal];
+  }
+
+  @Nullable
+  Comparable<?> value(int ordinal, boolean minimum) {
+    int tag = getInt(ordinal, minimum ? MIN_TAG : MAX_TAG);
+    long raw = getLong(ordinal, minimum ? MIN_RAW : MAX_RAW);
+    int blobField = minimum ? MIN_BLOB : MAX_BLOB;
+    switch (tag) {
+      case NO_VALUE:
+        return null;
+      case INT_VALUE:
+        return (int) raw;
+      case LONG_VALUE:
+        return raw;
+      case FLOAT_VALUE:
+        return Float.intBitsToFloat((int) raw);
+      case DOUBLE_VALUE:
+        return Double.longBitsToDouble(raw);
+      case DECIMAL_VALUE:
+        return new BigDecimal(string(ordinal, blobField));
+      case STRING_VALUE:
+        return string(ordinal, blobField);
+      case BYTES_VALUE:
+        return new ByteArray(blob(ordinal, blobField));
+      default:
+        throw new IllegalStateException("Invalid value tag: " + tag);
+    }
+  }
+
+  synchronized PropertiesConfiguration segmentConfiguration()
+      throws IOException, ConfigurationException {
+    ensureOpen();
+    byte[] bytes = new byte[_segmentConfigLength];
+    _buffer.copyTo(_segmentConfigOffset, bytes);
+    // Values were already split by the source parser. A second delimiter pass 
would change escaped commas.
+    PropertiesConfiguration config = 
CommonsConfigurationUtils.fromInputStream(null, false, null);
+    try (DataInputStream input = new DataInputStream(new 
ByteArrayInputStream(bytes))) {
+      int count = input.readInt();
+      for (int i = 0; i < count; i++) {
+        String key = readString(input);
+        int valueCount = input.readInt();
+        if (valueCount == 1) {
+          config.setProperty(key, readString(input));
+        } else {
+          List<String> values = new ArrayList<>(valueCount);
+          for (int j = 0; j < valueCount; j++) {
+            values.add(readString(input));
+          }
+          config.setProperty(key, values);
+        }
+      }
+    }
+    return config;
+  }
+
+  @Override
+  public synchronized void close()
+      throws IOException {
+    if (_closed) {
+      return;
+    }
+    _closed = true;
+    _buffer.close();
+  }
+
+  private void ensureOpen() {
+    if (_closed) {
+      throw new IllegalStateException("Mapped segment metadata is closed");
+    }
+  }
+
+  private static byte[] build(File indexDir, Fingerprint 
propertiesFingerprint, Fingerprint indexMapFingerprint,
+      IndexService indexService)
+      throws IOException, ConfigurationException {
+    SegmentMetadataImpl source = new SegmentMetadataImpl(indexDir);

Review Comment:
   Added current-head full-segment synthetic measurements to the PR 
description. Across 32 complete 1,000-column v3 segment copies and three fresh 
JVMs per mode, median load-to-first-pruned-query time at 4 load workers was 
2.110 s eager, 2.224 s mapped with cold sidecars, and 2.100 s with reused 
sidecars. Sampled peak heap/RSS was 379/683 MiB eager versus 404/737 MiB mapped 
cold; load GC was 14/51 ms versus 15/55 ms. The probe uses real index readers 
but runs in-process on macOS with identical 100-row synthetic segments, so 
actual server/pod readiness, production distribution, Linux VMA headroom, and 
50k scale remain open. Keeping this thread unresolved for that validation.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/metadata/MappedSegmentMetadataStore.java:
##########
@@ -0,0 +1,943 @@
+/**
+ * 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.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.Interner;
+import com.google.common.collect.Interners;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.zip.CRC32C;
+import javax.annotation.Nullable;
+import org.apache.commons.configuration2.Configuration;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.configuration2.ex.ConfigurationException;
+import org.apache.pinot.segment.spi.ColumnMetadata;
+import org.apache.pinot.segment.spi.V1Constants;
+import org.apache.pinot.segment.spi.creator.SegmentVersion;
+import org.apache.pinot.segment.spi.index.IndexService;
+import org.apache.pinot.segment.spi.index.IndexType;
+import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.store.ColumnIndexUtils;
+import org.apache.pinot.segment.spi.store.SegmentDirectoryPaths;
+import org.apache.pinot.segment.spi.utils.SegmentMetadataUtils;
+import org.apache.pinot.spi.config.table.FieldConfig.EncodingType;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.env.CommonsConfigurationUtils;
+import org.apache.pinot.spi.utils.ByteArray;
+import org.apache.pinot.spi.utils.ColumnNameInterner;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.spi.utils.ReadMode;
+
+/// Versioned, file-backed metadata for a sealed segment. The source 
`metadata.properties` remains the canonical
+/// representation for old readers and preprocessing.
+///
+/// The big-endian file starts with a 64-byte header containing the magic, 
format version, total length, source
+/// `metadata.properties` and `index_map` length/CRC fingerprints, registered 
index IDs, payload CRC,
+/// segment-property blob reference,
+/// column count, and record-table bounds. Sorted columns occupy fixed 
180-byte records, followed by variable blobs;
+/// each blob reference is an absolute 32-bit offset and length. Numeric 
column statistics are read directly from the
+/// backing buffer. The column layout retains names and reusable [FieldSpec] 
references on heap.
+///
+/// A stale or corrupt sidecar is rebuilt from the canonical source and 
replaced locally, using atomic rename where
+/// supported. Change `VERSION` whenever the encoding or the values derived 
from canonical metadata change; old
+/// versions are rebuilt rather than migrated.
+final class MappedSegmentMetadataStore implements Closeable {
+  static final String FILE_NAME = "segment_metadata.bin";
+  private static final String TEMP_FILE_PREFIX = ".segment_metadata.";
+  private static final String TEMP_FILE_SUFFIX = ".tmp";
+
+  static boolean isSidecarFileName(String fileName) {
+    return FILE_NAME.equals(fileName)
+        || (fileName.startsWith(TEMP_FILE_PREFIX) && 
fileName.endsWith(TEMP_FILE_SUFFIX));
+  }
+
+  private static final int MAGIC = 0x504d4431; // PMD1
+  private static final int VERSION = 5;
+  private static final int HEADER_SIZE = 64;
+  private static final int RECORD_SIZE = 180;
+
+  static final int NAME = 0;
+  static final int FIELD_SPEC = 8;
+  static final int TOTAL_DOCS = 16;
+  static final int CARDINALITY = 20;
+  static final int FLAGS = 24;
+  static final int ENCODING = 28;
+  static final int SHORTEST = 32;
+  static final int LONGEST = 36;
+  static final int TOTAL_ENTRIES = 40;
+  static final int MAX_MV = 44;
+  static final int MAX_ROW = 48;
+  static final int BITS = 52;
+  static final int MIN_TAG = 56;
+  static final int MIN_RAW = 60;
+  static final int MIN_BLOB = 68;
+  static final int MAX_TAG = 76;
+  static final int MAX_RAW = 80;
+  static final int MAX_BLOB = 88;
+  static final int PARTITION_FUNCTION = 96;
+  static final int PARTITIONS = 104;
+  static final int PARENT = 112;
+  static final int SPARSE_KEYS = 120;
+  static final int SPARSE_MULTI_VALUE_KEYS = 128;
+  static final int SPARSE_KEY_TYPES = 136;
+  static final int RAW_UNCOMPRESSED_SIZE = 144;
+  static final int DICTIONARY_UNCOMPRESSED_SIZE = 152;
+  static final int COMPRESSION_TYPE = 160;
+  static final int INDEXES = 168;
+  static final int INDEX_COUNT = 176;
+
+  static final int HAS_DICTIONARY = 1;
+  static final int SORTED = 1 << 1;
+  static final int NON_NULL = 1 << 2;
+  static final int INVALID_MIN_MAX = 1 << 3;
+  static final int ASCII = 1 << 4;
+  static final int AUTO_GENERATED = 1 << 5;
+
+  private static final int NO_VALUE = 0;
+  private static final int INT_VALUE = 1;
+  private static final int LONG_VALUE = 2;
+  private static final int FLOAT_VALUE = 3;
+  private static final int DOUBLE_VALUE = 4;
+  private static final int DECIMAL_VALUE = 5;
+  private static final int STRING_VALUE = 6;
+  private static final int BYTES_VALUE = 7;
+
+  private static final Interner<FieldSpec> FIELD_SPECS = 
Interners.newWeakInterner();
+  private static final Interner<ColumnLayout> COLUMN_LAYOUTS = 
Interners.newWeakInterner();
+
+  private final PinotDataBuffer _buffer;
+  private final ColumnLayout _columns;
+  private final int _tableOffset;
+  private final int _segmentConfigOffset;
+  private final int _segmentConfigLength;
+  private boolean _closed;
+
+  private MappedSegmentMetadataStore(PinotDataBuffer buffer, ColumnLayout 
columns, int tableOffset,
+      int segmentConfigOffset, int segmentConfigLength) {
+    _buffer = buffer;
+    _columns = columns;
+    _tableOffset = tableOffset;
+    _segmentConfigOffset = segmentConfigOffset;
+    _segmentConfigLength = segmentConfigLength;
+  }
+
+  static MappedSegmentMetadataStore open(File indexDir, ReadMode readMode)
+      throws IOException, ConfigurationException {
+    File source = SegmentDirectoryPaths.findMetadataFile(indexDir);
+    if (source == null) {
+      throw new IOException("Missing metadata.properties in " + indexDir);
+    }
+    File sidecar = new File(indexDir, FILE_NAME);
+    boolean rebuilt = false;
+    for (int attempt = 0; attempt < 3; attempt++) {
+      IndexService indexService = IndexService.getInstance();
+      Fingerprint propertiesFingerprint = Fingerprint.of(source);
+      Fingerprint indexMapFingerprint = indexMapFingerprint(indexDir, 
indexService);
+      // The validated heap copy is transient; the store retains only the 
buffer and shared column layout.
+      byte[] bytes = readValid(sidecar, propertiesFingerprint, 
indexMapFingerprint);
+      if (bytes == null) {
+        writeAtomically(sidecar, build(indexDir, propertiesFingerprint, 
indexMapFingerprint, indexService));
+        rebuilt = true;
+        bytes = readValid(sidecar, propertiesFingerprint, indexMapFingerprint);
+        if (bytes == null) {
+          continue;
+        }
+      }
+      PinotDataBuffer buffer = readMode == ReadMode.heap
+          ? PinotDataBuffer.loadFile(sidecar, 0, bytes.length, 
ByteOrder.BIG_ENDIAN, "segment metadata")
+          : PinotDataBuffer.mapFile(sidecar, true, 0, bytes.length, 
ByteOrder.BIG_ENDIAN, "segment metadata");
+      boolean keepBuffer = false;
+      try {
+        // Another loader may atomically replace the sidecar between 
validation and opening it. Check the exact
+        // buffer bytes and canonical inputs before publishing a view. The 
header alone cannot prove the bytes match.
+        if (!matchesBuffer(buffer, bytes) || 
!propertiesFingerprint.sameAs(Fingerprint.of(source))
+            || indexService != IndexService.getInstance()
+            || !indexMapFingerprint.sameAs(indexMapFingerprint(indexDir, 
indexService))) {
+          continue;
+        }
+        ByteBuffer header = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
+        int count = header.getInt(52);
+        int tableOffset = header.getInt(56);
+        String[] names = new String[count];
+        FieldSpec[] fieldSpecs = new FieldSpec[count];
+        for (int i = 0; i < count; i++) {
+          int record = tableOffset + i * RECORD_SIZE;
+          names[i] = ColumnNameInterner.intern(readString(bytes, 
header.getInt(record + NAME),
+              header.getInt(record + NAME + 4)));
+          FieldSpec parsed = JsonUtils.stringToObject(readString(bytes, 
header.getInt(record + FIELD_SPEC),
+              header.getInt(record + FIELD_SPEC + 4)), FieldSpec.class);
+          fieldSpecs[i] = parsed instanceof ComplexFieldSpec ? parsed : 
FIELD_SPECS.intern(parsed);
+        }
+        ColumnLayout columns = COLUMN_LAYOUTS.intern(new ColumnLayout(names, 
fieldSpecs));
+        MappedSegmentMetadataStore store = new 
MappedSegmentMetadataStore(buffer, columns, tableOffset,
+            header.getInt(44), header.getInt(48));
+        keepBuffer = true;
+        return store;
+      } catch (IOException | RuntimeException e) {
+        if (!rebuilt) {
+          // A checksum-valid older sidecar can still contain FieldSpec JSON 
this reader cannot parse. Rebuild it
+          // once from canonical metadata instead of falling back to eager on 
every load.
+          writeAtomically(sidecar, build(indexDir, propertiesFingerprint, 
indexMapFingerprint, indexService));
+          rebuilt = true;
+          continue;
+        }
+        throw new IOException("Invalid field specs in mapped segment metadata: 
" + sidecar, e);
+      } finally {
+        if (!keepBuffer) {
+          buffer.close();
+        }
+      }
+    }
+    throw new IOException("Metadata changed while opening segment: " + 
indexDir);
+  }
+
+  private static boolean matchesBuffer(PinotDataBuffer buffer, byte[] bytes) {
+    if (buffer.size() != bytes.length) {
+      return false;
+    }
+    byte[] block = new byte[Math.min(8192, bytes.length)];
+    for (int offset = 0; offset < bytes.length; offset += block.length) {
+      int length = Math.min(block.length, bytes.length - offset);
+      buffer.copyTo(offset, block, 0, length);
+      for (int i = 0; i < length; i++) {
+        if (block[i] != bytes[offset + i]) {
+          return false;
+        }
+      }
+    }
+    return true;
+  }
+
+  int size() {
+    return _columns._names.length;
+  }
+
+  String name(int ordinal) {
+    return _columns._names[ordinal];
+  }
+
+  int ordinal(String column) {
+    return Arrays.binarySearch(_columns._names, column);
+  }
+
+  synchronized int getInt(int ordinal, int offset) {

Review Comment:
   Added a bounded same-segment query comparison on current head 47e02405cd to 
the PR description. One complete 1,000-column v3 segment ran filtered COUNT, 
filtered SUM, and a min/max-pruned COUNT through in-process plans, 100 queries 
per worker across three JVMs. Median per-run p95 eager versus mapped cold was 
213/221 microseconds at 1 worker, 163/158 at 4, 174/186 at 8, and 309/253 at 
16. This tiny 100-row synthetic fixture shows no clear query regression, but it 
is not a representative production query mix or server load; keeping the thread 
open for that comparison. The close/read synchronization remains unchanged.



-- 
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