Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,16 @@

import org.apache.xtable.collectors.CustomCollectors;
import org.apache.xtable.exception.NotSupportedException;
import org.apache.xtable.exception.PartitionValuesExtractorException;
import org.apache.xtable.exception.ReadException;
import org.apache.xtable.model.InternalTable;
import org.apache.xtable.model.exception.ParseException;
import org.apache.xtable.model.schema.InternalField;
import org.apache.xtable.model.schema.InternalPartitionField;
import org.apache.xtable.model.schema.InternalSchema;
import org.apache.xtable.model.schema.InternalType;
import org.apache.xtable.model.schema.PartitionTransformType;
import org.apache.xtable.model.stat.ColumnStat;
import org.apache.xtable.model.stat.PartitionValue;
import org.apache.xtable.model.storage.FileFormat;
import org.apache.xtable.model.storage.InternalDataFile;
Expand Down Expand Up @@ -166,9 +172,7 @@ public InternalFilesDiff getDiffForCommit(

Stream<InternalDataFile> filesAddedWithoutStats = allInfo.getAdded().stream();
List<InternalDataFile> filesAdded =
fileStatsExtractor
.addStatsToFiles(tableMetadata, filesAddedWithoutStats, table.getReadSchema())
.collect(Collectors.toList());
withStats(filesAddedWithoutStats, table.getReadSchema()).collect(Collectors.toList());
List<InternalDataFile> filesRemoved = allInfo.getRemoved();

return InternalFilesDiff.builder().filesAdded(filesAdded).filesRemoved(filesRemoved).build();
Expand Down Expand Up @@ -223,8 +227,7 @@ public InternalFilesDiff getDiffFromCommitMetadata(
}
});
List<InternalDataFile> filesAdded =
fileStatsExtractor
.addStatsToFiles(tableMetadata, filesAddedWithoutStats.stream(), table.getReadSchema())
withStats(filesAddedWithoutStats.stream(), table.getReadSchema())
.collect(Collectors.toList());
return InternalFilesDiff.builder().filesAdded(filesAdded).filesRemoved(filesToRemove).build();
}
Expand Down Expand Up @@ -293,8 +296,7 @@ public InternalFilesDiff getDiffFromRollbackMetadata(
filesAddedWithoutStats.add(buildFileWithoutStats(partitionValues, baseFile)));
});
List<InternalDataFile> filesAdded =
fileStatsExtractor
.addStatsToFiles(tableMetadata, filesAddedWithoutStats.stream(), table.getReadSchema())
withStats(filesAddedWithoutStats.stream(), table.getReadSchema())
.collect(Collectors.toList());
return InternalFilesDiff.builder().filesAdded(filesAdded).filesRemoved(filesToRemove).build();
}
Expand Down Expand Up @@ -425,8 +427,7 @@ public InternalFilesDiff getDiffFromReplaceCommitMetadata(
.collect(Collectors.toList()));
});
List<InternalDataFile> filesAdded =
fileStatsExtractor
.addStatsToFiles(tableMetadata, filesAddedWithoutStats.stream(), table.getReadSchema())
withStats(filesAddedWithoutStats.stream(), table.getReadSchema())
.collect(Collectors.toList());
return InternalFilesDiff.builder().filesAdded(filesAdded).filesRemoved(filesToRemove).build();
}
Expand Down Expand Up @@ -724,8 +725,7 @@ private List<PartitionFileGroup> getInternalDataFilesForPartitions(
.getLatestBaseFiles(partitionPath)
.map(baseFile -> buildFileWithoutStats(partitionValues, baseFile));
});
Stream<InternalDataFile> files =
fileStatsExtractor.addStatsToFiles(tableMetadata, filesWithoutStats, table.getReadSchema());
Stream<InternalDataFile> files = withStats(filesWithoutStats, table.getReadSchema());
return PartitionFileGroup.fromFiles(files);
}

Expand All @@ -750,6 +750,93 @@ private static class AddedAndRemovedFiles {
List<InternalDataFile> removed;
}

private Stream<InternalDataFile> withStats(
Stream<InternalDataFile> files, InternalSchema schema) {
return fileStatsExtractor
.addStatsToFiles(tableMetadata, files, schema)
.map(HudiDataFileExtractor::requireTimestampPartitionValuesMatchStats);
}

/**
* A partition value parsed from the path is the value of every row of the file only when the path
* holds the value itself. Hudi's SQL key generator writes a TIMESTAMP partition path truncated to
* whole seconds, so there the path is a one-second bucket: rows whose values differ below the
* second share a path and a file group. A target that fills an identity partition column from the
* partition value, as Iceberg and Delta readers do, would read every row of the file as the
* truncated value, and prune filters on the column by it.
*
* <p>No single partition value is right for a file holding several values, and a value taken from
* the column stats would differ from the one the file is later removed under, which is parsed
* from the path again. So the path value is kept, and a file whose column stats show any other
* value for a timestamp partition column is refused.
*
* <p>A file without stats for the column is kept, since nothing shows it holds another value.
*
* @throws PartitionValuesExtractorException when the column stats of a timestamp partition column
* of the file show a value other than its partition value
*/
static InternalDataFile requireTimestampPartitionValuesMatchStats(InternalDataFile file) {
for (PartitionValue partitionValue : file.getPartitionValues()) {
InternalPartitionField partitionField = partitionValue.getPartitionField();
InternalField sourceField = partitionField.getSourceField();
InternalType type = sourceField.getSchema().getDataType();
Object value = partitionValue.getRange().getMinValue();
if (partitionField.getTransformType() != PartitionTransformType.VALUE
|| (type != InternalType.TIMESTAMP && type != InternalType.TIMESTAMP_NTZ)
|| value == null) {
continue;
}
Optional<ColumnStat> stat =
file.getColumnStats().stream()
.filter(
s -> s.getField() != null && sourceField.getPath().equals(s.getField().getPath()))
.findFirst();
Object min = stat.map(s -> s.getRange().getMinValue()).orElse(null);
Object max = stat.map(s -> s.getRange().getMaxValue()).orElse(null);
if (min == null && max == null) {
// The column is outside the indexed columns, or the file stores no stats for it.
continue;
}
if (!value.equals(min) || !value.equals(max)) {
throw new PartitionValuesExtractorException(
String.format(
"Data file %s holds values of TIMESTAMP partition column %s from %s to %s, but its"
+ " partition path records %s. Hudi writes a timestamp partition path"
+ " truncated to whole seconds, so values with fractional seconds, or"
+ " several values in one file, cannot be published as a partition value."
+ " Partition by a column holding whole seconds or a coarser value instead",
file.getPhysicalPath(),
sourceField.getPath(),
render(min, sourceField),
render(max, sourceField),
render(value, sourceField)));
}
}
return file;
}

private static String render(Object timestamp, InternalField field) {
if (!(timestamp instanceof Long)) {
return String.valueOf(timestamp);
}
long value = (Long) timestamp;
Object precision =
field.getSchema().getMetadata() == null
? null
: field.getSchema().getMetadata().get(InternalSchema.MetadataKey.TIMESTAMP_PRECISION);
java.time.Instant instant =
precision == InternalSchema.MetadataValue.MILLIS
? java.time.Instant.ofEpochMilli(value)
: precision == InternalSchema.MetadataValue.NANOS
? java.time.Instant.ofEpochSecond(0, value)
: java.time.Instant.ofEpochSecond(
Math.floorDiv(value, 1_000_000L), Math.floorMod(value, 1_000_000L) * 1_000L);
String rendered = instant.toString();
return field.getSchema().getDataType() == InternalType.TIMESTAMP_NTZ
? rendered.substring(0, rendered.length() - 1)
: rendered;
}

/**
* Builds a {@link InternalDataFile} without any statistics or rowCount value set.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,33 @@
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.Value;

import org.apache.hudi.common.util.PartitionPathEncodeUtils;

import org.apache.xtable.exception.PartitionValuesExtractorException;
import org.apache.xtable.model.schema.InternalPartitionField;
import org.apache.xtable.model.schema.InternalSchema;
import org.apache.xtable.model.schema.InternalType;
import org.apache.xtable.model.stat.PartitionValue;
import org.apache.xtable.model.stat.Range;
Expand All @@ -42,6 +57,16 @@
@AllArgsConstructor
public class PathBasedPartitionValuesExtractor {
private static final String HIVE_DEFAULT_PARTITION = "__HIVE_DEFAULT_PARTITION__";
private static final Pattern INTEGRAL_VALUE = Pattern.compile("-?\\d+");
private static final DateTimeFormatter TIMESTAMP_FORMATTER =
new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendPattern("[' ']['T']")
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.toFormatter();
@NonNull protected final Map<String, String> pathToPartitionFieldFormat;

public List<PartitionValue> extractPartitionValues(
Expand Down Expand Up @@ -95,8 +120,7 @@ private PartialResult parsePartitionPath(
// this case is possible if user is directly relying on directly _hoodie_partition_path due
// to custom partitioning logic
boolean isSlashDelimited = totalNumberOfPartitions > 1;
return parseValue(
remainingPath, field.getSourceField().getSchema().getDataType(), isSlashDelimited);
return parseValue(remainingPath, field.getSourceField().getSchema(), isSlashDelimited);
default:
throw new IllegalArgumentException(
"Unexpected partition type: " + field.getTransformType());
Expand All @@ -119,7 +143,7 @@ protected static PartialResult parseDate(String remainingPath, String format) {
}

protected static PartialResult parseValue(
String remainingPath, InternalType sourceFieldType, boolean isSlashDelimited) {
String remainingPath, InternalSchema sourceFieldSchema, boolean isSlashDelimited) {
if (remainingPath.isEmpty()) {
throw new PartitionValuesExtractorException("Missing partition value");
}
Expand All @@ -134,19 +158,24 @@ protected static PartialResult parseValue(
String unParsedPath =
remainingPath.substring(Math.min(endCharIndex + 1, remainingPath.length()));
Object parsedValue;
InternalType sourceFieldType = sourceFieldSchema.getDataType();
switch (sourceFieldType) {
case STRING:
case ENUM:
parsedValue = valueAsString;
break;
case INT:
case DATE:
parsedValue = Integer.parseInt(valueAsString);
break;
case DATE:
parsedValue = parseDateValue(valueAsString);
break;
case LONG:
parsedValue = Long.parseLong(valueAsString);
break;
case TIMESTAMP:
case TIMESTAMP_NTZ:
parsedValue = Long.parseLong(valueAsString);
parsedValue = parseTimestampValue(valueAsString, sourceFieldSchema);
break;
case DOUBLE:
parsedValue = Double.parseDouble(valueAsString);
Expand All @@ -172,6 +201,60 @@ protected static PartialResult parseValue(
return new PartialResult(parsedValue, unParsedPath);
}

/** Days since epoch, from either a number of days or an ISO date such as 2024-02-29. */
private static int parseDateValue(String value) {
if (INTEGRAL_VALUE.matcher(value).matches()) {
return Integer.parseInt(value);
}
try {
return (int) LocalDate.parse(value).toEpochDay();
} catch (DateTimeParseException ex) {
throw new PartitionValuesExtractorException("Unable to parse date from path: " + value, ex);
}
}

/**
* Time since epoch in the field's timestamp precision, from either a number in that precision or
* a date and time such as 2024-02-29 10:30:00, which may be path escaped and carry an offset.
*/
private static long parseTimestampValue(String value, InternalSchema fieldSchema) {
if (INTEGRAL_VALUE.matcher(value).matches()) {
return Long.parseLong(value);
}
String unescaped = PartitionPathEncodeUtils.unescapePathName(value);
Instant instant;
try {
TemporalAccessor parsed =
TIMESTAMP_FORMATTER.parseBest(unescaped, OffsetDateTime::from, LocalDateTime::from);
if (parsed instanceof OffsetDateTime) {
instant = ((OffsetDateTime) parsed).toInstant();
} else {
// Hudi's SQL key generator writes a timestamp as wall-clock time in the writer JVM's
// default time zone, while a timestamp without time zone has no zone to apply.
ZoneId zone =
fieldSchema.getDataType() == InternalType.TIMESTAMP_NTZ
? ZoneOffset.UTC
: ZoneId.systemDefault();
instant = ((LocalDateTime) parsed).atZone(zone).toInstant();
}
} catch (DateTimeParseException ex) {
throw new PartitionValuesExtractorException(
"Unable to parse timestamp from path: " + value, ex);
}
Object precision =
fieldSchema.getMetadata() == null
? null
: fieldSchema.getMetadata().get(InternalSchema.MetadataKey.TIMESTAMP_PRECISION);
if (precision == InternalSchema.MetadataValue.MILLIS) {
return instant.toEpochMilli();
}
if (precision == InternalSchema.MetadataValue.NANOS) {
return TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano();
}
return TimeUnit.SECONDS.toMicros(instant.getEpochSecond())
+ TimeUnit.NANOSECONDS.toMicros(instant.getNano());
}

@Value
protected static class PartialResult {
Object value;
Expand Down
Loading