divjotarora commented on code in PR #3610:
URL: https://github.com/apache/parquet-java/pull/3610#discussion_r3569059246


##########
parquet-column/src/main/java/org/apache/parquet/schema/PrimitiveComparator.java:
##########
@@ -354,4 +355,36 @@ public String toString() {
           return "BINARY_AS_FLOAT16_IEEE_754_TOTAL_ORDER_COMPARATOR";
         }
       };
+
+  /**
+   * Comparator for two timestamps encoded as INT96 (12-byte little-endian) 
binary.
+   * Layout: first 8 bytes = nanoseconds within the day, last 4 bytes = Julian 
day.
+   *
+   * Two-level comparison, matching the INT96 timestamp sort order:
+   * 1. Compare the last 4 bytes (Julian day) as a signed little-endian int32.
+   * 2. If equal, compare the first 8 bytes (nanos) as a signed little-endian 
int64.

Review Comment:
   Added validation for both cases



##########
parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java:
##########
@@ -354,6 +359,60 @@ public void 
testBinaryAsSignedIntegerComparatorWithEquals() {
     }
   }
 
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return new NanoTime(julianDay, nanosOfDay).toBinary();
+  }
+
+  private static Binary timestampToInt96(String timestamp) {
+    LocalDateTime dt = LocalDateTime.parse(timestamp);
+    int julianDay = (int) (dt.toLocalDate().toEpochDay() + 2440588);
+    return new NanoTime(julianDay, dt.toLocalTime().toNanoOfDay()).toBinary();
+  }
+
+  @Test
+  public void testInt96TimestampComparator() {
+    Binary[] valuesInAscendingOrder = {
+      int96(Integer.MIN_VALUE, 0), // most negative julian day
+      int96(-1, 86_399_999_999_999L), // negative julian days sort before day 0
+      int96(0, 0), // start of the julian period
+      int96(0, 86_399_999_999_999L), // same day, later time of day
+      timestampToInt96("1968-05-23T00:00:00.000000123"), // pre-epoch but 
positive julian day
+      timestampToInt96("2020-01-01T12:00:00"),
+      timestampToInt96("2020-02-01T11:00:00"), // later day even though 
earlier time of day
+      timestampToInt96("2020-02-01T11:00:00.000000001"), // nanos tie-break
+      int96(Integer.MAX_VALUE, 86_399_999_999_999L)
+    };
+
+    // The same value in different Binary representations must compare 
identically; the offset
+    // variant guards against absolute reads not being relative to the value's 
start
+    List<Function<Binary, Binary>> representations = List.of(
+        b -> b,
+        b -> Binary.fromReusedByteArray(b.getBytes()),

Review Comment:
   Removed, now we're just testing using `valuesInAscendingOrder`



##########
parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java:
##########
@@ -354,6 +359,60 @@ public void 
testBinaryAsSignedIntegerComparatorWithEquals() {
     }
   }
 
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return new NanoTime(julianDay, nanosOfDay).toBinary();
+  }
+
+  private static Binary timestampToInt96(String timestamp) {

Review Comment:
   Removed this function



##########
parquet-hadoop/src/main/java/org/apache/parquet/format/converter/ParquetMetadataConverter.java:
##########
@@ -2057,7 +2064,17 @@ private void buildChildren(
                   || schemaElement.converted_type == ConvertedType.INTERVAL)) {
             columnOrder = org.apache.parquet.schema.ColumnOrder.undefined();
           }
+          // INT96_TIMESTAMP_ORDER is only valid for INT96 columns, ignore it 
anywhere else.
+          if (columnOrder.getColumnOrderName() == 
ColumnOrderName.INT96_TIMESTAMP_ORDER
+              && schemaElement.type != Type.INT96) {
+            columnOrder = org.apache.parquet.schema.ColumnOrder.undefined();
+          }
           primitiveBuilder.columnOrder(columnOrder);
+        } else if (schemaElement.type == Type.INT96) {
+          // A footer without column orders predates INT96_TIMESTAMP_ORDER, so 
an INT96 column here
+          // must not inherit the (chronological) construction-time default: 
its stats, if any, were
+          // written under the legacy order and must be ignored.
+          
primitiveBuilder.columnOrder(org.apache.parquet.schema.ColumnOrder.undefined());

Review Comment:
   Added such a test



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)

Review Comment:
   Renamed `copyWithNewFooter`



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {

Review Comment:
   Removed this function



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)
+      throws IOException {
+    byte[] bytes = Files.readAllBytes(src.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    File dst = new File(tmp.getRoot(), name);
+    try (FileOutputStream out = new FileOutputStream(dst)) {
+      out.write(bytes, 0, footerStart);
+      ByteArrayOutputStream serialized = new ByteArrayOutputStream();
+      Util.writeFileMetaData(footer, serialized);
+      out.write(serialized.toByteArray());
+      out.write(ByteBuffer.allocate(4)
+          .order(ByteOrder.LITTLE_ENDIAN)
+          .putInt(serialized.size())
+          .array());
+      out.write(ParquetFileWriter.MAGIC);
+    }
+    return dst;
+  }
+
+  /**
+   * Retags the INT96 column orders in the footer as TYPE_ORDER while leaving 
the (already written)
+   * min/max statistics in place. This simulates a legacy writer that emitted 
INT96 stats under
+   * TYPE_ORDER before INT96_TIMESTAMP_ORDER existed; such stats must be 
ignored by the reader.
+   */
+  private static void downgradeInt96ToTypeOrder(FileMetaData footer) {
+    for (org.apache.parquet.format.ColumnOrder columnOrder : 
footer.getColumn_orders()) {
+      if (columnOrder.isSetINT96_TIMESTAMP_ORDER()) {
+        columnOrder.setTYPE_ORDER(new TypeDefinedOrder());
+      }
+    }
+  }
+
+  private static ColumnChunkMetaData getColumn(ParquetMetadata footer, String 
name) {
+    BlockMetaData block = footer.getBlocks().get(0);
+    return block.getColumns().stream()
+        .filter(c -> c.getPath().toDotString().equals(name))
+        .findFirst()
+        .orElseThrow(() -> new IllegalArgumentException("no column " + name));
+  }
+
+  private static void assertStatsIgnored(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() == null || 
!column.getStatistics().hasNonNullValue());
+  }
+
+  private static void assertStatsUsable(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() != null && 
column.getStatistics().hasNonNullValue());
+    assertArrayEquals(EXPECTED_MIN.getBytes(), 
column.getStatistics().getMinBytes());
+    assertArrayEquals(EXPECTED_MAX.getBytes(), 
column.getStatistics().getMaxBytes());
+  }
+
+  @Test
+  public void testWriterEmitsInt96StatsAndColumnOrder() throws IOException {
+    // Values are written in non-chronological order; the writer must still 
produce the
+    // chronological min/max, not first/last or byte-wise extremes.
+    File file = writeFile();
+    FileMetaData rawFooter = readRawFooter(file);
+    // schema[0] is the message root; column_orders are indexed by leaf order: 
ts=0, id=1
+    
assertTrue(rawFooter.getColumn_orders().get(0).isSetINT96_TIMESTAMP_ORDER());
+    assertTrue(rawFooter.getColumn_orders().get(1).isSetTYPE_ORDER());

Review Comment:
   Removed



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)
+      throws IOException {
+    byte[] bytes = Files.readAllBytes(src.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    File dst = new File(tmp.getRoot(), name);
+    try (FileOutputStream out = new FileOutputStream(dst)) {
+      out.write(bytes, 0, footerStart);
+      ByteArrayOutputStream serialized = new ByteArrayOutputStream();
+      Util.writeFileMetaData(footer, serialized);
+      out.write(serialized.toByteArray());
+      out.write(ByteBuffer.allocate(4)
+          .order(ByteOrder.LITTLE_ENDIAN)
+          .putInt(serialized.size())
+          .array());
+      out.write(ParquetFileWriter.MAGIC);
+    }
+    return dst;
+  }
+
+  /**
+   * Retags the INT96 column orders in the footer as TYPE_ORDER while leaving 
the (already written)
+   * min/max statistics in place. This simulates a legacy writer that emitted 
INT96 stats under
+   * TYPE_ORDER before INT96_TIMESTAMP_ORDER existed; such stats must be 
ignored by the reader.
+   */
+  private static void downgradeInt96ToTypeOrder(FileMetaData footer) {
+    for (org.apache.parquet.format.ColumnOrder columnOrder : 
footer.getColumn_orders()) {
+      if (columnOrder.isSetINT96_TIMESTAMP_ORDER()) {
+        columnOrder.setTYPE_ORDER(new TypeDefinedOrder());
+      }
+    }
+  }
+
+  private static ColumnChunkMetaData getColumn(ParquetMetadata footer, String 
name) {
+    BlockMetaData block = footer.getBlocks().get(0);
+    return block.getColumns().stream()
+        .filter(c -> c.getPath().toDotString().equals(name))
+        .findFirst()
+        .orElseThrow(() -> new IllegalArgumentException("no column " + name));
+  }
+
+  private static void assertStatsIgnored(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() == null || 
!column.getStatistics().hasNonNullValue());
+  }
+
+  private static void assertStatsUsable(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() != null && 
column.getStatistics().hasNonNullValue());
+    assertArrayEquals(EXPECTED_MIN.getBytes(), 
column.getStatistics().getMinBytes());
+    assertArrayEquals(EXPECTED_MAX.getBytes(), 
column.getStatistics().getMaxBytes());
+  }
+
+  @Test
+  public void testWriterEmitsInt96StatsAndColumnOrder() throws IOException {
+    // Values are written in non-chronological order; the writer must still 
produce the
+    // chronological min/max, not first/last or byte-wise extremes.
+    File file = writeFile();
+    FileMetaData rawFooter = readRawFooter(file);
+    // schema[0] is the message root; column_orders are indexed by leaf order: 
ts=0, id=1
+    
assertTrue(rawFooter.getColumn_orders().get(0).isSetINT96_TIMESTAMP_ORDER());
+    assertTrue(rawFooter.getColumn_orders().get(1).isSetTYPE_ORDER());
+
+    for (RowGroup rowGroup : rawFooter.getRow_groups()) {
+      for (ColumnChunk chunk : rowGroup.getColumns()) {

Review Comment:
   Done



##########
parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBinaryTruncator.java:
##########
@@ -93,7 +93,16 @@ public void testContractNonStringTypes() {
     testTruncator(
         
Types.required(FIXED_LEN_BYTE_ARRAY).length(12).as(INTERVAL).named("test_fixed_interval"),
 false);
     
testTruncator(Types.required(BINARY).as(DECIMAL).precision(10).scale(2).named("test_binary_decimal"),
 false);
-    testTruncator(Types.required(INT96).named("test_int96"), false);
+
+    // INT96 has a fixed 12-byte width and a chronological comparator (so it 
is excluded from the
+    // variable-length checks above, like FLOAT16). Its truncator is a no-op: 
verify it returns the
+    // value unchanged regardless of the requested length.
+    BinaryTruncator int96Truncator = BinaryTruncator.getTruncator(

Review Comment:
   Added a separate `testInt96`



##########
parquet-column/src/main/java/org/apache/parquet/schema/PrimitiveType.java:
##########
@@ -578,9 +580,15 @@ public PrimitiveType(
     this.decimalMeta = decimalMeta;
 
     if (columnOrder == null) {
-      columnOrder = primitive == PrimitiveTypeName.INT96 || originalType == 
OriginalType.INTERVAL
-          ? ColumnOrder.undefined()
-          : ColumnOrder.typeDefined();
+      if (primitive == PrimitiveTypeName.INT96) {
+        // A plain INT96 is the legacy timestamp encoding; default it to the 
chronological order.
+        // An annotated INT96 carries other semantics, so leave its order 
undefined.
+        columnOrder = originalType == null ? ColumnOrder.int96TimestampOrder() 
: ColumnOrder.undefined();

Review Comment:
   done



##########
parquet-hadoop/src/main/java/org/apache/parquet/format/converter/ParquetMetadataConverter.java:
##########
@@ -911,8 +916,10 @@ private static byte[] tuncateMax(BinaryTruncator 
truncator, int truncateLength,
   }
 
   private static boolean isMinMaxStatsSupported(PrimitiveType type) {
-    return type.columnOrder().getColumnOrderName() == 
ColumnOrderName.TYPE_DEFINED_ORDER
-        || type.columnOrder().getColumnOrderName() == 
ColumnOrderName.IEEE_754_TOTAL_ORDER;
+    ColumnOrderName name = type.columnOrder().getColumnOrderName();
+    return name == ColumnOrderName.TYPE_DEFINED_ORDER
+        || name == ColumnOrderName.IEEE_754_TOTAL_ORDER
+        || name == ColumnOrderName.INT96_TIMESTAMP_ORDER;

Review Comment:
   Switched to `switch`



##########
parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java:
##########
@@ -354,6 +359,60 @@ public void 
testBinaryAsSignedIntegerComparatorWithEquals() {
     }
   }
 
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return new NanoTime(julianDay, nanosOfDay).toBinary();
+  }
+
+  private static Binary timestampToInt96(String timestamp) {
+    LocalDateTime dt = LocalDateTime.parse(timestamp);
+    int julianDay = (int) (dt.toLocalDate().toEpochDay() + 2440588);
+    return new NanoTime(julianDay, dt.toLocalTime().toNanoOfDay()).toBinary();
+  }
+
+  @Test
+  public void testInt96TimestampComparator() {

Review Comment:
   Added a separate test case



##########
parquet-hadoop/src/test/java/org/apache/parquet/format/converter/TestParquetMetadataConverter.java:
##########
@@ -1171,17 +1171,14 @@ public void testMissingValuesFromStats() {
 
   @Test
   public void testSkippedV2Stats() {
+    // INTERVAL has an undefined column order, so its stats are skipped.

Review Comment:
   Removed



##########
parquet-hadoop/src/test/java/org/apache/parquet/format/converter/TestParquetMetadataConverter.java:
##########
@@ -1171,17 +1171,14 @@ public void testMissingValuesFromStats() {
 
   @Test
   public void testSkippedV2Stats() {
+    // INTERVAL has an undefined column order, so its stats are skipped.
     testSkippedV2Stats(
         Types.optional(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY)
             .length(12)
             .as(OriginalType.INTERVAL)
             .named(""),
         new BigInteger("12345678"),
         new BigInteger("12345679"));
-    testSkippedV2Stats(
-        Types.optional(PrimitiveTypeName.INT96).named(""),
-        new BigInteger("-75687987"),
-        new BigInteger("45367657"));

Review Comment:
   Fixed `testV2StatsEqualMinMax` to use `NanoTime#toBinary()` and added the 
`Statistics` implementation for `Binary` as well. Also added an INT96 test case 
to `testV2OnlyStats`



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)
+      throws IOException {
+    byte[] bytes = Files.readAllBytes(src.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    File dst = new File(tmp.getRoot(), name);
+    try (FileOutputStream out = new FileOutputStream(dst)) {
+      out.write(bytes, 0, footerStart);
+      ByteArrayOutputStream serialized = new ByteArrayOutputStream();
+      Util.writeFileMetaData(footer, serialized);
+      out.write(serialized.toByteArray());
+      out.write(ByteBuffer.allocate(4)
+          .order(ByteOrder.LITTLE_ENDIAN)
+          .putInt(serialized.size())
+          .array());
+      out.write(ParquetFileWriter.MAGIC);
+    }
+    return dst;
+  }
+
+  /**
+   * Retags the INT96 column orders in the footer as TYPE_ORDER while leaving 
the (already written)
+   * min/max statistics in place. This simulates a legacy writer that emitted 
INT96 stats under
+   * TYPE_ORDER before INT96_TIMESTAMP_ORDER existed; such stats must be 
ignored by the reader.
+   */
+  private static void downgradeInt96ToTypeOrder(FileMetaData footer) {

Review Comment:
   I wasn't able to test `UNDEFINED` as I didn't find a good way to serialize 
an undefined value for the union



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)
+      throws IOException {
+    byte[] bytes = Files.readAllBytes(src.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    File dst = new File(tmp.getRoot(), name);
+    try (FileOutputStream out = new FileOutputStream(dst)) {
+      out.write(bytes, 0, footerStart);
+      ByteArrayOutputStream serialized = new ByteArrayOutputStream();
+      Util.writeFileMetaData(footer, serialized);
+      out.write(serialized.toByteArray());
+      out.write(ByteBuffer.allocate(4)
+          .order(ByteOrder.LITTLE_ENDIAN)
+          .putInt(serialized.size())
+          .array());
+      out.write(ParquetFileWriter.MAGIC);
+    }
+    return dst;
+  }
+
+  /**
+   * Retags the INT96 column orders in the footer as TYPE_ORDER while leaving 
the (already written)
+   * min/max statistics in place. This simulates a legacy writer that emitted 
INT96 stats under
+   * TYPE_ORDER before INT96_TIMESTAMP_ORDER existed; such stats must be 
ignored by the reader.
+   */
+  private static void downgradeInt96ToTypeOrder(FileMetaData footer) {
+    for (org.apache.parquet.format.ColumnOrder columnOrder : 
footer.getColumn_orders()) {
+      if (columnOrder.isSetINT96_TIMESTAMP_ORDER()) {
+        columnOrder.setTYPE_ORDER(new TypeDefinedOrder());
+      }
+    }
+  }
+
+  private static ColumnChunkMetaData getColumn(ParquetMetadata footer, String 
name) {
+    BlockMetaData block = footer.getBlocks().get(0);
+    return block.getColumns().stream()
+        .filter(c -> c.getPath().toDotString().equals(name))
+        .findFirst()
+        .orElseThrow(() -> new IllegalArgumentException("no column " + name));
+  }
+
+  private static void assertStatsIgnored(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() == null || 
!column.getStatistics().hasNonNullValue());
+  }
+
+  private static void assertStatsUsable(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() != null && 
column.getStatistics().hasNonNullValue());
+    assertArrayEquals(EXPECTED_MIN.getBytes(), 
column.getStatistics().getMinBytes());
+    assertArrayEquals(EXPECTED_MAX.getBytes(), 
column.getStatistics().getMaxBytes());
+  }
+
+  @Test
+  public void testWriterEmitsInt96StatsAndColumnOrder() throws IOException {
+    // Values are written in non-chronological order; the writer must still 
produce the
+    // chronological min/max, not first/last or byte-wise extremes.
+    File file = writeFile();
+    FileMetaData rawFooter = readRawFooter(file);
+    // schema[0] is the message root; column_orders are indexed by leaf order: 
ts=0, id=1
+    
assertTrue(rawFooter.getColumn_orders().get(0).isSetINT96_TIMESTAMP_ORDER());
+    assertTrue(rawFooter.getColumn_orders().get(1).isSetTYPE_ORDER());
+
+    for (RowGroup rowGroup : rawFooter.getRow_groups()) {
+      for (ColumnChunk chunk : rowGroup.getColumns()) {
+        if (chunk.getMeta_data().getType() == Type.INT96) {
+          Statistics stats = chunk.getMeta_data().getStatistics();
+          assertTrue(stats != null && stats.isSetMin_value());
+          assertArrayEquals(EXPECTED_MIN.getBytes(), stats.getMin_value());
+          assertArrayEquals(EXPECTED_MAX.getBytes(), stats.getMax_value());
+        }
+      }
+    }
+
+    // Column index should be present for both columns.

Review Comment:
   Changed to `Column index should be present for the INT96 column`



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)
+      throws IOException {
+    byte[] bytes = Files.readAllBytes(src.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    File dst = new File(tmp.getRoot(), name);
+    try (FileOutputStream out = new FileOutputStream(dst)) {
+      out.write(bytes, 0, footerStart);
+      ByteArrayOutputStream serialized = new ByteArrayOutputStream();
+      Util.writeFileMetaData(footer, serialized);
+      out.write(serialized.toByteArray());
+      out.write(ByteBuffer.allocate(4)
+          .order(ByteOrder.LITTLE_ENDIAN)
+          .putInt(serialized.size())
+          .array());
+      out.write(ParquetFileWriter.MAGIC);
+    }
+    return dst;
+  }
+
+  /**
+   * Retags the INT96 column orders in the footer as TYPE_ORDER while leaving 
the (already written)
+   * min/max statistics in place. This simulates a legacy writer that emitted 
INT96 stats under
+   * TYPE_ORDER before INT96_TIMESTAMP_ORDER existed; such stats must be 
ignored by the reader.
+   */
+  private static void downgradeInt96ToTypeOrder(FileMetaData footer) {

Review Comment:
   Removed this helper and added both 
`testReaderIgnoresInt96StatsWithTypeDefinedOrder` and 
`testReaderIgnoresInt96StatsWhenColumnOrdersAbsent`



##########
parquet-hadoop/src/test/java/org/apache/parquet/statistics/TestInt96TimestampStatistics.java:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.parquet.statistics;
+
+import static org.apache.parquet.schema.MessageTypeParser.parseMessageType;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.util.List;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.HadoopReadOptions;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.format.ColumnChunk;
+import org.apache.parquet.format.FileMetaData;
+import org.apache.parquet.format.RowGroup;
+import org.apache.parquet.format.Statistics;
+import org.apache.parquet.format.Type;
+import org.apache.parquet.format.TypeDefinedOrder;
+import org.apache.parquet.format.Util;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetFileWriter;
+import org.apache.parquet.hadoop.ParquetReader;
+import org.apache.parquet.hadoop.ParquetWriter;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.example.GroupWriteSupport;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.internal.column.columnindex.ColumnIndex;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.ColumnOrder;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/**
+ * Tests for INT96 timestamp statistics support (INT96_TIMESTAMP_ORDER).
+ */
+public class TestInt96TimestampStatistics {
+
+  private static final MessageType SCHEMA =
+      parseMessageType("message test { required int96 ts; required int64 id; } 
");
+
+  // Chronologically: EARLY < SAME_DAY_EARLY < LATE_IN_DAY < NEXT_DAY.
+  // Byte-wise lexicographic comparison would order these incorrectly (nanos 
bytes come first),
+  // so these values detect a reader/writer using the wrong order.
+  private static final Binary EARLY = int96(2440000, 123L); // 1968-05-23 
00:00:00.000000123
+  private static final Binary SAME_DAY_EARLY = int96(2440588, 1_000L); // 
1970-01-01 00:00:00.000001
+  private static final Binary LATE_IN_DAY = int96(2440588, 
86_399_999_999_999L); // 1970-01-01 23:59:59.999...
+  private static final Binary NEXT_DAY = int96(2440589, 0L); // 1970-01-02 
00:00:00
+
+  private static final List<Binary> VALUES = List.of(LATE_IN_DAY, NEXT_DAY, 
EARLY, SAME_DAY_EARLY);
+  private static final Binary EXPECTED_MIN = EARLY;
+  private static final Binary EXPECTED_MAX = NEXT_DAY;
+
+  @Rule
+  public TemporaryFolder tmp = new TemporaryFolder();
+
+  private static Binary int96(int julianDay, long nanosOfDay) {
+    return Binary.fromConstantByteArray(ByteBuffer.allocate(12)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .putLong(nanosOfDay)
+        .putInt(julianDay)
+        .array());
+  }
+
+  private File writeFile() throws IOException {
+    File file = new File(tmp.getRoot(), "int96.parquet");
+    Configuration conf = new Configuration();
+    GroupWriteSupport.setSchema(SCHEMA, conf);
+    SimpleGroupFactory factory = new SimpleGroupFactory(SCHEMA);
+    ParquetWriter<Group> writer = ExampleParquetWriter.builder(new 
Path(file.getAbsolutePath()))
+        .withConf(conf)
+        .build();
+    try {
+      for (int i = 0; i < VALUES.size(); i++) {
+        writer.write(factory.newGroup().append("ts", 
VALUES.get(i)).append("id", (long) i));
+      }
+    } finally {
+      writer.close();
+    }
+    return file;
+  }
+
+  private static ParquetMetadata readFooter(File file, Configuration conf) 
throws IOException {
+    Path path = new Path(file.getAbsolutePath());
+    try (ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf),
+        HadoopReadOptions.builder(conf, path).build())) {
+      return reader.getFooter();
+    }
+  }
+
+  private static FileMetaData readRawFooter(File file) throws IOException {
+    byte[] bytes = Files.readAllBytes(file.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    return Util.readFileMetaData(new ByteArrayInputStream(bytes, footerStart, 
footerLen));
+  }
+
+  /** Rewrites the footer of src into a new file, keeping all data pages 
byte-identical. */
+  private File rewriteFooter(File src, FileMetaData footer, String name)
+      throws IOException {
+    byte[] bytes = Files.readAllBytes(src.toPath());
+    int footerLen = ByteBuffer.wrap(bytes, bytes.length - 8, 4)
+        .order(ByteOrder.LITTLE_ENDIAN)
+        .getInt();
+    int footerStart = bytes.length - 8 - footerLen;
+    File dst = new File(tmp.getRoot(), name);
+    try (FileOutputStream out = new FileOutputStream(dst)) {
+      out.write(bytes, 0, footerStart);
+      ByteArrayOutputStream serialized = new ByteArrayOutputStream();
+      Util.writeFileMetaData(footer, serialized);
+      out.write(serialized.toByteArray());
+      out.write(ByteBuffer.allocate(4)
+          .order(ByteOrder.LITTLE_ENDIAN)
+          .putInt(serialized.size())
+          .array());
+      out.write(ParquetFileWriter.MAGIC);
+    }
+    return dst;
+  }
+
+  /**
+   * Retags the INT96 column orders in the footer as TYPE_ORDER while leaving 
the (already written)
+   * min/max statistics in place. This simulates a legacy writer that emitted 
INT96 stats under
+   * TYPE_ORDER before INT96_TIMESTAMP_ORDER existed; such stats must be 
ignored by the reader.
+   */
+  private static void downgradeInt96ToTypeOrder(FileMetaData footer) {
+    for (org.apache.parquet.format.ColumnOrder columnOrder : 
footer.getColumn_orders()) {
+      if (columnOrder.isSetINT96_TIMESTAMP_ORDER()) {
+        columnOrder.setTYPE_ORDER(new TypeDefinedOrder());
+      }
+    }
+  }
+
+  private static ColumnChunkMetaData getColumn(ParquetMetadata footer, String 
name) {
+    BlockMetaData block = footer.getBlocks().get(0);
+    return block.getColumns().stream()
+        .filter(c -> c.getPath().toDotString().equals(name))
+        .findFirst()
+        .orElseThrow(() -> new IllegalArgumentException("no column " + name));
+  }
+
+  private static void assertStatsIgnored(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() == null || 
!column.getStatistics().hasNonNullValue());
+  }
+
+  private static void assertStatsUsable(ColumnChunkMetaData column) {
+    assertTrue(column.getStatistics() != null && 
column.getStatistics().hasNonNullValue());
+    assertArrayEquals(EXPECTED_MIN.getBytes(), 
column.getStatistics().getMinBytes());
+    assertArrayEquals(EXPECTED_MAX.getBytes(), 
column.getStatistics().getMaxBytes());
+  }
+
+  @Test
+  public void testWriterEmitsInt96StatsAndColumnOrder() throws IOException {
+    // Values are written in non-chronological order; the writer must still 
produce the
+    // chronological min/max, not first/last or byte-wise extremes.
+    File file = writeFile();
+    FileMetaData rawFooter = readRawFooter(file);
+    // schema[0] is the message root; column_orders are indexed by leaf order: 
ts=0, id=1
+    
assertTrue(rawFooter.getColumn_orders().get(0).isSetINT96_TIMESTAMP_ORDER());
+    assertTrue(rawFooter.getColumn_orders().get(1).isSetTYPE_ORDER());
+
+    for (RowGroup rowGroup : rawFooter.getRow_groups()) {
+      for (ColumnChunk chunk : rowGroup.getColumns()) {
+        if (chunk.getMeta_data().getType() == Type.INT96) {
+          Statistics stats = chunk.getMeta_data().getStatistics();
+          assertTrue(stats != null && stats.isSetMin_value());
+          assertArrayEquals(EXPECTED_MIN.getBytes(), stats.getMin_value());
+          assertArrayEquals(EXPECTED_MAX.getBytes(), stats.getMax_value());
+        }
+      }
+    }
+
+    // Column index should be present for both columns.
+    Configuration conf = new Configuration();
+    Path path = new Path(file.getAbsolutePath());
+    try (
+      ParquetFileReader reader = ParquetFileReader.open(
+        HadoopInputFile.fromPath(path, conf), HadoopReadOptions.builder(conf, 
path).build()
+      )
+    ) {
+      assertNotNull(reader.readColumnIndex(getColumn(reader.getFooter(), 
"id")));
+
+      ColumnIndex columnIndex = 
reader.readColumnIndex(getColumn(reader.getFooter(), "ts"));
+      assertNotNull(columnIndex);
+      assertArrayEquals(EXPECTED_MIN.getBytes(), 
toArray(columnIndex.getMinValues().get(0)));
+      assertArrayEquals(EXPECTED_MAX.getBytes(),
+        
toArray(columnIndex.getMaxValues().get(columnIndex.getMaxValues().size() - 1)));

Review Comment:
   Changed to `get(0)`



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