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

the-other-tim-brown pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-xtable.git


The following commit(s) were added to refs/heads/main by this push:
     new ed4be71f [1017] Write Delta Kernel timestamp stats in micros for 
millisecond columns (#1018)
ed4be71f is described below

commit ed4be71f9f29dd0f1f1d179f97096d63c10e50bb
Author: Neeraj <[email protected]>
AuthorDate: Sat Nov 28 21:36:39 2026 +0530

    [1017] Write Delta Kernel timestamp stats in micros for millisecond columns 
(#1018)
    
    * [1017] Write Delta Kernel timestamp stats in micros for millisecond 
columns
    
    XTable stores TIMESTAMP and TIMESTAMP_NTZ column stats as millis or
    micros since epoch, depending on the field's TIMESTAMP_PRECISION.
    DeltaKernelDataFileUpdatesExtractor passed the value to Kernel's
    timestamp literals, which take micros, without checking the precision.
    For a millisecond column, such as a Hudi timestamp-millis field, the
    Kernel target wrote min and max 1000 times too small, in January 1970.
    Delta readers skip files with these stats, so a filter on the column
    returned no rows. The Standalone target already converts by precision.
    Convert millis to micros before building the literal.
    
    Fixes #1017
    
    * [1017] Move the Kernel target timestamp round trip into 
ITConversionController
    
    * [1017] Use long literals for ColumnStat counts in the new tests
    
    So the tests also compile once #1012 makes numNulls Long.
    
    * [1017] Filter on the millis timestamp in the Kernel target IT and share 
one ObjectMapper
    
    Check the timestamp-millis filter in testVariousOperationsDeltaKernelTarget
    instead of a separate IT, and use one ObjectMapper for the test class.
---
 .../DeltaKernelDataFileUpdatesExtractor.java       |  23 +++-
 .../org/apache/xtable/ITConversionController.java  |  10 ++
 .../TestDeltaKernelDataFileUpdatesExtractor.java   | 134 ++++++++++++++++++++-
 3 files changed, 160 insertions(+), 7 deletions(-)

diff --git 
a/xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileUpdatesExtractor.java
 
b/xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileUpdatesExtractor.java
index 8c641e2b..9a2dd48d 100644
--- 
a/xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileUpdatesExtractor.java
+++ 
b/xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileUpdatesExtractor.java
@@ -24,6 +24,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 import java.util.stream.Stream;
 
 import lombok.Builder;
@@ -315,11 +316,9 @@ public class DeltaKernelDataFileUpdatesExtractor {
         // XTable stores dates as days since epoch (int)
         return Literal.ofDate(((Number) value).intValue());
       case TIMESTAMP:
-        // XTable stores timestamps as microseconds since epoch
-        return Literal.ofTimestamp(((Number) value).longValue());
+        return Literal.ofTimestamp(toEpochMicros(value, fieldSchema));
       case TIMESTAMP_NTZ:
-        // XTable stores timestamp_ntz as microseconds since epoch
-        return Literal.ofTimestampNtz(((Number) value).longValue());
+        return Literal.ofTimestampNtz(toEpochMicros(value, fieldSchema));
       case DECIMAL:
         // Extract precision and scale from schema metadata
         Map<InternalSchema.MetadataKey, Object> metadata = 
fieldSchema.getMetadata();
@@ -344,6 +343,22 @@ public class DeltaKernelDataFileUpdatesExtractor {
     }
   }
 
+  /**
+   * Returns a timestamp stat as micros since epoch, which is what Kernel's 
timestamp literals take.
+   * XTable stores timestamp stats as millis or micros since epoch, depending 
on the field's {@link
+   * InternalSchema.MetadataKey#TIMESTAMP_PRECISION}.
+   */
+  private static long toEpochMicros(Object value, InternalSchema fieldSchema) {
+    long timestamp = ((Number) value).longValue();
+    Map<InternalSchema.MetadataKey, Object> metadata = 
fieldSchema.getMetadata();
+    if (metadata != null
+        && metadata.get(InternalSchema.MetadataKey.TIMESTAMP_PRECISION)
+            == InternalSchema.MetadataValue.MILLIS) {
+      return TimeUnit.MILLISECONDS.toMicros(timestamp);
+    }
+    return timestamp;
+  }
+
   private MapValue convertToMapValue(Map<String, String> map) {
     return VectorUtils.stringStringMapValue(map);
   }
diff --git 
a/xtable-core/src/test/java/org/apache/xtable/ITConversionController.java 
b/xtable-core/src/test/java/org/apache/xtable/ITConversionController.java
index 1c4e2f79..ee06fa44 100644
--- a/xtable-core/src/test/java/org/apache/xtable/ITConversionController.java
+++ b/xtable-core/src/test/java/org/apache/xtable/ITConversionController.java
@@ -369,6 +369,16 @@ public class ITConversionController {
       checkDatasetEquivalence(HUDI, table, targetTableFormats, 130);
       checkDatasetEquivalenceWithFilter(
           HUDI, table, targetTableFormats, table.getFilterQuery(), 
Collections.emptyMap());
+      // Delta readers skip files by the min and max stats in the Delta log, 
so a filter on a
+      // timestamp-millis column drops rows if the target writes its stats in 
the wrong unit.
+      checkDatasetEquivalenceWithFilter(
+          HUDI,
+          table,
+          targetTableFormats,
+          String.format(
+              "timestamp_millis_nullable_field >= timestamp_millis(%d)",
+              Instant.now().truncatedTo(ChronoUnit.DAYS).minus(2, 
ChronoUnit.DAYS).toEpochMilli()),
+          Collections.emptyMap());
     }
 
     try (GenericTable tableWithUpdatedSchema =
diff --git 
a/xtable-core/src/test/java/org/apache/xtable/kernel/TestDeltaKernelDataFileUpdatesExtractor.java
 
b/xtable-core/src/test/java/org/apache/xtable/kernel/TestDeltaKernelDataFileUpdatesExtractor.java
index 809f9579..4801b604 100644
--- 
a/xtable-core/src/test/java/org/apache/xtable/kernel/TestDeltaKernelDataFileUpdatesExtractor.java
+++ 
b/xtable-core/src/test/java/org/apache/xtable/kernel/TestDeltaKernelDataFileUpdatesExtractor.java
@@ -18,6 +18,8 @@
  
 package org.apache.xtable.kernel;
 
+import static 
org.apache.xtable.model.schema.InternalSchema.MetadataValue.MICROS;
+import static 
org.apache.xtable.model.schema.InternalSchema.MetadataValue.MILLIS;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -29,6 +31,7 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.time.Instant;
+import java.time.temporal.ChronoUnit;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
@@ -41,6 +44,7 @@ import org.junit.jupiter.api.io.TempDir;
 
 import scala.collection.JavaConverters;
 
+import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
 import io.delta.kernel.Table;
@@ -55,6 +59,8 @@ import io.delta.kernel.types.StringType;
 import io.delta.kernel.types.StructField;
 import io.delta.kernel.types.StructType;
 
+import org.apache.xtable.delta.DeltaStatsExtractor;
+import org.apache.xtable.delta.DeltaValueConverter;
 import org.apache.xtable.model.schema.InternalField;
 import org.apache.xtable.model.schema.InternalPartitionField;
 import org.apache.xtable.model.schema.InternalSchema;
@@ -68,6 +74,7 @@ import org.apache.xtable.model.storage.InternalFilesDiff;
 import org.apache.xtable.model.storage.PartitionFileGroup;
 
 public class TestDeltaKernelDataFileUpdatesExtractor {
+  private static final ObjectMapper MAPPER = new ObjectMapper();
 
   @TempDir private Path tempDir;
 
@@ -238,14 +245,13 @@ public class TestDeltaKernelDataFileUpdatesExtractor {
     // id keeps its bounds, and its unknown null count is left out instead of 
written as 0. Kernel
     // does not write null values in the stats maps.
     AddFile addFile = (AddFile) actions.get(0);
-    ObjectMapper mapper = new ObjectMapper();
     assertEquals(
-        mapper.readTree(
+        MAPPER.readTree(
             "{\"numRecords\":10,"
                 + "\"minValues\":{\"id\":1,\"name\":\"a\"},"
                 + "\"maxValues\":{\"id\":9,\"name\":\"z\"},"
                 + "\"nullCount\":{\"name\":2}}"),
-        mapper.readTree(addFile.getStatsJson().get()));
+        MAPPER.readTree(addFile.getStatsJson().get()));
   }
 
   @Test
@@ -458,6 +464,128 @@ public class TestDeltaKernelDataFileUpdatesExtractor {
     // Note: file2 should not appear in actions as it's unchanged
   }
 
+  @Test
+  public void testTimestampStatsUseFieldPrecision() throws IOException {
+    // Range stores TIMESTAMP and TIMESTAMP_NTZ stats as millis or micros, 
depending on the field's
+    // TIMESTAMP_PRECISION. Sources with millisecond timestamps (Hudi, Paimon, 
Parquet) send millis.
+    Instant min = Instant.parse("2024-03-15T10:20:30Z");
+    Instant max = Instant.parse("2024-03-16T11:22:33Z");
+    InternalField tsMillis = timestampField("ts_millis", 
InternalType.TIMESTAMP, MILLIS);
+    InternalField tsMicros = timestampField("ts_micros", 
InternalType.TIMESTAMP, MICROS);
+    InternalField ntzMillis = timestampField("ntz_millis", 
InternalType.TIMESTAMP_NTZ, MILLIS);
+    InternalField ntzMicros = timestampField("ntz_micros", 
InternalType.TIMESTAMP_NTZ, MICROS);
+    InternalSchema schema =
+        InternalSchema.builder()
+            .name("record")
+            .dataType(InternalType.RECORD)
+            .fields(Arrays.asList(tsMillis, tsMicros, ntzMillis, ntzMicros))
+            .build();
+    List<ColumnStat> columnStats =
+        Arrays.asList(
+            millisStat(tsMillis, min, max),
+            microsStat(tsMicros, min, max),
+            millisStat(ntzMillis, min, max),
+            microsStat(ntzMicros, min, max));
+
+    Path dataFilePath = tempDir.resolve("ts_data.parquet");
+    Files.createFile(dataFilePath);
+    InternalDataFile dataFile =
+        InternalDataFile.builder()
+            .physicalPath(dataFilePath.toString())
+            .fileSizeBytes(1024L)
+            .lastModified(Instant.now().toEpochMilli())
+            .recordCount(10L)
+            .partitionValues(Collections.emptyList())
+            .columnStats(columnStats)
+            .build();
+    DeltaKernelDataFileUpdatesExtractor statsExtractor =
+        DeltaKernelDataFileUpdatesExtractor.builder()
+            .engine(engine)
+            .basePath(tempDir.toString())
+            .includeColumnStats(true)
+            .build();
+    Table table = Table.forPath(engine, 
tempDir.resolve("new_table").toString());
+
+    List<RowBackedAction> actions =
+        JavaConverters.seqAsJavaList(
+            statsExtractor.applySnapshot(
+                table,
+                Collections.singletonList(
+                    PartitionFileGroup.builder()
+                        .files(Collections.singletonList(dataFile))
+                        .partitionValues(Collections.emptyList())
+                        .build()),
+                schema,
+                null));
+    assertEquals(1, actions.size());
+    JsonNode kernelStats = MAPPER.readTree(((AddFile) 
actions.get(0)).getStatsJson().get());
+    JsonNode standaloneStats =
+        MAPPER.readTree(
+            
DeltaStatsExtractor.getInstance().convertStatsToDeltaFormat(schema, 10L, 
columnStats));
+
+    for (InternalField field : schema.getFields()) {
+      for (String bound : Arrays.asList("minValues", "maxValues")) {
+        Instant expected = bound.equals("minValues") ? min : max;
+        String kernelValue = 
kernelStats.get(bound).get(field.getName()).asText();
+        String standaloneValue = 
standaloneStats.get(bound).get(field.getName()).asText();
+        assertEquals(
+            expected,
+            readStatAsInstant(kernelValue, field),
+            String.format("Kernel %s.%s was %s", bound, field.getName(), 
kernelValue));
+        assertEquals(
+            expected,
+            readStatAsInstant(standaloneValue, field),
+            String.format("Standalone %s.%s was %s", bound, field.getName(), 
standaloneValue));
+      }
+    }
+  }
+
+  private static InternalField timestampField(
+      String name, InternalType type, InternalSchema.MetadataValue precision) {
+    return InternalField.builder()
+        .name(name)
+        .schema(
+            InternalSchema.builder()
+                .name(type == InternalType.TIMESTAMP ? "timestamp" : 
"timestamp_ntz")
+                .dataType(type)
+                .isNullable(true)
+                .metadata(
+                    Collections.singletonMap(
+                        InternalSchema.MetadataKey.TIMESTAMP_PRECISION, 
precision))
+                .build())
+        .build();
+  }
+
+  private static ColumnStat millisStat(InternalField field, Instant min, 
Instant max) {
+    return ColumnStat.builder()
+        .field(field)
+        .range(Range.vector(min.toEpochMilli(), max.toEpochMilli()))
+        .numNulls(0L)
+        .numValues(10)
+        .build();
+  }
+
+  private static ColumnStat microsStat(InternalField field, Instant min, 
Instant max) {
+    return ColumnStat.builder()
+        .field(field)
+        .range(Range.vector(min.toEpochMilli() * 1000, max.toEpochMilli() * 
1000))
+        .numNulls(0L)
+        .numValues(10)
+        .build();
+  }
+
+  /** Reads a Delta timestamp stat back the way the Delta sources do, as 
micros in UTC. */
+  private static Instant readStatAsInstant(String statValue, InternalField 
field) {
+    InternalSchema microsSchema =
+        field.getSchema().toBuilder()
+            .metadata(
+                
Collections.singletonMap(InternalSchema.MetadataKey.TIMESTAMP_PRECISION, 
MICROS))
+            .build();
+    long micros =
+        (long) DeltaValueConverter.convertFromDeltaColumnStatValue(statValue, 
microsSchema);
+    return Instant.EPOCH.plus(micros, ChronoUnit.MICROS);
+  }
+
   private Table createSimpleDeltaTable() {
     try {
       // Create a simple Delta table directory structure

Reply via email to