You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by da...@apache.org on 2026/08/19 04:31:09 UTC
(hudi) branch master updated: feat(writer): add hoodie.meta.fields.mode for selective meta-field population on CoW tables (#19205)
This is an automated email from the ASF dual-hosted git repository.
danny0405 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hudi.git
The following commit(s) were added to refs/heads/master by this push:
new a5251b31ce4b feat(writer): add hoodie.meta.fields.mode for selective meta-field population on CoW tables (#19205)
a5251b31ce4b is described below
commit a5251b31ce4bf45d29f5fcf826ba2bb458807cf5
Author: Sivabalan Narayanan <n....@gmail.com>
AuthorDate: Tue Aug 18 21:31:03 2026 -0700
feat(writer): add hoodie.meta.fields.mode for selective meta-field population on CoW tables (#19205)
* feat(writer): add hoodie.meta.fields.mode for selective meta-field population on CoW tables
Introduces `hoodie.meta.fields.mode` — a comma-separated list of meta columns to populate
when `hoodie.populate.meta.fields=false`. Allowed tokens are `_hoodie_commit_time` and
`_hoodie_file_name`; any other token is rejected up-front. The mode is immutable at runtime
(settable only at table creation, via hudi-cli, or during upgrade).
Motivation: the existing all-or-nothing `populate.meta.fields=false` disables incremental
queries (needs `_hoodie_commit_time`) and file-level pruning / debugging lookups
(needs `_hoodie_file_name`). This lets a table opt into either or both without paying for
the remaining three meta columns.
Resulting modes:
- populate.meta.fields=true → ALL (default; mode list ignored)
- populate.meta.fields=false, mode="" → NONE
- populate.meta.fields=false, mode=<subset> → selective (COMMIT_TIME_ONLY /
FILE_NAME_ONLY / COMMIT_TIME_AND_FILE_NAME)
- populate.meta.fields=true, mode=<subset> → rejected at writer init
Scope in this patch:
- Spark writer path (Avro + Row): HoodieAvroParquetWriter, HoodieSparkParquetWriter,
HoodieRowCreateHandle take a Set<String> meta-fields mode and populate the columns
selectively; bloom filter / record-key index registration stays skipped when record key
is not populated.
- Incremental read path: CoW IncrementalRelationV1/V2 accept the new mode via
isCommitTimePopulated(); MoR incremental relations keep the strict populate=true guard
until the MoR log-write path is updated in a follow-up.
Fail-fast at writer init:
- Unknown token in the mode list (parser throws).
- populate.meta.fields=true combined with a non-empty mode (ambiguous).
- MERGE_ON_READ + non-empty mode (log-write path not yet wired; follow-up).
- Non-Spark engine + non-empty mode (Flink RowData / Java-client not yet wired; follow-up).
Runtime immutability:
- HoodieWriterUtils.validateTableConfig now explicitly rejects a null-on-disk → non-empty
transition on the mode property (existing loop only flagged the mismatch when the on-disk
value was non-null, which let this silent-drop path slip through).
Tests:
- TestHoodieMetaFieldsMode (hudi-hadoop-common) — accessor coverage for every combination
plus unknown-token rejection and whitespace tolerance.
- TestHoodieWriteConfigMetaFieldsMode (hudi-client-common) — builder + validate() coverage.
- TestMetaFieldsMode (hudi-spark) — end-to-end write / re-read for every mode plus the
three rejection paths (populate=true+mode, unknown token, MoR+mode).
* fix(writer): address meta fields mode review comments
* fix(writer): address Azure CI failures
---------
Co-authored-by: danny0405 <yu...@gmail.com>
---
.../org/apache/hudi/cli/commands/SparkMain.java | 36 +-
.../apache/hudi/client/BaseHoodieWriteClient.java | 58 +-
.../hudi/client/timeline/LSMTimelineWriter.java | 3 +-
.../org/apache/hudi/config/HoodieWriteConfig.java | 103 ++-
.../java/org/apache/hudi/io/BaseCreateHandle.java | 27 +-
.../org/apache/hudi/io/HoodieBinaryCopyHandle.java | 3 +
.../org/apache/hudi/io/HoodieWriteMergeHandle.java | 15 +-
.../table/upgrade/NineToTenUpgradeHandler.java | 22 +-
.../table/upgrade/TenToNineDowngradeHandler.java | 111 ++-
.../hudi/client/TestBaseHoodieWriteClient.java | 310 +++++++
.../timeline/TestHoodieTimelineArchiver.java | 41 +
.../TestHoodieWriteConfigMetaFieldsMode.java | 312 +++++++
.../io/TestSortedAndChangeLogMergeHandles.java | 2 +
.../table/upgrade/TestNineToTenUpgradeHandler.java | 86 ++
.../upgrade/TestTenToNineDowngradeHandler.java | 178 +++-
.../hudi/utils/HoodieWriterClientTestHarness.java | 70 +-
.../row/HoodieRowDataFileWriterFactory.java | 9 +-
.../TestHoodieJavaClientOnCopyOnWriteStorage.java | 2 +-
.../hudi/common/model/HoodieSparkRecord.java | 21 +-
.../io/storage/HoodieSparkFileWriterFactory.java | 18 +-
.../hudi/io/storage/HoodieSparkParquetWriter.java | 40 +-
.../hudi/io/storage/row/HoodieRowCreateHandle.java | 52 +-
.../hudi/HoodieDatasetBulkInsertHelper.scala | 7 +-
...erBasedDetectionStrategyWithZKLockProvider.java | 5 +-
.../hudi/io/TestHoodieKeyLocationFetchHandle.java | 5 +-
.../storage/TestHoodieAvroFileWriterFactory.java | 18 +-
.../table/action/cluster/ClusteringTestUtils.java | 4 +-
.../hudi/common/model/HoodieAvroIndexedRecord.java | 8 +-
.../apache/hudi/common/model/MetaFieldsMode.java | 225 +++++
.../hudi/common/table/HoodieTableConfig.java | 75 +-
.../hudi/common/table/HoodieTableMetaClient.java | 49 +-
.../hudi/common/table/TableSchemaResolver.java | 10 +-
.../core/io/storage/HoodieFileBinaryCopier.java | 13 +
.../core/io/storage/HoodieFileWriterFactory.java | 6 +-
.../hudi/common/model/TestMetaFieldsMode.java | 193 +++++
.../TestPositionBasedFileGroupRecordBuffer.java | 2 +-
.../read/lsm/TestHoodieLsmFileGroupReader.java | 2 +-
.../read/lsm/TestLsmFileGroupRecordIterator.java | 2 +-
.../hadoop/HoodieAvroFileWriterFactory.java | 7 +-
.../io/storage/hadoop/HoodieAvroParquetWriter.java | 62 +-
.../parquet/io/HoodieParquetBinaryCopyBase.java | 25 +-
.../hudi/common/table/TestHoodieTableConfig.java | 63 +-
.../table/TestHoodieTableConfigMetaFieldsMode.java | 159 ++++
.../common/table/TestHoodieTableMetaClient.java | 98 +++
.../hudi/metadata/TestHoodieTableMetadataUtil.java | 5 +-
.../apache/hudi/AutoRecordKeyGenerationUtils.scala | 18 +-
.../scala/org/apache/hudi/DataSourceOptions.scala | 9 +-
.../hudi/HoodieHadoopFsRelationFactory.scala | 16 +
.../org/apache/hudi/HoodieSparkSqlWriter.scala | 24 +-
.../scala/org/apache/hudi/HoodieWriterUtils.scala | 32 +-
.../org/apache/hudi/IncrementalRelationV1.scala | 8 +-
.../org/apache/hudi/IncrementalRelationV2.scala | 8 +-
.../hudi/MergeOnReadIncrementalRelationV1.scala | 17 +-
.../hudi/MergeOnReadIncrementalRelationV2.scala | 17 +-
.../sql/catalyst/catalog/HoodieCatalogTable.scala | 2 +-
.../org/apache/hudi/TestHoodieWriterUtils.java | 64 ++
.../apache/hudi/cli/BootstrapExecutorUtils.java | 7 +-
.../TestHoodieDatasetBulkInsertHelper.java | 12 +-
.../hudi/functional/TestMetaFieldsModeE2E.java | 923 +++++++++++++++++++++
...SparkBinaryCopyClusteringAndValidationMeta.java | 75 ++
.../io/storage/row/TestHoodieRowCreateHandle.java | 17 +
.../apache/hudi/HoodieSparkWriterTestBase.scala | 18 +
.../org/apache/hudi/TestHoodieSparkSqlWriter.scala | 26 +-
.../TestHoodieSparkSqlWriterWithTestFormat.scala | 23 +-
.../TestAutoGenerationOfRecordKeys.scala | 5 +-
.../sql/hudi/dml/insert/TestInsertTable2.scala | 7 +-
.../sql/hudi/procedure/TestRepairsProcedure.scala | 1 +
.../plugin/hudi/TestHudiMergeRequiredColumns.java | 2 +-
.../hudi/utilities/HoodieDropPartitionsTool.java | 10 +
.../hudi/utilities/streamer/BootstrapExecutor.java | 7 +-
.../apache/hudi/utilities/streamer/StreamSync.java | 15 +-
.../TestHoodieStreamerMetaFieldsMode.java | 286 +++++++
72 files changed, 4040 insertions(+), 171 deletions(-)
diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java
index cd47dd0cff5e..9f1c94af6026 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java
@@ -558,7 +558,7 @@ public class SparkMain {
* @throws Exception
*/
protected static int upgradeOrDowngradeTable(JavaSparkContext jsc, String basePath, String toVersion) {
- HoodieWriteConfig config = getWriteConfig(basePath, Boolean.parseBoolean(HoodieWriteConfig.ROLLBACK_USING_MARKERS_ENABLE.defaultValue()),
+ HoodieWriteConfig config = getWriteConfig(jsc, basePath, Boolean.parseBoolean(HoodieWriteConfig.ROLLBACK_USING_MARKERS_ENABLE.defaultValue()),
false);
HoodieTableMetaClient metaClient =
HoodieTableMetaClient.builder()
@@ -581,7 +581,7 @@ public class SparkMain {
}
private static SparkRDDWriteClient createHoodieClient(JavaSparkContext jsc, String basePath, Boolean rollbackUsingMarkers, boolean lazyCleanPolicy) throws Exception {
- HoodieWriteConfig config = getWriteConfig(basePath, rollbackUsingMarkers, lazyCleanPolicy);
+ HoodieWriteConfig config = getWriteConfig(jsc, basePath, rollbackUsingMarkers, lazyCleanPolicy);
return new SparkRDDWriteClient(new HoodieSparkEngineContext(jsc), config);
}
@@ -589,12 +589,38 @@ public class SparkMain {
return createHoodieClient(jsc, basePath, Boolean.parseBoolean(HoodieWriteConfig.ROLLBACK_USING_MARKERS_ENABLE.defaultValue()), lazyCleanPolicy);
}
- private static HoodieWriteConfig getWriteConfig(String basePath, Boolean rollbackUsingMarkers, boolean lazyCleanPolicy) {
- return HoodieWriteConfig.newBuilder().withPath(basePath)
+ private static HoodieWriteConfig getWriteConfig(JavaSparkContext jsc, String basePath, Boolean rollbackUsingMarkers, boolean lazyCleanPolicy) {
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder().withPath(basePath)
.withRollbackUsingMarkers(rollbackUsingMarkers)
.withCleanConfig(HoodieCleanConfig.newBuilder().withFailedWritesCleaningPolicy(lazyCleanPolicy ? HoodieFailedWritesCleaningPolicy.LAZY :
HoodieFailedWritesCleaningPolicy.EAGER).build())
- .withIndexConfig(HoodieIndexConfig.newBuilder().withIndexType(HoodieIndex.IndexType.BLOOM).build()).build();
+ .withIndexConfig(HoodieIndexConfig.newBuilder().withIndexType(HoodieIndex.IndexType.BLOOM).build());
+ // Adopt the table's meta-fields mode. These commands take only a base path, so without this the
+ // config resolves to the ALL default and is rejected against any table that is not ALL -- meta
+ // columns are physical, and a writer may not disagree with the table about which of them hold
+ // values. The table is the authority on that, and it is readable right here, so read it.
+ withMetaFieldsModeOf(jsc, basePath, builder);
+ return builder.build();
+ }
+
+ /**
+ * Copy {@code hoodie.meta.fields.mode} from the table at {@code basePath} onto the builder.
+ *
+ * <p>Silent when the table cannot be read: these are maintenance commands, and a base path that is
+ * not yet a Hudi table is the caller's problem to report, not this helper's. In that case the
+ * builder keeps its default and any real mismatch still surfaces at validation.
+ */
+ private static void withMetaFieldsModeOf(JavaSparkContext jsc, String basePath, HoodieWriteConfig.Builder builder) {
+ try {
+ HoodieTableMetaClient metaClient = HoodieTableMetaClient.builder()
+ .setConf(HadoopFSUtils.getStorageConfWithCopy(jsc.hadoopConfiguration()))
+ .setBasePath(basePath)
+ .build();
+ builder.withMetaFieldsMode(metaClient.getTableConfig().getMetaFieldsMode());
+ } catch (Exception e) {
+ log.warn("Could not read the table config at {} to pick up {}; proceeding with the default.",
+ basePath, HoodieTableConfig.META_FIELDS_MODE.key(), e);
+ }
}
private static int archive(JavaSparkContext jsc, int minCommits, int maxCommits, int commitsRetained, boolean enableMetadata, String basePath) {
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java
index 4e0e267391c5..09dc47bee59d 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java
@@ -42,6 +42,7 @@ import org.apache.hudi.common.model.HoodiePreWriteCleanerPolicy;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieTableType;
import org.apache.hudi.common.model.HoodieWriteStat;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.TableServiceType;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.schema.HoodieSchema;
@@ -1543,13 +1544,47 @@ public abstract class BaseHoodieWriteClient<T, I, K, O> extends BaseHoodieClient
return true;
}
+ /**
+ * Pure validation: this method reads both configs and throws, and never modifies either.
+ *
+ * <p>Nothing reconciles the write config against the table beforehand. That is deliberate: the mode
+ * is read further down the write path by handles and writer factories, some of which hold no table
+ * config at all, so the write config has to be correct on its own rather than corrected on the way
+ * in. This gate is what makes that true, by refusing writes whose meta-field settings do not already
+ * agree with the table.
+ */
public void validateAgainstTableProperties(HoodieTableConfig tableConfig, HoodieWriteConfig writeConfig) {
// mismatch of table versions.
CommonClientUtils.validateTableVersion(tableConfig, writeConfig);
- // Once meta fields are disabled, it cant be re-enabled for a given table.
- if (!tableConfig.populateMetaFields() && writeConfig.populateMetaFields()) {
- throw new HoodieException(HoodieTableConfig.POPULATE_META_FIELDS.key() + " already disabled for the table. Can't be re-enabled back");
+ // Meta-field population is physical, so a writer must not disagree with the table about which
+ // meta columns hold values. Compare the full enum rather than the legacy booleans: those collapse
+ // every selective mode to false, so a writer claiming COMMIT_TIME_ONLY against a NONE table would
+ // slip through and advertise commit times that were never written.
+ //
+ // hoodie.meta.fields.mode is a table property, changeable only via hudi-cli or an upgrade -- never
+ // as a side effect of a write.
+ MetaFieldsMode tableMetaFieldsMode = tableConfig.getMetaFieldsMode();
+
+ // The writer's resolved mode must equal the table's. Both directions are wrong, for different
+ // reasons: widening would leave earlier commits missing a column later ones have, and readers
+ // cannot tell the two apart; narrowing would leave rows the table still advertises as populated,
+ // which incremental queries then silently skip. Only hudi-cli or an upgrade may change the mode.
+ //
+ // HoodieWriteConfig normalizes legacy input into hoodie.meta.fields.mode as its last defaulting
+ // step. Consequently this comparison has one source of truth on both sides, including when the
+ // caller supplied only the deprecated boolean or no meta-field option at all.
+ MetaFieldsMode writeMetaFieldsMode = writeConfig.getMetaFieldsMode();
+ if (writeMetaFieldsMode != tableMetaFieldsMode) {
+ throw new HoodieException(String.format(
+ "%s mismatch: table is %s but the writer requests %s. Meta columns are physical, so the writer must "
+ + "match the table%s. Set %s=%s on the writer, or change the table's mode through "
+ + "hudi-cli.",
+ HoodieTableConfig.META_FIELDS_MODE.key(), tableMetaFieldsMode, writeMetaFieldsMode,
+ writeMetaFieldsMode.isWiderThan(tableMetaFieldsMode)
+ ? " -- enabling a column now would leave earlier commits without it"
+ : " -- writing fewer of them leaves rows the table still advertises as populated",
+ HoodieTableConfig.META_FIELDS_MODE.key(), tableMetaFieldsMode));
}
// Meta fields can be disabled only when either {@code SimpleKeyGenerator}, {@code ComplexKeyGenerator},
@@ -1563,6 +1598,23 @@ public abstract class BaseHoodieWriteClient<T, I, K, O> extends BaseHoodieClient
throw new HoodieException("Only simple, non-partitioned or complex key generator are supported when meta-fields are disabled. Used: " + keyGenClass);
}
}
+
+ // A bloom index needs the record key on disk. Without it the writer never builds a bloom filter
+ // (enableBloomFilter is gated on the same flag), so the reader finds no filter in the footer,
+ // HoodieKeyLookupHandle#getBloomFilter returns null, and addKey NPEs on the first upsert. Reject
+ // the combination here rather than let it fail mid-write with an unattributable
+ // NullPointerException.
+ if (!tableConfig.isRecordKeyPopulated()) {
+ HoodieIndex.IndexType indexType = writeConfig.getIndexType();
+ if (indexType == HoodieIndex.IndexType.BLOOM || indexType == HoodieIndex.IndexType.GLOBAL_BLOOM) {
+ throw new HoodieException(String.format(
+ "%s index requires the %s meta column, which %s=%s does not populate. The bloom filter is "
+ + "never written, so lookups would fail on the first upsert. Use SIMPLE, GLOBAL_SIMPLE, "
+ + "BUCKET or RECORD_INDEX instead, or use a mode that populates the record key.",
+ indexType, HoodieRecord.RECORD_KEY_METADATA_FIELD,
+ HoodieTableConfig.META_FIELDS_MODE.key(), tableConfig.getMetaFieldsMode()));
+ }
+ }
if (tableConfig.getTableVersion().lesserThan(HoodieTableVersion.NINE)
&& config.enableComplexKeygenValidation()
&& isComplexKeyGeneratorWithSingleRecordKeyField(tableConfig)) {
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/timeline/LSMTimelineWriter.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/timeline/LSMTimelineWriter.java
index 0e5ba37af34e..345c65b2c637 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/timeline/LSMTimelineWriter.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/timeline/LSMTimelineWriter.java
@@ -27,6 +27,7 @@ import org.apache.hudi.common.model.HoodieAvroIndexedRecord;
import org.apache.hudi.common.model.HoodieFileFormat;
import org.apache.hudi.common.model.HoodieLSMTimelineManifest;
import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.table.timeline.ActiveAction;
@@ -445,7 +446,7 @@ public class LSMTimelineWriter {
if (this.writeConfig == null) {
this.writeConfig = HoodieWriteConfig.newBuilder()
.withProperties(this.config.getProps())
- .withPopulateMetaFields(false).build();
+ .withMetaFieldsMode(MetaFieldsMode.NONE).build();
}
return this.writeConfig;
}
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java
index 0f1e32012394..73bbffb749d9 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java
@@ -50,6 +50,7 @@ import org.apache.hudi.common.model.HoodiePreWriteCleanerPolicy;
import org.apache.hudi.common.model.HoodieRecordMerger;
import org.apache.hudi.common.model.HoodieRecordPayload;
import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.WriteConcurrencyMode;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.schema.internal.utils.SchemaChangeUtils;
@@ -167,6 +168,19 @@ public class HoodieWriteConfig extends HoodieConfig {
.withDocumentation("If enabled, writers automatically migrate the table to the specified write table version "
+ "if the current table version is lower.");
+ public static final ConfigProperty<Boolean> ALLOW_META_FIELDS_MODE_RETENTION_ON_DOWNGRADE = ConfigProperty
+ .key("hoodie.downgrade.allow.meta.fields.mode.retention")
+ .defaultValue(false)
+ .markAdvanced()
+ .withDocumentation("Permits downgrading a table below version 10 while it still carries a selective "
+ + HoodieTableConfig.META_FIELDS_MODE.key() + ". Only consulted for tables created at version 10 or "
+ + "later: those never existed under an older version, so no reader outside this deployment has ever "
+ + "had to honor the mode. Setting this asserts that every reader of the table understands "
+ + HoodieTableConfig.META_FIELDS_MODE.key() + " rather than relying on "
+ + HoodieTableConfig.POPULATE_META_FIELDS.key() + " alone. Tables created before version 10 are "
+ + "downgraded without this flag -- they predate the mode, so returning them to a version that "
+ + "predates it is not a new state for them.");
+
public static final ConfigProperty<String> TAGGED_RECORD_STORAGE_LEVEL_VALUE = ConfigProperty
.key("hoodie.write.tagged.record.storage.level")
.defaultValue("MEMORY_AND_DISK_SER")
@@ -1773,8 +1787,36 @@ public class HoodieWriteConfig extends HoodieConfig {
return getInt(MERGE_SMALL_FILE_GROUP_CANDIDATES_LIMIT);
}
+ /**
+ * @return true when every meta column is populated.
+ *
+ * <p>Derived from {@link #getMetaFieldsMode()} so that call sites still written against the
+ * deprecated {@code hoodie.populate.meta.fields} boolean observe the same answer as the enum:
+ * only {@link MetaFieldsMode#ALL} populates every meta column.
+ */
public boolean populateMetaFields() {
- return getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ return getMetaFieldsMode().toLegacyPopulateMetaFields();
+ }
+
+ /**
+ * @return the {@link MetaFieldsMode} configured for writes.
+ */
+ public MetaFieldsMode getMetaFieldsMode() {
+ return MetaFieldsMode.resolve(this);
+ }
+
+ /**
+ * @return true when {@code _hoodie_commit_time} is physically populated on every row.
+ */
+ public boolean isCommitTimePopulated() {
+ return getMetaFieldsMode().isCommitTimePopulated();
+ }
+
+ /**
+ * @return true when {@code _hoodie_file_name} is physically populated on every row.
+ */
+ public boolean isFileNamePopulated() {
+ return getMetaFieldsMode().isFileNamePopulated();
}
/**
@@ -3587,11 +3629,47 @@ public class HoodieWriteConfig extends HoodieConfig {
return this;
}
+ /**
+ * @deprecated since 1.3.0, use {@link #withMetaFieldsMode(MetaFieldsMode)} instead
+ * ({@code true} maps to {@link MetaFieldsMode#ALL}, {@code false} to {@link MetaFieldsMode#NONE}).
+ */
+ @Deprecated
public Builder withPopulateMetaFields(boolean populateMetaFields) {
writeConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS, Boolean.toString(populateMetaFields));
return this;
}
+ public Builder withMetaFieldsMode(MetaFieldsMode metaFieldsMode) {
+ // Leaving the mode unset defers to the deprecated populate.meta.fields boolean. The legacy
+ // boolean is derived from the mode in build() rather than here, so the two cannot be made to
+ // disagree by calling the setters in either order.
+ writeConfig.setValue(HoodieTableConfig.META_FIELDS_MODE,
+ metaFieldsMode == null ? "" : metaFieldsMode.name());
+ return this;
+ }
+
+ /**
+ * Rewrite the deprecated {@code populate.meta.fields} boolean from {@code meta.fields.mode}
+ * whenever a mode is set, so the two can never disagree on the resulting config.
+ *
+ * <p>Done at build time, not in the setter: {@code withPopulateMetaFields} does not re-derive
+ * the mode, so deriving in {@link #withMetaFieldsMode} alone would make the invariant depend on
+ * call order. {@code withMetaFieldsMode(COMMIT_TIME_ONLY).withPopulateMetaFields(true)} would
+ * leave a selective mode sitting next to {@code populate.meta.fields=true} — a config that
+ * resolves correctly (the mode wins) but carries the contradiction to disk on any path that
+ * copies raw write-config props into {@code hoodie.properties}, misleading pre-1.3.0 readers
+ * into treating the table as ALL.
+ */
+ private void deriveMetaFieldsPopulationOptions() {
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(writeConfig);
+ writeConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, metaFieldsMode.name());
+
+ // The mode is the source of truth. Always rewrite the deprecated boolean so inherited props,
+ // direct builder calls, and their ordering all produce the same coherent config.
+ writeConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS,
+ Boolean.toString(metaFieldsMode.toLegacyPopulateMetaFields()));
+ }
+
public Builder withAllowOperationMetadataField(boolean allowOperationMetadataField) {
writeConfig.setValue(ALLOW_OPERATION_METADATA_FIELD, Boolean.toString(allowOperationMetadataField));
return this;
@@ -3772,6 +3850,8 @@ public class HoodieWriteConfig extends HoodieConfig {
HoodieTTLConfig.newBuilder().fromProperties(writeConfig.getProps()).build());
autoAdjustConfigsForConcurrencyMode(isLockProviderPropertySet);
+ // Keep the legacy boolean coherent after every explicit and derived default has been applied.
+ deriveMetaFieldsPopulationOptions();
}
private boolean isLockRequiredForSingleWriter() {
@@ -3889,6 +3969,27 @@ public class HoodieWriteConfig extends HoodieConfig {
checkArgument(ttlStatsMaxParallelism > 0,
String.format("%s must be positive, but was %d",
HoodieTTLConfig.STATS_MAX_PARALLELISM.key(), ttlStatsMaxParallelism));
+
+ // hoodie.meta.fields.mode is the source of truth for meta-column population; the deprecated
+ // populate.meta.fields boolean is consulted only when the mode is absent. There is therefore
+ // no ambiguous combination to reject here — MetaFieldsMode.resolve throws on unrecognized
+ // values.
+ MetaFieldsMode metaFieldsMode = writeConfig.getMetaFieldsMode();
+ // Selective meta-field modes are CoW-only in this release. MoR log-write path does not yet
+ // respect the mode, which would silently produce log records with null meta columns.
+ boolean isSelective = metaFieldsMode.isSelective();
+ checkArgument(!(writeConfig.getTableType() == HoodieTableType.MERGE_ON_READ && isSelective),
+ String.format("%s=%s is currently supported for COPY_ON_WRITE tables only. MoR support is a follow-up. "
+ + "For MoR use %s=ALL or %s=NONE.",
+ HoodieTableConfig.META_FIELDS_MODE.key(), metaFieldsMode,
+ HoodieTableConfig.META_FIELDS_MODE.key(), HoodieTableConfig.META_FIELDS_MODE.key()));
+ // Selective meta-field modes are wired only for the Spark writer path in this release. Flink
+ // RowData / Java-client writers ignore the mode and would silently produce NONE-mode output.
+ checkArgument(!(engineType != EngineType.SPARK && isSelective),
+ String.format("%s=%s is currently supported for the Spark writer only. Support for engine=%s is a follow-up. "
+ + "Use %s=ALL or %s=NONE.",
+ HoodieTableConfig.META_FIELDS_MODE.key(), metaFieldsMode, engineType,
+ HoodieTableConfig.META_FIELDS_MODE.key(), HoodieTableConfig.META_FIELDS_MODE.key()));
}
public HoodieWriteConfig build() {
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/BaseCreateHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/BaseCreateHandle.java
index 94bfa6cd2e4d..2decb5f2ecdf 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/BaseCreateHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/BaseCreateHandle.java
@@ -27,6 +27,7 @@ import org.apache.hudi.common.model.HoodiePartitionMetadata;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.model.IOType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.MetadataValues;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.util.Option;
@@ -57,6 +58,13 @@ public abstract class BaseCreateHandle<T, I, K, O> extends HoodieWriteHandle<T,
protected long recordsDeleted = 0;
protected Map<String, HoodieRecord<T>> recordMap;
protected boolean useWriterSchema = false;
+ // Read from the TABLE config, not the write config. Meta-field population is a physical property
+ // of the table, so the table is the authority: a writer carrying a stale
+ // hoodie.populate.meta.fields would otherwise resolve to NONE and write null meta columns into a
+ // table whose earlier files have them populated. Resolved once rather than per record --
+ // updateFileName consults it on the preserve-metadata path.
+ private final MetaFieldsMode metaFieldsMode =
+ hoodieTable.getMetaClient().getTableConfig().getMetaFieldsMode();
public BaseCreateHandle(HoodieWriteConfig config, String instantTime, HoodieTable<T, I, K, O> hoodieTable,
String partitionPath, String fileId, Option<HoodieSchema> overriddenSchema,
@@ -151,7 +159,8 @@ public abstract class BaseCreateHandle<T, I, K, O> extends HoodieWriteHandle<T,
*/
protected void writeRecordToFile(HoodieRecord record, HoodieSchema schema) throws IOException {
if (preserveMetadata) {
- HoodieRecord populatedRecord = updateFileName(record, schema, writeSchemaWithMetaFields, path.getName(), config.getProps());
+ HoodieRecord populatedRecord =
+ updateFileName(record, schema, writeSchemaWithMetaFields, path.getName(), config.getProps());
if (isSecondaryIndexStatsStreamingWritesEnabled) {
SecondaryIndexStreamingTracker.trackSecondaryIndexStats(populatedRecord, writeStatus, writeSchemaWithMetaFields, secondaryIndexDefns, config);
}
@@ -166,8 +175,22 @@ public abstract class BaseCreateHandle<T, I, K, O> extends HoodieWriteHandle<T,
}
}
+ /**
+ * Rewrite {@code _hoodie_file_name} to the file being written, when the table populates it.
+ *
+ * <p>{@code preserveMetadata} marks a table-service rewrite -- compaction or clustering copying
+ * existing data files forward -- so the record already carries whatever meta columns the table
+ * populates. Set the file name only when the mode says that column holds values; on a mode that
+ * opts out it is already null in the source file, so there is nothing to rewrite and nothing to
+ * clear.
+ */
protected HoodieRecord<T> updateFileName(HoodieRecord<T> record, HoodieSchema schema, HoodieSchema targetSchema, String fileName, Properties prop) {
- MetadataValues metadataValues = new MetadataValues().setFileName(fileName);
+ MetadataValues metadataValues = new MetadataValues();
+ if (metaFieldsMode.isFileNamePopulated()) {
+ metadataValues.setFileName(fileName);
+ }
+ // Even with no file-name value to update, this projection is required to align Spark records
+ // with the writer schema (for example, by dropping the temporary row-index column).
return record.prependMetaFields(schema, targetSchema, metadataValues, prop);
}
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieBinaryCopyHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieBinaryCopyHandle.java
index e1d13abddd29..e209acf232d9 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieBinaryCopyHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieBinaryCopyHandle.java
@@ -106,6 +106,9 @@ public class HoodieBinaryCopyHandle<T, I, K, O> extends HoodieWriteHandle<T, I,
conf,
CompressionCodecName.fromConf(config.getStringOrDefault(HoodieStorageConfig.PARQUET_COMPRESSION_CODEC_NAME)),
fileMetadataMerger);
+ // From the TABLE config, as the write handles do: the mode is a table property, and the copier
+ // otherwise rewrites _hoodie_file_name on a table that does not populate it.
+ this.writer.setMetaFieldsMode(hoodieTable.getMetaClient().getTableConfig().getMetaFieldsMode());
}
public void write() {
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieWriteMergeHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieWriteMergeHandle.java
index d997d0438453..fbd7b3d37872 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieWriteMergeHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieWriteMergeHandle.java
@@ -28,6 +28,7 @@ import org.apache.hudi.common.model.HoodieOperation;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.model.HoodieWriteStat.RuntimeStats;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.MetadataValues;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.serialization.DefaultSerializer;
@@ -108,6 +109,12 @@ public class HoodieWriteMergeHandle<T, I, K, O> extends HoodieAbstractMergeHandl
@Setter
protected HoodieReaderContext<T> readerContext;
+ // Read from the TABLE config, not the write config -- see the note on BaseCreateHandle. Resolved
+ // once rather than per record: writeToFile consults it on the preserve-metadata path, which runs
+ // for every record copied forward during a merge.
+ private final MetaFieldsMode metaFieldsMode =
+ hoodieTable.getMetaClient().getTableConfig().getMetaFieldsMode();
+
protected long recordsWritten = 0;
protected long recordsDeleted = 0;
protected long updatedRecordsWritten = 0;
@@ -417,7 +424,13 @@ public class HoodieWriteMergeHandle<T, I, K, O> extends HoodieAbstractMergeHandl
if (shouldPreserveRecordMetadata) {
// NOTE: `FILENAME_METADATA_FIELD` has to be rewritten to correctly point to the
// file holding this record even in cases when overall metadata is preserved
- HoodieRecord populatedRecord = record.updateMetaField(schema, HoodieRecord.FILENAME_META_FIELD_ORD, newFilePath.getName());
+ //
+ // Rewrite it only when the table populates that column. This path copies a record forward from
+ // the previous base file, so it already carries whatever meta columns the table populates; on a
+ // mode that opts out the column is already null in the source and there is nothing to rewrite.
+ HoodieRecord populatedRecord = metaFieldsMode.isFileNamePopulated()
+ ? record.updateMetaField(schema, HoodieRecord.FILENAME_META_FIELD_ORD, newFilePath.getName())
+ : record;
fileWriter.write(key.getRecordKey(), populatedRecord, writeSchemaWithMetaFields, props);
} else {
// rewrite the record to include metadata fields in schema, and the values will be set later.
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/NineToTenUpgradeHandler.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/NineToTenUpgradeHandler.java
index 97fdea90036f..ba9abf49cc96 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/NineToTenUpgradeHandler.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/NineToTenUpgradeHandler.java
@@ -18,13 +18,26 @@
package org.apache.hudi.table.upgrade;
+import org.apache.hudi.common.config.ConfigProperty;
import org.apache.hudi.common.engine.HoodieEngineContext;
+import org.apache.hudi.common.model.MetaFieldsMode;
+import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.config.HoodieWriteConfig;
+import java.util.Collections;
+import java.util.Map;
+
/**
* Version 10 enables native log format by default for new writes. Existing version 9
* inline log files remain readable by version 10 readers, so there is no table metadata
* rewrite required for the upgrade.
+ *
+ * <p>Version 10 also introduced {@code hoodie.meta.fields.mode}. Version 9 tables predate it and
+ * resolve to {@code ALL} / {@code NONE} from the deprecated {@code hoodie.populate.meta.fields}
+ * boolean. The upgrade records that derived value explicitly so upgraded tables describe their
+ * meta-field layout the same way newly created version 10 tables do, rather than depending on the
+ * legacy fallback. Once the mode is persisted, the deprecated boolean is redundant and is removed.
+ * A later downgrade derives and restores the boolean from the mode before removing the mode.
*/
public class NineToTenUpgradeHandler implements UpgradeHandler {
@@ -34,6 +47,13 @@ public class NineToTenUpgradeHandler implements UpgradeHandler {
HoodieEngineContext context,
String instantTime,
SupportsUpgradeDowngrade upgradeDowngradeHelper) {
- return new UpgradeDowngrade.TableConfigChangeSet();
+ HoodieTableConfig tableConfig =
+ upgradeDowngradeHelper.getTable(config, context).getMetaClient().getTableConfig();
+ // Resolves from the legacy boolean for a version 9 table, since the mode property is absent.
+ MetaFieldsMode metaFieldsMode = tableConfig.getMetaFieldsMode();
+ Map<ConfigProperty, String> propertiesToUpdate = Collections.singletonMap(
+ HoodieTableConfig.META_FIELDS_MODE, metaFieldsMode.name());
+ return new UpgradeDowngrade.TableConfigChangeSet(propertiesToUpdate,
+ Collections.singleton(HoodieTableConfig.POPULATE_META_FIELDS));
}
}
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/TenToNineDowngradeHandler.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/TenToNineDowngradeHandler.java
index 393dd6986d82..f23e76a8c535 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/TenToNineDowngradeHandler.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/upgrade/TenToNineDowngradeHandler.java
@@ -18,25 +18,130 @@
package org.apache.hudi.table.upgrade;
+import org.apache.hudi.common.config.ConfigProperty;
import org.apache.hudi.common.engine.HoodieEngineContext;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableVersion;
import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.exception.HoodieUpgradeDowngradeException;
-import java.util.Collections;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
/**
* Version 10 writes native log files by default. Downgrading to version 9 requires
* full compaction of native data/delete logs before the downgrade completes.
+ *
+ * <p>Version 10 also introduced {@code hoodie.meta.fields.mode}. {@code hoodie.populate.meta.fields}
+ * is always written back from it ({@code ALL -> true}, every other mode {@code -> false}), mirroring
+ * how {@link NineToEightDowngradeHandler} restores {@code hoodie.table.payload.class}. That restate
+ * is load-bearing: {@code POPULATE_META_FIELDS} defaults to {@code true}, so a table carrying only
+ * the mode would otherwise downgrade to {@code ALL} and claim {@code _hoodie_record_key} is
+ * populated on files where it is null.
+ *
+ * <p>What happens to the mode itself depends on whether the legacy boolean can express it:
+ *
+ * <ul>
+ * <li>{@link MetaFieldsMode#ALL} / {@link MetaFieldsMode#NONE} — dropped. These are exactly the
+ * two states the boolean expresses, so the mode carries nothing the downgraded table lacks.</li>
+ * <li>A selective mode, restated by the writer — <b>retained</b>. Restating it is the operator
+ * asserting that every reader of this table honors the mode rather than the boolean alone.
+ * Keeping it is also what makes the round trip lossless: a later re-upgrade finds the mode
+ * intact rather than deriving {@code NONE} from the boolean.</li>
+ * <li>A selective mode, not restated (or restated as a different value) — <b>rejected</b>.
+ * Dropping it would collapse the table to {@code NONE} irreversibly, and that is not a call to
+ * make on the operator's behalf.</li>
+ * </ul>
+ *
+ * <p>Retaining the mode on a version 9 table is safe mechanically: the property carries no
+ * {@code sinceVersion}, so {@code dropInvalidConfigs} does not strip it on load.
*/
public class TenToNineDowngradeHandler implements DowngradeHandler {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TenToNineDowngradeHandler.class);
+
@Override
public UpgradeDowngrade.TableConfigChangeSet downgrade(
HoodieWriteConfig config,
HoodieEngineContext context,
String instantTime,
SupportsUpgradeDowngrade upgradeDowngradeHelper) {
+ Set<ConfigProperty> propertiesToDelete = new HashSet<>();
+ propertiesToDelete.add(HoodieTableConfig.TABLE_STORAGE_LAYOUT);
+
+ Map<ConfigProperty, String> propertiesToUpdate = new HashMap<>();
+ if (upgradeDowngradeHelper != null) {
+ MetaFieldsMode metaFieldsMode =
+ upgradeDowngradeHelper.getTable(config, context).getMetaClient().getTableConfig().getMetaFieldsMode();
+
+ // Always restate the legacy boolean from the mode. Version 9 readers understand only that
+ // property, and without it POPULATE_META_FIELDS falls back to its `true` default -- i.e. the
+ // table silently downgrades to ALL and claims meta columns it does not have. For ALL / NONE
+ // this restates what was already there; for a selective mode it writes `false`, so a reader
+ // that does not honor the mode under-claims rather than over-claims.
+ propertiesToUpdate.put(HoodieTableConfig.POPULATE_META_FIELDS,
+ String.valueOf(metaFieldsMode.toLegacyPopulateMetaFields()));
+
+ HoodieTableVersion initialVersion =
+ upgradeDowngradeHelper.getTable(config, context).getMetaClient().getTableConfig().getTableInitialVersion();
+
+ if (!metaFieldsMode.isSelective()) {
+ // ALL and NONE are exactly what the boolean can express, so the mode carries no information
+ // the downgraded table lacks. Drop it.
+ propertiesToDelete.add(HoodieTableConfig.META_FIELDS_MODE);
+ } else if (initialVersion.lesserThan(HoodieTableVersion.TEN)
+ || config.getBooleanOrDefault(HoodieWriteConfig.ALLOW_META_FIELDS_MODE_RETENTION_ON_DOWNGRADE)) {
+ // Selective mode, and the writer restated it. That restatement is the operator asserting
+ // "I know this table is selective and every reader of it honors the mode" -- so the mode is
+ // retained on the downgraded table rather than dropped. Two consequences they are taking on:
+ // the property outlives the version that formally understands it (harmless -- it carries no
+ // sinceVersion, so it is not stripped on load), and a reader that ignores it sees
+ // populate.meta.fields=false and treats the table as NONE.
+ //
+ // Keeping it is also what makes the round trip lossless: a later re-upgrade finds the mode
+ // intact instead of deriving NONE from the boolean.
+ LOG.warn("Downgrading a table on {}={} to table version 9, retaining the mode on the downgraded "
+ + "table (created at table version {}). Version 9 does not formally understand it, so "
+ + "every reader of this table must honor {} rather than relying on {} alone -- which now "
+ + "reads false and would have them treat the table as NONE.",
+ HoodieTableConfig.META_FIELDS_MODE.key(), metaFieldsMode, initialVersion.versionCode(),
+ HoodieTableConfig.META_FIELDS_MODE.key(),
+ HoodieTableConfig.POPULATE_META_FIELDS.key());
+ } else {
+ // Created at version 10 or later and still selective, with no explicit opt-in. This table has
+ // never existed under a version that predates the mode, so nothing outside this deployment has
+ // ever had to honor it -- and the operator has not said that it does. Retaining the mode would
+ // leave a property the downgraded version does not formally understand; dropping it would
+ // collapse the table to NONE irreversibly, since a re-upgrade derives the mode from a boolean
+ // that by then reads false. Neither is ours to choose silently.
+ throw new HoodieUpgradeDowngradeException(String.format(
+ "Cannot downgrade to table version 9: %s=%s populates only some meta columns, which version "
+ + "9 cannot express, and this table was created at table version %s so it has never been "
+ + "read by an older version. Set %s=true to retain the mode on the downgraded table -- "
+ + "every reader must then honor %s rather than %s, which will read false. Alternatively "
+ + "rewrite the table as %s or %s first.",
+ HoodieTableConfig.META_FIELDS_MODE.key(), metaFieldsMode, initialVersion.versionCode(),
+ HoodieWriteConfig.ALLOW_META_FIELDS_MODE_RETENTION_ON_DOWNGRADE.key(),
+ HoodieTableConfig.META_FIELDS_MODE.key(),
+ HoodieTableConfig.POPULATE_META_FIELDS.key(),
+ MetaFieldsMode.ALL, MetaFieldsMode.NONE));
+ }
+ } else {
+ // No helper means the table config is unreachable, so the mode cannot be read. Deleting the
+ // property is still correct (version 9 cannot interpret it), but the legacy boolean is left
+ // alone rather than guessed at -- writing a derived value from an assumed mode is how a table
+ // would end up claiming meta columns it does not have.
+ propertiesToDelete.add(HoodieTableConfig.META_FIELDS_MODE);
+ }
+
return new UpgradeDowngrade.TableConfigChangeSet(
- Collections.emptyMap(),
- Collections.singleton(HoodieTableConfig.TABLE_STORAGE_LAYOUT));
+ propertiesToUpdate,
+ propertiesToDelete);
}
}
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/TestBaseHoodieWriteClient.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/TestBaseHoodieWriteClient.java
index 4396e061a49e..43867ced791a 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/TestBaseHoodieWriteClient.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/TestBaseHoodieWriteClient.java
@@ -23,7 +23,9 @@ import org.apache.hudi.client.embedded.EmbeddedTimelineService;
import org.apache.hudi.client.transaction.TransactionManager;
import org.apache.hudi.common.engine.HoodieLocalEngineContext;
import org.apache.hudi.common.model.HoodieCommitMetadata;
+import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieTimelineTimeZone;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.WriteConcurrencyMode;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.table.HoodieTableConfig;
@@ -40,9 +42,11 @@ import org.apache.hudi.common.table.view.FileSystemViewStorageType;
import org.apache.hudi.common.testutils.HoodieCommonTestHarness;
import org.apache.hudi.common.testutils.HoodieTestUtils;
import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieIndexConfig;
import org.apache.hudi.config.HoodieLockConfig;
import org.apache.hudi.config.HoodieWriteConfig;
import org.apache.hudi.core.transaction.lock.InProcessLockProvider;
+import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.index.HoodieIndex;
import org.apache.hudi.index.HoodieSimpleIndex;
import org.apache.hudi.keygen.ComplexAvroKeyGenerator;
@@ -55,6 +59,7 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.InOrder;
import org.mockito.Mockito;
@@ -74,6 +79,8 @@ import java.util.stream.Stream;
import static org.apache.hudi.common.testutils.HoodieTestUtils.getDefaultStorageConf;
import static org.apache.hudi.testutils.Assertions.assertComplexKeyGeneratorValidationThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@@ -82,6 +89,262 @@ import static org.mockito.Mockito.when;
class TestBaseHoodieWriteClient extends HoodieCommonTestHarness {
+ private static HoodieTableConfig tableConfigWithMode(MetaFieldsMode mode) {
+ HoodieTableConfig tableConfig = new HoodieTableConfig();
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, mode.name());
+ tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS,
+ Boolean.toString(mode.toLegacyPopulateMetaFields()));
+ tableConfig.setValue(HoodieTableConfig.VERSION,
+ String.valueOf(HoodieTableVersion.current().versionCode()));
+ return tableConfig;
+ }
+
+ private static BaseHoodieWriteClient<?, ?, ?, ?> validatorClient(HoodieWriteConfig writeConfig) {
+ return new TestWriteClient(writeConfig, mock(HoodieTable.class), Option.empty(),
+ mock(BaseHoodieTableServiceClient.class));
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsMetaFieldsModeMismatch() throws IOException {
+ initMetaClient();
+ // A writer that explicitly asks for NONE against a COMMIT_TIME_ONLY table: both legacy booleans
+ // are false, so a boolean-only check passes and the writer goes on to produce null commit times
+ // while the table still advertises COMMIT_TIME_ONLY.
+ HoodieWriteConfig noneWriteConfig = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.NONE)
+ .build();
+ assertEquals(MetaFieldsMode.NONE, noneWriteConfig.getMetaFieldsMode());
+
+ HoodieTableConfig commitTimeOnlyTable = tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY);
+ assertFalse(commitTimeOnlyTable.populateMetaFields(),
+ "precondition: both legacy booleans are false, so only the enum comparison can catch this");
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(noneWriteConfig).validateAgainstTableProperties(commitTimeOnlyTable, noneWriteConfig));
+ assertTrue(ex.getMessage().contains(HoodieTableConfig.META_FIELDS_MODE.key()),
+ "error must name the mode property: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains("COMMIT_TIME_ONLY") && ex.getMessage().contains("NONE"),
+ "error must name both modes: " + ex.getMessage());
+ }
+
+ @Test
+ void validateAgainstTablePropertiesAcceptsAnUnstatedWriterAgainstANonSelectiveTable() throws IOException {
+ initMetaClient();
+ // An ALL or NONE table may be written by a writer that states no meta-field property at all. Those
+ // two modes are exactly what the deprecated boolean expresses, so such a writer resolves to the
+ // right answer on its own -- and the overwhelming majority of callers, including every table
+ // service, build their config this way. Only the three selective modes require a statement, since
+ // no legacy property can express them; see
+ // validateAgainstTablePropertiesRequiresAnUnstatedWriterToStateASelectiveMode.
+ HoodieWriteConfig unstated = HoodieWriteConfig.newBuilder().withPath(basePath).build();
+ assertEquals(MetaFieldsMode.ALL, unstated.getMetaFieldsMode(),
+ "precondition: on its own an unstated writer resolves to the ALL default");
+
+ validatorClient(unstated)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.ALL), unstated);
+
+ assertEquals(MetaFieldsMode.ALL, unstated.getMetaFieldsMode());
+ assertTrue(unstated.populateMetaFields(),
+ "the derived legacy boolean must follow the mode, or the ~55 call sites still reading "
+ + "populateMetaFields() would disagree with the enum");
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRequiresAnUnstatedWriterToStateASelectiveMode() throws IOException {
+ initMetaClient();
+ // A selective table requires every writer to name the mode. Inheriting it here would work, but it
+ // could not be relied upon: the mode is read further down the write path by handles and by writer
+ // factories, three of whose call sites hold no table config at all, so nothing there could repeat
+ // the inference. Requiring the statement is what lets all of them trust the write config.
+ //
+ // Concretely, an unstated writer resolves to the ALL default, so inheriting silently would be the
+ // difference between writing all five meta columns and writing one.
+ HoodieWriteConfig unstated = HoodieWriteConfig.newBuilder().withPath(basePath).build();
+ assertEquals(MetaFieldsMode.ALL, unstated.getMetaFieldsMode(),
+ "precondition: on its own an unstated writer resolves to the ALL default");
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(unstated).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), unstated));
+ assertTrue(ex.getMessage().contains(HoodieTableConfig.META_FIELDS_MODE.key()), ex.getMessage());
+ assertTrue(ex.getMessage().contains("COMMIT_TIME_ONLY"),
+ "the error must name the mode the writer has to state: " + ex.getMessage());
+ }
+
+ @Test
+ void validateAgainstTablePropertiesAcceptsAWriterThatRestatesTheSelectiveMode() throws IOException {
+ initMetaClient();
+ // The migration path for the case above, and what every writer against a selective table must do.
+ HoodieWriteConfig restated = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+
+ validatorClient(restated)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), restated);
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, restated.getMetaFieldsMode());
+ assertFalse(restated.populateMetaFields(),
+ "COMMIT_TIME_ONLY does not populate the record key, so the derived boolean stays false");
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsUnstatedWriterNarrowingASelectiveTable() throws IOException {
+ initMetaClient();
+ // The StreamSync-restart case. A writer that resolves to NONE against a COMMIT_TIME_ONLY table
+ // would write base files with a null _hoodie_commit_time while hoodie.properties still says
+ // COMMIT_TIME_ONLY, and incremental queries — which the table is still deemed to support — would
+ // silently drop every one of those rows.
+ //
+ // Stating NONE makes it an explicit mismatch. Stating nothing at all is rejected too, by the
+ // must-state-it rule — see validateAgainstTablePropertiesRequiresAnUnstatedWriterToStateASelectiveMode.
+ HoodieWriteConfig stated = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.NONE)
+ .build();
+ assertEquals(MetaFieldsMode.NONE, stated.getMetaFieldsMode());
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(stated).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), stated));
+ assertTrue(ex.getMessage().contains(HoodieTableConfig.META_FIELDS_MODE.key()), ex.getMessage());
+ assertTrue(ex.getMessage().contains("COMMIT_TIME_ONLY") && ex.getMessage().contains("NONE"),
+ "error must name both modes: " + ex.getMessage());
+ // The message must point at the sanctioned mutation path rather than implying a write can do it.
+ assertTrue(ex.getMessage().contains("hudi-cli"), ex.getMessage());
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsStatedSelectiveToSelectiveNarrowing() throws IOException {
+ initMetaClient();
+ // Same shape one step in: a writer stating COMMIT_TIME_ONLY against COMMIT_TIME_AND_FILE_NAME.
+ // Narrowing between two selective modes is still a conflict — only hudi-cli may do that.
+ HoodieWriteConfig stated = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+
+ assertThrows(HoodieException.class, () ->
+ validatorClient(stated).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME), stated));
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsSiblingSelectiveModesBothWays() throws IOException {
+ initMetaClient();
+ // COMMIT_TIME_ONLY and FILE_NAME_ONLY are each wider than the other, so neither can stand in for
+ // the other. Nothing tested this before, and it is the case that makes "narrowing is allowed"
+ // subtle: there is no narrowing direction between them at all.
+ HoodieWriteConfig commitTimeOnly = HoodieWriteConfig.newBuilder()
+ .withPath(basePath).withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY).build();
+ HoodieWriteConfig fileNameOnly = HoodieWriteConfig.newBuilder()
+ .withPath(basePath).withMetaFieldsMode(MetaFieldsMode.FILE_NAME_ONLY).build();
+
+ assertThrows(HoodieException.class, () -> validatorClient(commitTimeOnly)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.FILE_NAME_ONLY), commitTimeOnly));
+ assertThrows(HoodieException.class, () -> validatorClient(fileNameOnly)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), fileNameOnly));
+ }
+
+ @Test
+ void validateAgainstTablePropertiesAllowsSelectiveWriterToNarrowAnAllTable() throws IOException {
+ initMetaClient();
+ // COMMIT_TIME_AND_FILE_NAME against ALL populates strictly fewer columns (no record key), so it
+ // is a narrowing and stays allowed. Pins the one pair the isRecordKeyPopulated clause decides.
+ HoodieWriteConfig selective = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME)
+ .build();
+
+ // Rejected in this direction only because the writer stated the mode explicitly.
+ assertThrows(HoodieException.class, () -> validatorClient(selective)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.ALL), selective));
+ // ...but never as a *widening*: the reverse direction is what isWiderThan must catch.
+ HoodieWriteConfig allWriter = HoodieWriteConfig.newBuilder()
+ .withPath(basePath).withMetaFieldsMode(MetaFieldsMode.ALL).build();
+ HoodieException ex = assertThrows(HoodieException.class, () -> validatorClient(allWriter)
+ .validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME), allWriter));
+ assertTrue(ex.getMessage().contains("would leave earlier commits without it"),
+ "the message must name the widening as the reason: " + ex.getMessage());
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsADefaultWriterAgainstANoneTable() throws IOException {
+ initMetaClient();
+ // A default writer is normalized to the ALL mode. Against a NONE table that is a widening: it
+ // would populate all five meta columns on a table that has none of them. This must be caught here
+ // rather than quietly corrected -- the mode is read again downstream by handles and writer
+ // factories that cannot repeat any correction made at this point.
+ HoodieWriteConfig defaultWriteConfig = HoodieWriteConfig.newBuilder().withPath(basePath).build();
+ assertEquals(MetaFieldsMode.ALL, defaultWriteConfig.getMetaFieldsMode(),
+ "precondition: a default writer is normalized to ALL");
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(defaultWriteConfig).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.NONE), defaultWriteConfig));
+ assertTrue(ex.getMessage().contains("requests ALL"), ex.getMessage());
+ assertTrue(ex.getMessage().contains("NONE"), ex.getMessage());
+ // The rejected validation must not have mutated the write config.
+ assertEquals(MetaFieldsMode.ALL, defaultWriteConfig.getMetaFieldsMode(),
+ "validation must not modify the write config");
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsStatedWidening() throws IOException {
+ initMetaClient();
+ // Widening is rejected when the writer asks for it: ALL against a NONE table would claim meta
+ // columns the table never wrote, and earlier commits cannot be distinguished from later ones.
+ HoodieWriteConfig allWriter = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.ALL)
+ .build();
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(allWriter)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.NONE), allWriter));
+ assertTrue(ex.getMessage().contains("would leave earlier commits without it"),
+ "the message must name the widening as the reason: " + ex.getMessage());
+ }
+
+ @Test
+ void validateAgainstTablePropertiesRejectsAnExplicitLegacyBooleanThatDisagrees() throws IOException {
+ initMetaClient();
+ // The one user-visible break in this rule. Passing populate.meta.fields=false against an ALL
+ // table used to narrow it silently (HUDI-2161); it now throws, because the writer explicitly
+ // asked for something the table cannot do. Telling the user beats overriding them — but existing
+ // jobs that pass this flag against a default table will fail until they drop it.
+ HoodieWriteConfig legacyFalse = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withPopulateMetaFields(false)
+ .build();
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(legacyFalse)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.ALL), legacyFalse));
+ assertTrue(ex.getMessage().contains("hudi-cli"),
+ "the message must point at the sanctioned mutation path: " + ex.getMessage());
+ }
+
+ @Test
+ void validateAgainstTablePropertiesAcceptsMatchingMetaFieldsMode() throws IOException {
+ initMetaClient();
+ // Default writer and default table both resolve to ALL — the overwhelmingly common case.
+ HoodieWriteConfig defaultWriteConfig = HoodieWriteConfig.newBuilder().withPath(basePath).build();
+ assertEquals(MetaFieldsMode.ALL, defaultWriteConfig.getMetaFieldsMode());
+ validatorClient(defaultWriteConfig)
+ .validateAgainstTableProperties(tableConfigWithMode(MetaFieldsMode.ALL), defaultWriteConfig);
+
+ // And a selective writer against a table recorded with the same mode.
+ HoodieWriteConfig selectiveWriteConfig = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+ validatorClient(selectiveWriteConfig).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), selectiveWriteConfig);
+ }
+
@Test
void startCommitWillRollbackFailedWritesInEagerMode() throws IOException {
initMetaClient();
@@ -400,4 +663,51 @@ class TestBaseHoodieWriteClient extends HoodieCommonTestHarness {
}
}
+
+ @ParameterizedTest
+ @CsvSource({"BLOOM", "GLOBAL_BLOOM"})
+ void validateAgainstTablePropertiesRejectsABloomIndexWithoutTheRecordKey(String indexTypeName) throws IOException {
+ initMetaClient();
+ // A bloom index needs the record key on disk. Without it the writer never builds a filter --
+ // HoodieFileWriterFactory#enableBloomFilter short-circuits on populateMetaFields, which every
+ // selective mode makes false -- so the reader finds none in the footer,
+ // HoodieKeyLookupHandle#getBloomFilter returns null, and addKey NPEs on the first upsert.
+ //
+ // hoodie.index.type defaults to BLOOM, so a COMMIT_TIME_ONLY table created with defaults would hit
+ // this. Rejecting at init beats an unattributable NullPointerException mid-write.
+ HoodieIndex.IndexType indexType = HoodieIndex.IndexType.valueOf(indexTypeName);
+ HoodieWriteConfig writeConfig = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .withIndexConfig(HoodieIndexConfig.newBuilder().withIndexType(indexType).build())
+ .build();
+
+ HoodieException ex = assertThrows(HoodieException.class, () ->
+ validatorClient(writeConfig).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), writeConfig));
+ assertTrue(ex.getMessage().contains(indexTypeName),
+ "the message must name the index type: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains(HoodieRecord.RECORD_KEY_METADATA_FIELD),
+ "the message must name the missing meta column: " + ex.getMessage());
+ }
+
+ @ParameterizedTest
+ // BUCKET is omitted: its builder requires extra bucket configuration this fixture does not
+ // supply, which is unrelated to the meta-fields restriction under test.
+ @CsvSource({"SIMPLE", "GLOBAL_SIMPLE"})
+ void validateAgainstTablePropertiesAcceptsNonBloomIndexesOnASelectiveTable(String indexTypeName) throws IOException {
+ initMetaClient();
+ // The indexes that do not need a persisted record key stay available -- the restriction is on the
+ // bloom filter specifically, not on selective tables having an index at all. BUCKET is likewise
+ // unrestricted; it is left out of the parameters only because its builder needs extra setup.
+ HoodieWriteConfig writeConfig = HoodieWriteConfig.newBuilder()
+ .withPath(basePath)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .withIndexConfig(HoodieIndexConfig.newBuilder()
+ .withIndexType(HoodieIndex.IndexType.valueOf(indexTypeName)).build())
+ .build();
+
+ validatorClient(writeConfig).validateAgainstTableProperties(
+ tableConfigWithMode(MetaFieldsMode.COMMIT_TIME_ONLY), writeConfig);
+ }
}
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/timeline/TestHoodieTimelineArchiver.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/timeline/TestHoodieTimelineArchiver.java
index 76192a4f06b1..af117dd110f2 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/timeline/TestHoodieTimelineArchiver.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/timeline/TestHoodieTimelineArchiver.java
@@ -22,7 +22,9 @@ package org.apache.hudi.client.timeline;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.engine.HoodieEngineContext;
import org.apache.hudi.common.engine.HoodieLocalEngineContext;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
+import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.table.timeline.versioning.v1.ActiveTimelineV1;
import org.apache.hudi.common.testutils.HoodieCommonTestHarness;
import org.apache.hudi.common.testutils.InProcessTimeGenerator;
@@ -41,6 +43,7 @@ import java.util.Collections;
import static org.apache.hudi.common.testutils.SchemaTestUtil.getSchemaFromResource;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -95,6 +98,44 @@ class TestHoodieTimelineArchiver extends HoodieCommonTestHarness {
assertEquals(9, rawActiveTimeline.countInstants());
}
+ /**
+ * The LSM writer must build its config on a table upgraded to version 10.
+ *
+ * <p>{@code LSMTimelineWriter#getOrCreateWriterConfig} inherits the parent config's props and then
+ * sets {@code metaFieldsMode=NONE} -- it writes timeline instants, not records. On an upgraded
+ * table those inherited props carry {@code hoodie.meta.fields.mode=ALL}, written by
+ * {@code NineToTenUpgradeHandler} for every version 9 table. If the builder treated that inherited
+ * mode as authoritative over the writer's override, archival would use the wrong mode on every
+ * upgraded table once it passed {@code hoodie.keep.min.commits} -- the default case.
+ *
+ * <p>This exercises the writer's own config construction rather than a full archival run, because
+ * that construction is where the failure was: {@code getOrCreateWriterConfig} throws before any
+ * instant is written.
+ */
+ @Test
+ void lsmWriterConfigSurvivesAnUpgradedTablesInheritedMode() {
+ // What an upgraded v9 -> v10 table hands down: the mode written by the upgrade handler.
+ TypedProperties upgradedTableProps = new TypedProperties();
+ upgradedTableProps.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.ALL.name());
+
+ HoodieWriteConfig parentConfig = HoodieWriteConfig.newBuilder()
+ .withPath(tempDir.toString())
+ .withProperties(upgradedTableProps)
+ .build();
+ assertEquals(MetaFieldsMode.ALL, parentConfig.getMetaFieldsMode(),
+ "precondition: the parent config carries the upgraded table's ALL mode");
+
+ // Exactly what LSMTimelineWriter#getOrCreateWriterConfig does.
+ HoodieWriteConfig lsmConfig = HoodieWriteConfig.newBuilder()
+ .withProperties(parentConfig.getProps())
+ .withMetaFieldsMode(MetaFieldsMode.NONE)
+ .build();
+
+ assertEquals(MetaFieldsMode.NONE, lsmConfig.getMetaFieldsMode(),
+ "the LSM writer's explicit NONE mode must win over the table's inherited ALL");
+ assertFalse(lsmConfig.populateMetaFields());
+ }
+
private HoodieTable setupMockHoodieTable(HoodieEngineContext context, HoodieWriteConfig writeConfig) {
HoodieTable hoodieTable = mock(HoodieTable.class, RETURNS_DEEP_STUBS);
when(hoodieTable.getContext()).thenReturn(context);
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/config/TestHoodieWriteConfigMetaFieldsMode.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/config/TestHoodieWriteConfigMetaFieldsMode.java
new file mode 100644
index 000000000000..f8becb176f83
--- /dev/null
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/config/TestHoodieWriteConfigMetaFieldsMode.java
@@ -0,0 +1,312 @@
+/*
+ * 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.hudi.config;
+
+import org.apache.hudi.common.config.TypedProperties;
+import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.model.MetaFieldsMode;
+import org.apache.hudi.common.table.HoodieTableConfig;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Properties;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Validates the writer-side accessors and validation guards for the meta-field-population modes
+ * on {@link HoodieWriteConfig}. Companion test for the {@link HoodieTableConfig} accessors lives
+ * in {@code TestHoodieMetaFieldsMode}; this test covers the writer-builder surface and the
+ * cross-flag validation that runs at {@code build()} time.
+ */
+class TestHoodieWriteConfigMetaFieldsMode {
+
+ private static HoodieWriteConfig.Builder baseBuilder() {
+ return HoodieWriteConfig.newBuilder().withPath("file:///tmp/test_hudi_meta_fields_mode");
+ }
+
+ private static Properties mergeOnReadProps() {
+ Properties props = new Properties();
+ props.setProperty(HoodieTableConfig.TYPE.key(), HoodieTableType.MERGE_ON_READ.name());
+ return props;
+ }
+
+ @Test
+ void defaultsToAllMode() {
+ HoodieWriteConfig cfg = baseBuilder().build();
+ assertTrue(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.ALL, cfg.getMetaFieldsMode());
+ assertTrue(cfg.isCommitTimePopulated());
+ assertTrue(cfg.isFileNamePopulated());
+ }
+
+ @Test
+ void explicitNoneModeBuilds() {
+ HoodieWriteConfig cfg = baseBuilder().withPopulateMetaFields(false).build();
+ assertFalse(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.NONE, cfg.getMetaFieldsMode());
+ assertFalse(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ }
+
+ @Test
+ void commitTimeOnlyModeBuilds() {
+ HoodieWriteConfig cfg = baseBuilder()
+ .withPopulateMetaFields(false)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, cfg.getMetaFieldsMode());
+ assertTrue(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ }
+
+ @Test
+ void fileNameOnlyModeBuilds() {
+ HoodieWriteConfig cfg = baseBuilder()
+ .withPopulateMetaFields(false)
+ .withMetaFieldsMode(MetaFieldsMode.FILE_NAME_ONLY)
+ .build();
+ assertEquals(MetaFieldsMode.FILE_NAME_ONLY, cfg.getMetaFieldsMode());
+ assertFalse(cfg.isCommitTimePopulated());
+ assertTrue(cfg.isFileNamePopulated());
+ }
+
+ @Test
+ void commitTimeAndFileNameCombinationBuilds() {
+ HoodieWriteConfig cfg = baseBuilder()
+ .withPopulateMetaFields(false)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME)
+ .build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME, cfg.getMetaFieldsMode());
+ assertTrue(cfg.isCommitTimePopulated());
+ assertTrue(cfg.isFileNamePopulated());
+ }
+
+ @Test
+ void modeOverridesContradictingLegacyBoolean() {
+ HoodieWriteConfig config = baseBuilder()
+ .withPopulateMetaFields(true)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, config.getMetaFieldsMode());
+ assertFalse(config.populateMetaFields());
+ }
+
+ @Test
+ void restatingTheDerivedBooleanIsAccepted() {
+ // Restating what the mode already implies is a coherent, if redundant, request.
+ HoodieWriteConfig selective = baseBuilder()
+ .withPopulateMetaFields(false)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, selective.getMetaFieldsMode());
+ assertFalse(selective.populateMetaFields());
+
+ HoodieWriteConfig all = baseBuilder()
+ .withPopulateMetaFields(true)
+ .withMetaFieldsMode(MetaFieldsMode.ALL)
+ .build();
+ assertEquals(MetaFieldsMode.ALL, all.getMetaFieldsMode());
+ assertTrue(all.populateMetaFields());
+ }
+
+ @Test
+ void modePrecedenceIsIndependentOfBuilderOrder() {
+ HoodieWriteConfig modeFirst = baseBuilder()
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .withPopulateMetaFields(true)
+ .build();
+ HoodieWriteConfig modeLast = baseBuilder()
+ .withPopulateMetaFields(true)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .build();
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, modeFirst.getMetaFieldsMode());
+ assertFalse(modeFirst.populateMetaFields());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, modeLast.getMetaFieldsMode());
+ assertFalse(modeLast.populateMetaFields());
+ }
+
+ @Test
+ void everyModeOverridesItsContradictingBooleanInBothOrders() {
+ // Pinned by construction across all five modes rather than by hand-picked cases.
+ for (MetaFieldsMode mode : MetaFieldsMode.values()) {
+ boolean contradicting = !mode.toLegacyPopulateMetaFields();
+
+ HoodieWriteConfig modeLast =
+ baseBuilder().withPopulateMetaFields(contradicting).withMetaFieldsMode(mode).build();
+ HoodieWriteConfig modeFirst =
+ baseBuilder().withMetaFieldsMode(mode).withPopulateMetaFields(contradicting).build();
+ assertEquals(mode, modeLast.getMetaFieldsMode());
+ assertEquals(mode.toLegacyPopulateMetaFields(), modeLast.populateMetaFields());
+ assertEquals(mode, modeFirst.getMetaFieldsMode());
+ assertEquals(mode.toLegacyPopulateMetaFields(), modeFirst.populateMetaFields());
+
+ // And the derived value is what lands when the boolean is left alone.
+ HoodieWriteConfig unstated = baseBuilder().withMetaFieldsMode(mode).build();
+ assertEquals(Boolean.toString(mode.toLegacyPopulateMetaFields()),
+ unstated.getStringOrDefault(HoodieTableConfig.POPULATE_META_FIELDS),
+ "the derived boolean must be persisted for " + mode);
+ assertEquals(mode, unstated.getMetaFieldsMode());
+ }
+ }
+
+ @Test
+ void unsetModeLeavesTheLegacyBooleanAlone() {
+ // The derivation must only fire when a mode is actually set, or it would clobber the legacy
+ // boolean for the many callers that never mention the mode at all.
+ HoodieWriteConfig cfg = baseBuilder().withPopulateMetaFields(false).build();
+ assertEquals("false", cfg.getStringOrDefault(HoodieTableConfig.POPULATE_META_FIELDS));
+ assertEquals(MetaFieldsMode.NONE, cfg.getMetaFieldsMode());
+
+ HoodieWriteConfig dflt = baseBuilder().build();
+ assertEquals(MetaFieldsMode.ALL, dflt.getMetaFieldsMode());
+ }
+
+ @Test
+ void explicitAllModeOverridesLegacyFalse() {
+ HoodieWriteConfig config = baseBuilder()
+ .withPopulateMetaFields(false)
+ .withMetaFieldsMode(MetaFieldsMode.ALL)
+ .build();
+
+ assertEquals(MetaFieldsMode.ALL, config.getMetaFieldsMode());
+ assertTrue(config.populateMetaFields());
+ }
+
+ @Test
+ void noneModeWithExplicitBuildIsStillNone() {
+ HoodieWriteConfig cfg = baseBuilder()
+ .withPopulateMetaFields(false)
+ .withMetaFieldsMode(MetaFieldsMode.NONE)
+ .build();
+ assertEquals(MetaFieldsMode.NONE, cfg.getMetaFieldsMode());
+ assertFalse(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ }
+
+ @Test
+ void legacyBooleanIsUsedWhenModeIsAbsent() {
+ // Backward compat: tables written before hoodie.meta.fields.mode existed keep their behavior.
+ HoodieWriteConfig allCfg = baseBuilder().withPopulateMetaFields(true).build();
+ assertEquals(MetaFieldsMode.ALL, allCfg.getMetaFieldsMode());
+
+ HoodieWriteConfig noneCfg = baseBuilder().withPopulateMetaFields(false).build();
+ assertEquals(MetaFieldsMode.NONE, noneCfg.getMetaFieldsMode());
+ }
+
+ @Test
+ void rejectsSelectiveModeOnMergeOnRead() {
+ // Selective modes are CoW-only until the MoR log-write path honors them.
+ HoodieWriteConfig.Builder builder = baseBuilder()
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .withProps(mergeOnReadProps());
+ IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, builder::build);
+ assertTrue(ex.getMessage().contains("hoodie.meta.fields.mode"),
+ "exception must name the mode property: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains("COPY_ON_WRITE"),
+ "exception must explain the CoW-only restriction: " + ex.getMessage());
+ }
+
+ @Test
+ void allowsAllAndNoneOnMergeOnRead() {
+ // Only the selective modes are restricted — the two legacy-equivalent modes stay available.
+ assertEquals(MetaFieldsMode.ALL, baseBuilder()
+ .withMetaFieldsMode(MetaFieldsMode.ALL)
+ .withProps(mergeOnReadProps())
+ .build().getMetaFieldsMode());
+ assertEquals(MetaFieldsMode.NONE, baseBuilder()
+ .withMetaFieldsMode(MetaFieldsMode.NONE)
+ .withProps(mergeOnReadProps())
+ .build().getMetaFieldsMode());
+ }
+
+ /**
+ * The builder treats the mode as authoritative regardless of whether it arrived through inherited
+ * properties or a direct setter, and rewrites the legacy boolean instead of rejecting the config.
+ */
+ @Test
+ void inheritedModeDoesNotConflictWithAnExplicitBoolean() {
+ Properties inherited = new Properties();
+ inherited.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.ALL.name());
+
+ HoodieWriteConfig config = baseBuilder()
+ .withProperties(inherited)
+ .withPopulateMetaFields(false)
+ .build();
+
+ assertEquals(MetaFieldsMode.ALL, config.getMetaFieldsMode());
+ assertTrue(config.populateMetaFields());
+ }
+
+ /**
+ * The mirror case: an inherited boolean must not veto an explicitly-stated mode.
+ *
+ * <p>An upgraded table keeps {@code hoodie.populate.meta.fields=true} on disk alongside the new
+ * mode, so a caller stating {@code NONE} on a config that inherited those props would otherwise be
+ * rejected in the other direction.
+ */
+ @Test
+ void inheritedBooleanDoesNotConflictWithAnExplicitMode() {
+ Properties inherited = new Properties();
+ inherited.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "true");
+
+ HoodieWriteConfig config = baseBuilder()
+ .withProperties(inherited)
+ .withMetaFieldsMode(MetaFieldsMode.NONE)
+ .build();
+
+ assertEquals(MetaFieldsMode.NONE, config.getMetaFieldsMode(),
+ "an explicitly-stated mode must override an inherited boolean, not throw");
+ assertFalse(config.populateMetaFields());
+ }
+
+ /**
+ * The shape both bootstrap paths use when building the table.
+ *
+ * <p>{@code BootstrapExecutor} and {@code BootstrapExecutorUtils} read the deprecated boolean out of
+ * the props to hand to {@code TableBuilder}. Using the two-argument {@code getBoolean} there returns
+ * a primitive, so an unstated boolean arrives as the {@code true} default and contradicts an explicit
+ * selective mode -- every bootstrap with {@code hoodie.meta.fields.mode=COMMIT_TIME_ONLY} or
+ * {@code NONE} would be rejected at table creation. Passing null when unstated is what lets the mode
+ * stand on its own.
+ */
+ @Test
+ void unstatedBooleanFromPropsDoesNotContradictAnExplicitMode() {
+ TypedProperties props = new TypedProperties();
+ props.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+
+ // What the bootstrap paths now do: null when the caller never mentioned the boolean.
+ Boolean populate = props.containsKey(HoodieTableConfig.POPULATE_META_FIELDS.key())
+ ? props.getBoolean(HoodieTableConfig.POPULATE_META_FIELDS.key()) : null;
+ assertNull(populate, "an unstated boolean must arrive as null, not the true default");
+
+ HoodieWriteConfig config = baseBuilder()
+ .withProperties(props)
+ .build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, config.getMetaFieldsMode());
+ assertFalse(config.populateMetaFields(),
+ "COMMIT_TIME_ONLY does not populate the record key, so the derived boolean is false");
+ }
+}
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/io/TestSortedAndChangeLogMergeHandles.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/io/TestSortedAndChangeLogMergeHandles.java
index 784e3c1edba9..d5731ab37ba6 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/io/TestSortedAndChangeLogMergeHandles.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/io/TestSortedAndChangeLogMergeHandles.java
@@ -28,6 +28,7 @@ import org.apache.hudi.common.model.HoodieFileFormat;
import org.apache.hudi.common.model.HoodieKey;
import org.apache.hudi.common.model.HoodieOperation;
import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.table.HoodieTableMetaClient;
@@ -280,6 +281,7 @@ public class TestSortedAndChangeLogMergeHandles {
when(metaClient.getTableConfig()).thenReturn(tableConfig);
when(metaClient.getIndexMetadata()).thenReturn(Option.empty());
when(tableConfig.getTableVersion()).thenReturn(HoodieTableVersion.TEN);
+ when(tableConfig.getMetaFieldsMode()).thenReturn(MetaFieldsMode.ALL);
when(tableConfig.getRecordMergeMode()).thenReturn(RecordMergeMode.COMMIT_TIME_ORDERING);
when(tableConfig.getPayloadClassIfPresent()).thenReturn(Option.empty());
when(tableConfig.getPartitionMetafileFormat()).thenReturn(Option.empty());
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestNineToTenUpgradeHandler.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestNineToTenUpgradeHandler.java
new file mode 100644
index 000000000000..23ebd9376227
--- /dev/null
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestNineToTenUpgradeHandler.java
@@ -0,0 +1,86 @@
+/*
+ * 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.hudi.table.upgrade;
+
+import org.apache.hudi.common.engine.HoodieEngineContext;
+import org.apache.hudi.common.model.MetaFieldsMode;
+import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.table.HoodieTable;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Version 9 tables predate {@code hoodie.meta.fields.mode}, so the upgrade records the value
+ * derived from the deprecated {@code hoodie.populate.meta.fields} boolean. This makes an upgraded
+ * table describe its meta-field layout the same way a freshly created version 10 table does,
+ * instead of relying on the legacy fallback at every read.
+ */
+class TestNineToTenUpgradeHandler {
+
+ private static SupportsUpgradeDowngrade helperFor(MetaFieldsMode resolvedMode) {
+ HoodieTable table = mock(HoodieTable.class, RETURNS_DEEP_STUBS);
+ HoodieTableMetaClient metaClient = mock(HoodieTableMetaClient.class, RETURNS_DEEP_STUBS);
+ HoodieTableConfig tableConfig = mock(HoodieTableConfig.class);
+ when(tableConfig.getMetaFieldsMode()).thenReturn(resolvedMode);
+ when(metaClient.getTableConfig()).thenReturn(tableConfig);
+ when(table.getMetaClient()).thenReturn(metaClient);
+
+ SupportsUpgradeDowngrade helper = mock(SupportsUpgradeDowngrade.class);
+ when(helper.getTable(any(HoodieWriteConfig.class), any(HoodieEngineContext.class))).thenReturn(table);
+ return helper;
+ }
+
+ @ParameterizedTest
+ @CsvSource({"ALL", "NONE"})
+ void upgradeRecordsTheModeDerivedFromTheLegacyBoolean(String modeName) {
+ MetaFieldsMode expected = MetaFieldsMode.valueOf(modeName);
+ UpgradeDowngrade.TableConfigChangeSet changeSet = new NineToTenUpgradeHandler().upgrade(
+ mock(HoodieWriteConfig.class), mock(HoodieEngineContext.class), "001", helperFor(expected));
+
+ assertEquals(Collections.singleton(HoodieTableConfig.POPULATE_META_FIELDS),
+ changeSet.propertiesToDelete());
+ assertEquals(1, changeSet.propertiesToUpdate().size());
+ assertEquals(expected.name(),
+ changeSet.propertiesToUpdate().get(HoodieTableConfig.META_FIELDS_MODE));
+ }
+
+ @Test
+ void upgradeRemovesTheLegacyBoolean() {
+ UpgradeDowngrade.TableConfigChangeSet changeSet = new NineToTenUpgradeHandler().upgrade(
+ mock(HoodieWriteConfig.class), mock(HoodieEngineContext.class), "001",
+ helperFor(MetaFieldsMode.NONE));
+
+ assertFalse(changeSet.propertiesToUpdate().containsKey(HoodieTableConfig.POPULATE_META_FIELDS));
+ assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.POPULATE_META_FIELDS));
+ }
+}
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestTenToNineDowngradeHandler.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestTenToNineDowngradeHandler.java
index 12faa9736930..d7175e9f9a07 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestTenToNineDowngradeHandler.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestTenToNineDowngradeHandler.java
@@ -18,33 +18,201 @@
package org.apache.hudi.table.upgrade;
+import org.apache.hudi.common.engine.HoodieEngineContext;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.table.HoodieTableVersion;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.exception.HoodieUpgradeDowngradeException;
+import org.apache.hudi.table.HoodieTable;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+/**
+ * Version 9 cannot interpret {@code hoodie.meta.fields.mode}, so the downgrade deletes it and writes
+ * {@code hoodie.populate.meta.fields} back from it. The write-back is the load-bearing part:
+ * {@code POPULATE_META_FIELDS} defaults to {@code true}, so deleting the mode without restating the
+ * boolean would silently downgrade the table to {@code ALL}.
+ *
+ * <p>Every mode downgrades, including the selective ones: they already persist the boolean as
+ * {@code false}, so restating it is exactly what version 9 should see. The table under-claims --
+ * files keep their populated meta columns while the table advertises none -- which is the safe
+ * direction. It is not reversible, and that is asserted here rather than left implicit.
+ */
class TestTenToNineDowngradeHandler {
+ private static SupportsUpgradeDowngrade helperFor(MetaFieldsMode resolvedMode) {
+ return helperFor(resolvedMode, HoodieTableVersion.SIX);
+ }
+
+ private static SupportsUpgradeDowngrade helperFor(MetaFieldsMode resolvedMode,
+ HoodieTableVersion initialVersion) {
+ HoodieTable table = mock(HoodieTable.class, RETURNS_DEEP_STUBS);
+ HoodieTableMetaClient metaClient = mock(HoodieTableMetaClient.class, RETURNS_DEEP_STUBS);
+ HoodieTableConfig tableConfig = mock(HoodieTableConfig.class);
+ when(tableConfig.getMetaFieldsMode()).thenReturn(resolvedMode);
+ when(tableConfig.getTableInitialVersion()).thenReturn(initialVersion);
+ when(metaClient.getTableConfig()).thenReturn(tableConfig);
+ when(table.getMetaClient()).thenReturn(metaClient);
+
+ SupportsUpgradeDowngrade helper = mock(SupportsUpgradeDowngrade.class);
+ when(helper.getTable(any(HoodieWriteConfig.class), any(HoodieEngineContext.class))).thenReturn(table);
+ return helper;
+ }
+
+ private static UpgradeDowngrade.TableConfigChangeSet downgradeWith(MetaFieldsMode tableMode) {
+ return downgradeWith(tableMode, HoodieTableVersion.SIX, false);
+ }
+
+ /**
+ * @param tableMode what the table config reports
+ * @param initialVersion the version the table was created at
+ * @param allowRetention whether the operator opted in to retaining a selective mode
+ */
+ private static UpgradeDowngrade.TableConfigChangeSet downgradeWith(MetaFieldsMode tableMode,
+ HoodieTableVersion initialVersion,
+ boolean allowRetention) {
+ HoodieWriteConfig writeConfig = mock(HoodieWriteConfig.class);
+ when(writeConfig.getBooleanOrDefault(
+ HoodieWriteConfig.ALLOW_META_FIELDS_MODE_RETENTION_ON_DOWNGRADE)).thenReturn(allowRetention);
+ return new TenToNineDowngradeHandler().downgrade(
+ writeConfig, mock(HoodieEngineContext.class), "001", helperFor(tableMode, initialVersion));
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ // Only ALL populates every meta column, so it is the only mode that maps back to true.
+ "ALL, true",
+ "NONE, false",
+ })
+ void downgradeWritesTheLegacyBooleanDerivedFromTheMode(String modeName, boolean expectedBoolean) {
+ UpgradeDowngrade.TableConfigChangeSet changeSet =
+ downgradeWith(MetaFieldsMode.valueOf(modeName));
+
+ assertEquals(String.valueOf(expectedBoolean),
+ changeSet.propertiesToUpdate().get(HoodieTableConfig.POPULATE_META_FIELDS),
+ "version 9 only understands the boolean, so it must be restated from the mode");
+ // The mode itself goes away; the boolean must not, or the table resolves to the `true` default.
+ assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE));
+ assertFalse(changeSet.propertiesToDelete().contains(HoodieTableConfig.POPULATE_META_FIELDS));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"COMMIT_TIME_ONLY", "FILE_NAME_ONLY", "COMMIT_TIME_AND_FILE_NAME"})
+ void downgradeRejectsASelectiveModeOnATableBornAtTenWithoutOptIn(String modeName) {
+ // Created at version 10, so no version that predates the mode has ever read this table. Dropping
+ // the mode would collapse it to NONE irreversibly; retaining it leaves a property version 9 does
+ // not formally understand. Neither is ours to pick silently.
+ MetaFieldsMode mode = MetaFieldsMode.valueOf(modeName);
+ HoodieUpgradeDowngradeException ex = assertThrows(HoodieUpgradeDowngradeException.class,
+ () -> downgradeWith(mode, HoodieTableVersion.TEN, false));
+ assertTrue(ex.getMessage().contains(
+ HoodieWriteConfig.ALLOW_META_FIELDS_MODE_RETENTION_ON_DOWNGRADE.key()),
+ "the message must name the opt-in flag: " + ex.getMessage());
+ }
+
+ @ParameterizedTest
+ @CsvSource({"COMMIT_TIME_ONLY", "FILE_NAME_ONLY", "COMMIT_TIME_AND_FILE_NAME"})
+ void downgradeRetainsASelectiveModeOnATableThatPredatesTen(String modeName) {
+ // Created before version 10, so it existed under a version with no mode property and is simply
+ // being returned to a state it has already lived in. No opt-in required.
+ MetaFieldsMode mode = MetaFieldsMode.valueOf(modeName);
+ UpgradeDowngrade.TableConfigChangeSet changeSet =
+ downgradeWith(mode, HoodieTableVersion.SIX, false);
+
+ assertFalse(changeSet.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE),
+ "a table that predates version 10 keeps its mode through a downgrade");
+ assertEquals("false",
+ changeSet.propertiesToUpdate().get(HoodieTableConfig.POPULATE_META_FIELDS),
+ "the legacy boolean is still written so an unaware reader under-claims rather than over-claims");
+ }
+
+ @ParameterizedTest
+ @CsvSource({"COMMIT_TIME_ONLY", "FILE_NAME_ONLY", "COMMIT_TIME_AND_FILE_NAME"})
+ void downgradeRetainsASelectiveModeBornAtTenWhenTheOperatorOptsIn(String modeName) {
+ MetaFieldsMode mode = MetaFieldsMode.valueOf(modeName);
+ UpgradeDowngrade.TableConfigChangeSet changeSet =
+ downgradeWith(mode, HoodieTableVersion.TEN, true);
+
+ assertFalse(changeSet.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE));
+ assertEquals("false",
+ changeSet.propertiesToUpdate().get(HoodieTableConfig.POPULATE_META_FIELDS));
+ }
+
@Test
- void testDowngradeRemovesStorageLayoutOnly() {
+ void retainedSelectiveModeSurvivesAReUpgrade() {
+ // The point of retaining it: a later re-upgrade finds the mode intact rather than deriving NONE
+ // from the boolean. This is what the earlier drop-and-warn behaviour could not offer.
+ UpgradeDowngrade.TableConfigChangeSet down =
+ downgradeWith(MetaFieldsMode.COMMIT_TIME_ONLY, HoodieTableVersion.SIX, false);
+ assertFalse(down.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE));
+
+ UpgradeDowngrade.TableConfigChangeSet up = new NineToTenUpgradeHandler().upgrade(
+ mock(HoodieWriteConfig.class), mock(HoodieEngineContext.class), "001",
+ helperFor(MetaFieldsMode.COMMIT_TIME_ONLY));
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY.name(),
+ up.propertiesToUpdate().get(HoodieTableConfig.META_FIELDS_MODE),
+ "the retained mode must still be COMMIT_TIME_ONLY after upgrading again");
+ }
+
+ @Test
+ void downgradeRemovesStorageLayoutAndMetaFieldsMode() {
+ UpgradeDowngrade.TableConfigChangeSet changeSet = downgradeWith(MetaFieldsMode.ALL);
+
+ assertEquals(2, changeSet.propertiesToDelete().size());
+ assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.TABLE_STORAGE_LAYOUT));
+ assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE));
+ }
+
+ @Test
+ void downgradeWithoutHelperLeavesTheLegacyBooleanUntouched() {
+ // Some callers drive the change set without a helper, so the table config is unreachable and the
+ // mode cannot be read. Deleting the mode is still right, but the boolean must not be guessed —
+ // writing a value derived from an assumed mode is how a table ends up claiming absent columns.
UpgradeDowngrade.TableConfigChangeSet changeSet =
new TenToNineDowngradeHandler().downgrade(null, null, null, null);
assertTrue(changeSet.propertiesToUpdate().isEmpty());
- assertEquals(1, changeSet.propertiesToDelete().size());
- assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.TABLE_STORAGE_LAYOUT));
+ assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE));
+ assertFalse(changeSet.propertiesToDelete().contains(HoodieTableConfig.POPULATE_META_FIELDS));
}
@Test
- void testTenToNineDowngradeRouteIsSupported() {
+ void tenToNineDowngradeRouteIsSupported() {
UpgradeDowngrade.TableConfigChangeSet changeSet =
new UpgradeDowngrade(null, null, null, null)
.downgrade(HoodieTableVersion.TEN, HoodieTableVersion.NINE, "001");
- assertEquals(1, changeSet.propertiesToDelete().size());
+ assertEquals(2, changeSet.propertiesToDelete().size());
assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.TABLE_STORAGE_LAYOUT));
+ assertTrue(changeSet.propertiesToDelete().contains(HoodieTableConfig.META_FIELDS_MODE));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"ALL", "NONE"})
+ void upgradeDowngradeRoundTripIsLosslessForNonSelectiveModes(String modeName) {
+ MetaFieldsMode mode = MetaFieldsMode.valueOf(modeName);
+
+ UpgradeDowngrade.TableConfigChangeSet up = new NineToTenUpgradeHandler().upgrade(
+ mock(HoodieWriteConfig.class), mock(HoodieEngineContext.class), "001", helperFor(mode));
+ UpgradeDowngrade.TableConfigChangeSet down = downgradeWith(mode);
+
+ // Up records the mode and removes the boolean; down restores the boolean and drops the mode. A
+ // v9 table therefore reads back the same meta-field layout it started with.
+ assertEquals(mode.name(), up.propertiesToUpdate().get(HoodieTableConfig.META_FIELDS_MODE));
+ assertEquals(String.valueOf(mode.toLegacyPopulateMetaFields()),
+ down.propertiesToUpdate().get(HoodieTableConfig.POPULATE_META_FIELDS));
}
}
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/utils/HoodieWriterClientTestHarness.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/utils/HoodieWriterClientTestHarness.java
index 8200d7d48e96..eb42fd1acaab 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/utils/HoodieWriterClientTestHarness.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/utils/HoodieWriterClientTestHarness.java
@@ -43,6 +43,7 @@ import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieReplaceCommitMetadata;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.model.IOType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.WriteConcurrencyMode;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.schema.HoodieSchema;
@@ -197,6 +198,42 @@ public abstract class HoodieWriterClientTestHarness extends HoodieCommonTestHarn
return properties;
}
+ /**
+ * The key-generator properties a clustering writer needs, with the meta-fields boolean following the
+ * flag the table was created with.
+ *
+ * <p>This is {@link #getPropertiesForKeyGen(boolean)} with one property overridden, and the
+ * distinction matters. The key-generator properties themselves are needed on both paths -- the
+ * reader context resolves record keys through them, and dropping them fails with "No record keys
+ * specified and meta fields are not populated". What must follow the flag is only
+ * {@code populate.meta.fields}, since the writer has to agree with the table about which meta
+ * columns hold values.
+ */
+ protected static Properties keyGenPropsWithMetaFields(boolean populateMetaFields) {
+ Properties props = getPropertiesForKeyGen(false);
+ props.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), String.valueOf(populateMetaFields));
+ return props;
+ }
+
+ /**
+ * Align the fixture table's meta-fields setting with what the writer under test is about to ask for.
+ *
+ * <p>The table is created once per test by {@code initMetaClient()}, which always populates all meta
+ * fields. A test that then builds a {@code populate.meta.fields=false} writer is asking to narrow the
+ * table on the fly, which is rejected -- meta columns are physical, so a writer may not disagree with
+ * the table about which of them hold values. Tests that legitimately want a non-populated table state
+ * that on the table itself, here, rather than only on the writer.
+ */
+ protected void alignTableWithPopulateMetaFields(boolean populateMetaFields) throws IOException {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+ props.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), String.valueOf(populateMetaFields));
+ props.put(HoodieTableConfig.META_FIELDS_MODE.key(),
+ (populateMetaFields ? MetaFieldsMode.ALL : MetaFieldsMode.NONE).name());
+ HoodieTableConfig.update(metaClient.getStorage(), metaClient.getMetaPath(), props);
+ metaClient = HoodieTableMetaClient.reload(metaClient);
+ }
+
protected Properties getPropertiesForMetadataTable() {
Properties properties = new Properties();
properties.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
@@ -890,7 +927,7 @@ public abstract class HoodieWriterClientTestHarness extends HoodieCommonTestHarn
HoodieWriteConfig config = getConfigBuilder(HoodieFailedWritesCleaningPolicy.LAZY)
.withClusteringConfig(clusteringConfig)
- .withProps(getPropertiesForKeyGen()).build();
+ .withProps(keyGenPropsWithMetaFields(populateMetaFields)).build();
HoodieWriteMetadata<List<WriteStatus>> clusterMetadata =
performClustering(clusteringConfig, populateMetaFields, completeClustering, validatorClasses, sqlQueryForEqualityValidation,
sqlQueryForSingleResultValidation, allRecords.getLeft(), transformWriteMetadataFn, createKeyGeneratorFn);
@@ -901,10 +938,15 @@ public abstract class HoodieWriterClientTestHarness extends HoodieCommonTestHarn
assertEquals(insertedFileIds, replacedFileIds);
}
if (completeClustering) {
- String clusteringCommitTime = createMetaClient().reloadActiveTimeline().getCompletedReplaceTimeline()
- .getReverseOrderedInstants().findFirst().get().requestedTime();
- verifyRecordsWritten(clusteringCommitTime, populateMetaFields, allRecords.getLeft().getLeft(),
- clusterMetadata.getWriteStatuses(), config, createKeyGeneratorFn.apply(config));
+ if (populateMetaFields) {
+ verifyRecordsWrittenWithPreservedMetadata(new HashSet<>(allRecords.getLeft().getRight()),
+ allRecords.getLeft().getLeft(), clusterMetadata.getWriteStatuses());
+ } else {
+ String clusteringCommitTime = createMetaClient().reloadActiveTimeline().getCompletedReplaceTimeline()
+ .getReverseOrderedInstants().findFirst().get().requestedTime();
+ verifyRecordsWritten(clusteringCommitTime, false, allRecords.getLeft().getLeft(),
+ clusterMetadata.getWriteStatuses(), config, createKeyGeneratorFn.apply(config));
+ }
}
}
@@ -1021,9 +1063,12 @@ public abstract class HoodieWriterClientTestHarness extends HoodieCommonTestHarn
}
}
- protected void testDeletesWithoutInserts(boolean populateMetaFields, Function transformInputFn, Function transformOutputFn) {
+ protected void testDeletesWithoutInserts(boolean populateMetaFields, Function transformInputFn, Function transformOutputFn) throws IOException {
final String testPartitionPath = "2016/09/26";
final int insertSplitLimit = 100;
+ // The fixture table always populates meta fields; make it agree with the writer built below, which
+ // otherwise asks to narrow an ALL table to NONE.
+ alignTableWithPopulateMetaFields(populateMetaFields);
// setup the small file handling params
HoodieWriteConfig config = getSmallInsertWriteConfig(insertSplitLimit,
TRIP_EXAMPLE_SCHEMA, dataGen.getEstimatedFileSizeInBytes(150), populateMetaFields, populateMetaFields
@@ -1044,7 +1089,11 @@ public abstract class HoodieWriterClientTestHarness extends HoodieCommonTestHarn
testInsertTwoBatches(true, createBrokenClusteringClientFn);
HoodieWriteConfig config = getConfigBuilder(HoodieFailedWritesCleaningPolicy.LAZY)
.withClusteringConfig(clusteringConfig)
- .withProps(getPropertiesForKeyGen()).build();
+ // The table above was created with meta fields populated, so this writer must agree with it.
+ // Only the meta-fields property, for the reason given in testClustering: the rest of the
+ // getPropertiesForKeyGen bundle was never present on this path and changes clustering
+ // behaviour beyond what the meta-fields check requires.
+ .withProps(keyGenPropsWithMetaFields(true)).build();
dataGen = new HoodieTestDataGenerator(new String[] {"2015/03/16"});
generateInsertsAndCommit(config, transformInputFn, transformOutputFn);
HoodieTableMetaClient metaClient = createMetaClient();
@@ -1166,8 +1215,11 @@ public abstract class HoodieWriterClientTestHarness extends HoodieCommonTestHarn
addConfigsForPopulateMetaFields(cfgBuilder, populateMetaFields);
HoodieWriteConfig hoodieWriteConfig = cfgBuilder.withMergeAllowDuplicateOnInserts(true).withTimelineLayoutVersion(VERSION_0).build();
- HoodieTableMetaClient.newTableBuilder()
- .fromMetaClient(metaClient)
+ // addConfigsForPopulateMetaFields may recreate the table with virtual-key fields. Reload before
+ // using its properties as the source for the timeline-layout rewrite so those fields are kept.
+ metaClient = HoodieTableMetaClient.reload(metaClient);
+ metaClient = HoodieTableMetaClient.newTableBuilder()
+ .fromProperties(metaClient.getTableConfig().getProps())
.setTimelineLayoutVersion(VERSION_0)
.initTable(metaClient.getStorageConf().newInstance(), metaClient.getBasePath());
diff --git a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataFileWriterFactory.java b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataFileWriterFactory.java
index 18337b3a8115..b75aeaede82e 100644
--- a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataFileWriterFactory.java
+++ b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowDataFileWriterFactory.java
@@ -23,8 +23,8 @@ import org.apache.hudi.common.config.HoodieConfig;
import org.apache.hudi.common.config.HoodieParquetConfig;
import org.apache.hudi.common.config.HoodieStorageConfig;
import org.apache.hudi.common.engine.TaskContextSupplier;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
-import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.ReflectionUtils;
import org.apache.hudi.common.util.collection.Pair;
@@ -95,7 +95,7 @@ public class HoodieRowDataFileWriterFactory extends HoodieFileWriterFactory {
HoodieConfig config,
HoodieSchema schema,
TaskContextSupplier taskContextSupplier) throws IOException {
- boolean populateMetaFields = config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ boolean populateMetaFields = MetaFieldsMode.resolve(config).toLegacyPopulateMetaFields();
boolean withOperation = config.getBooleanOrDefault(HoodieWriteConfig.ALLOW_OPERATION_METADATA_FIELD);
Pair<StorageConfiguration, HoodieConfig> injectedConfigs = HoodieParquetConfigInjector.applyConfigInjector(storagePath, storage.getConf(), config);
@@ -120,9 +120,10 @@ public class HoodieRowDataFileWriterFactory extends HoodieFileWriterFactory {
HoodieConfig config,
HoodieSchema schema,
TaskContextSupplier taskContextSupplier) {
- boolean populateMetaFields = config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(config);
+ boolean populateMetaFields = metaFieldsMode.toLegacyPopulateMetaFields();
boolean withOperation = config.getBooleanOrDefault(HoodieWriteConfig.ALLOW_OPERATION_METADATA_FIELD);
- Option<org.apache.hudi.common.bloom.BloomFilter> bloomFilter = enableBloomFilter(populateMetaFields, config)
+ Option<org.apache.hudi.common.bloom.BloomFilter> bloomFilter = enableBloomFilter(metaFieldsMode, config)
? Option.of(createBloomFilter(config)) : Option.empty();
RowType rowType = HoodieSchemaConverter.convertToRowType(schema);
return new HoodieRowDataLanceWriter(
diff --git a/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/functional/TestHoodieJavaClientOnCopyOnWriteStorage.java b/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/functional/TestHoodieJavaClientOnCopyOnWriteStorage.java
index 0d2daf9fe34c..cd6264c72c39 100644
--- a/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/functional/TestHoodieJavaClientOnCopyOnWriteStorage.java
+++ b/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/functional/TestHoodieJavaClientOnCopyOnWriteStorage.java
@@ -400,7 +400,7 @@ public class TestHoodieJavaClientOnCopyOnWriteStorage extends HoodieJavaClientTe
*/
@ParameterizedTest
@ValueSource(booleans = {true, false})
- public void testDeletesWithoutInserts(boolean populateMetaFields) {
+ public void testDeletesWithoutInserts(boolean populateMetaFields) throws IOException {
testDeletesWithoutInserts(populateMetaFields, IDENTITY, IDENTITY);
}
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/common/model/HoodieSparkRecord.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/common/model/HoodieSparkRecord.java
index bf680bb2015e..de30e4ef94a6 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/common/model/HoodieSparkRecord.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/common/model/HoodieSparkRecord.java
@@ -65,7 +65,6 @@ import java.util.Properties;
import scala.Function1;
import static org.apache.hudi.BaseSparkInternalRecordContext.getFieldValueFromInternalRowAsJava;
-import static org.apache.hudi.common.table.HoodieTableConfig.POPULATE_META_FIELDS;
import static org.apache.spark.sql.HoodieInternalRowUtils.getCachedUnsafeProjection;
import static org.apache.spark.sql.types.DataTypes.StringType;
@@ -233,7 +232,17 @@ public class HoodieSparkRecord extends HoodieRecord<InternalRow> {
public HoodieRecord updateMetaField(HoodieSchema recordSchema, int ordinal, String value) {
StructType structType = HoodieInternalRowUtils.getCachedSchema(recordSchema);
HoodieInternalRow updatableRow = wrapIntoUpdatableOverlay(this.data, structType);
- updatableRow.update(ordinal, CatalystTypeConverters.convertToCatalyst(value));
+ if (value == null) {
+ // HoodieInternalRow#update cannot take a null: it accepts only UTF8String or String and
+ // otherwise reports the offending type via value.getClass(), which NPEs on a null before the
+ // exception is built. Clearing a meta column is a legitimate request -- a selective
+ // hoodie.meta.fields.mode leaves _hoodie_file_name unpopulated, and a record copied forward
+ // from a file written under ALL must have the stale value cleared rather than carried over --
+ // so route it through setNullAt, which handles the meta-field range correctly.
+ updatableRow.setNullAt(ordinal);
+ } else {
+ updatableRow.update(ordinal, CatalystTypeConverters.convertToCatalyst(value));
+ }
return new HoodieSparkRecord(getKey(), updatableRow, structType, getOperation(), this.currentLocation, this.newLocation, false);
}
@@ -296,9 +305,11 @@ public class HoodieSparkRecord extends HoodieRecord<InternalRow> {
StructType structType = HoodieInternalRowUtils.getCachedSchema(recordSchema);
String key;
String partition;
- boolean populateMetaFields = Boolean.parseBoolean(props.getOrDefault(POPULATE_META_FIELDS.key(),
- POPULATE_META_FIELDS.defaultValue().toString()).toString());
- if (!populateMetaFields && keyGen.isPresent()) {
+ // Resolve via hoodie.meta.fields.mode — reading the deprecated boolean alone would report
+ // "populated" for a selective-mode table (whose _hoodie_record_key column is null), sending us
+ // down the meta-column branch below and NPE-ing on the null ordinal.
+ boolean recordKeyPopulated = MetaFieldsMode.resolve(props).isRecordKeyPopulated();
+ if (!recordKeyPopulated && keyGen.isPresent()) {
SparkKeyGeneratorInterface keyGenerator = (SparkKeyGeneratorInterface) keyGen.get();
key = keyGenerator.getRecordKey(data, structType).toString();
partition = keyGenerator.getPartitionPath(data, structType).toString();
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkFileWriterFactory.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkFileWriterFactory.java
index 67949fee472e..53d40b6f1044 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkFileWriterFactory.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkFileWriterFactory.java
@@ -22,8 +22,8 @@ import org.apache.hudi.common.bloom.BloomFilter;
import org.apache.hudi.common.config.HoodieConfig;
import org.apache.hudi.common.config.HoodieStorageConfig;
import org.apache.hudi.common.engine.TaskContextSupplier;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
-import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.ReflectionUtils;
import org.apache.hudi.common.util.collection.Pair;
@@ -56,7 +56,7 @@ public class HoodieSparkFileWriterFactory extends HoodieFileWriterFactory {
protected HoodieFileWriter newParquetFileWriter(
String instantTime, StoragePath path, HoodieConfig config, HoodieSchema schema,
TaskContextSupplier taskContextSupplier) throws IOException {
- boolean populateMetaFields = config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(config);
Pair<StorageConfiguration, HoodieConfig> injectedConfigs = HoodieParquetConfigInjector.applyConfigInjector(path, storage.getConf(), config);
StorageConfiguration storageConfiguration = injectedConfigs.getLeft();
@@ -69,7 +69,7 @@ public class HoodieSparkFileWriterFactory extends HoodieFileWriterFactory {
}
HoodieRowParquetWriteSupport writeSupport = getHoodieRowParquetWriteSupport(storageConfiguration, schema,
- hoodieConfig, enableBloomFilter(populateMetaFields, hoodieConfig));
+ hoodieConfig, enableBloomFilter(metaFieldsMode, hoodieConfig));
HoodieRowParquetConfig parquetConfig = new HoodieRowParquetConfig(writeSupport,
CompressionCodecName.fromConf(compressionCodecName),
hoodieConfig.getIntOrDefault(HoodieStorageConfig.PARQUET_BLOCK_SIZE),
@@ -80,7 +80,7 @@ public class HoodieSparkFileWriterFactory extends HoodieFileWriterFactory {
hoodieConfig.getBooleanOrDefault(HoodieStorageConfig.PARQUET_DICTIONARY_ENABLED));
parquetConfig.getHadoopConf().addResource(writeSupport.getHadoopConf());
- return new HoodieSparkParquetWriter(path, parquetConfig, instantTime, taskContextSupplier, populateMetaFields);
+ return new HoodieSparkParquetWriter(path, parquetConfig, instantTime, taskContextSupplier, metaFieldsMode);
}
protected HoodieFileWriter newParquetFileWriter(OutputStream outputStream, HoodieConfig config,
@@ -119,9 +119,10 @@ public class HoodieSparkFileWriterFactory extends HoodieFileWriterFactory {
protected HoodieFileWriter newLanceFileWriter(String instantTime, StoragePath path, HoodieConfig config, HoodieSchema schema,
TaskContextSupplier taskContextSupplier) throws IOException {
HoodieSparkLanceWriter.validateNoVariantColumns(schema);
- boolean populateMetaFields = config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(config);
+ boolean populateMetaFields = metaFieldsMode.toLegacyPopulateMetaFields();
StructType structType = HoodieInternalRowUtils.getCachedSchema(schema);
- boolean enableBloomFilter = enableBloomFilter(populateMetaFields, config);
+ boolean enableBloomFilter = enableBloomFilter(metaFieldsMode, config);
Option<BloomFilter> bloomFilter = enableBloomFilter ? Option.of(createBloomFilter(config)) : Option.empty();
long maxFileSize = config.getLongOrDefault(HoodieStorageConfig.LANCE_MAX_FILE_SIZE);
long allocatorSize = config.getLongOrDefault(HoodieStorageConfig.LANCE_WRITE_ALLOCATOR_SIZE_BYTES);
@@ -144,9 +145,10 @@ public class HoodieSparkFileWriterFactory extends HoodieFileWriterFactory {
@Override
protected HoodieFileWriter newVortexFileWriter(String instantTime, StoragePath path, HoodieConfig config, HoodieSchema schema,
TaskContextSupplier taskContextSupplier) throws IOException {
- boolean populateMetaFields = config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(config);
+ boolean populateMetaFields = metaFieldsMode.toLegacyPopulateMetaFields();
StructType structType = HoodieInternalRowUtils.getCachedSchema(schema);
- boolean enableBloomFilter = enableBloomFilter(populateMetaFields, config);
+ boolean enableBloomFilter = enableBloomFilter(metaFieldsMode, config);
Option<BloomFilter> bloomFilter = enableBloomFilter ? Option.of(createBloomFilter(config)) : Option.empty();
long maxFileSize = config.getLongOrDefault(HoodieStorageConfig.VORTEX_MAX_FILE_SIZE);
long allocatorSize = config.getLongOrDefault(HoodieStorageConfig.VORTEX_WRITE_ALLOCATOR_SIZE_BYTES);
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkParquetWriter.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkParquetWriter.java
index f2ed3831d492..aaf231858405 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkParquetWriter.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/HoodieSparkParquetWriter.java
@@ -21,6 +21,7 @@ package org.apache.hudi.io.storage;
import org.apache.hudi.common.engine.TaskContextSupplier;
import org.apache.hudi.common.model.HoodieKey;
import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.io.hadoop.HoodieBaseParquetWriter;
import org.apache.hudi.io.storage.row.HoodieRowParquetConfig;
import org.apache.hudi.io.storage.row.HoodieRowParquetWriteSupport;
@@ -31,6 +32,7 @@ import org.apache.spark.unsafe.types.UTF8String;
import java.io.IOException;
import java.util.Map;
+import java.util.Objects;
import java.util.function.Function;
import static org.apache.hudi.common.model.HoodieRecord.HoodieMetadataField.COMMIT_SEQNO_METADATA_FIELD;
@@ -44,7 +46,7 @@ public class HoodieSparkParquetWriter extends HoodieBaseParquetWriter<InternalRo
private final UTF8String fileName;
private final UTF8String instantTime;
- private final boolean populateMetaFields;
+ private final MetaFieldsMode metaFieldsMode;
private final HoodieRowParquetWriteSupport writeSupport;
@@ -54,12 +56,12 @@ public class HoodieSparkParquetWriter extends HoodieBaseParquetWriter<InternalRo
HoodieRowParquetConfig parquetConfig,
String instantTime,
TaskContextSupplier taskContextSupplier,
- boolean populateMetaFields) throws IOException {
+ MetaFieldsMode metaFieldsMode) throws IOException {
super(file, parquetConfig);
this.writeSupport = parquetConfig.getWriteSupport();
this.fileName = UTF8String.fromString(file.getName());
this.instantTime = UTF8String.fromString(instantTime);
- this.populateMetaFields = populateMetaFields;
+ this.metaFieldsMode = Objects.requireNonNull(metaFieldsMode, "metaFieldsMode");
this.seqIdGenerator = recordIndex -> {
Integer partitionId = taskContextSupplier.getPartitionIdSupplier().get();
return HoodieRecord.generateSequenceId(instantTime, partitionId, recordIndex);
@@ -68,21 +70,35 @@ public class HoodieSparkParquetWriter extends HoodieBaseParquetWriter<InternalRo
@Override
public void writeRowWithMetadata(HoodieKey key, InternalRow row) throws IOException {
- if (populateMetaFields) {
- UTF8String recordKey = UTF8String.fromString(key.getRecordKey());
- updateRecordMetadata(row, recordKey, key.getPartitionPath(), getWrittenRecordCount());
-
- super.write(row);
- writeSupport.add(recordKey);
- } else {
- super.write(row);
+ switch (metaFieldsMode) {
+ case ALL:
+ UTF8String recordKey = UTF8String.fromString(key.getRecordKey());
+ updateRecordMetadata(row, recordKey, key.getPartitionPath(), getWrittenRecordCount());
+ super.write(row);
+ writeSupport.add(recordKey);
+ break;
+ case NONE:
+ super.write(row);
+ break;
+ default:
+ // Selective mode — populate only the opted-in columns. Record-key column stays null, so
+ // we do NOT register the record key with the write support (bloom filter / RLI hooks are
+ // meaningless without the record-key column).
+ if (metaFieldsMode.isCommitTimePopulated()) {
+ row.update(COMMIT_TIME_METADATA_FIELD.ordinal(), instantTime);
+ }
+ if (metaFieldsMode.isFileNamePopulated()) {
+ row.update(FILENAME_METADATA_FIELD.ordinal(), fileName);
+ }
+ super.write(row);
+ break;
}
}
@Override
public void writeRow(String recordKey, InternalRow row) throws IOException {
super.write(row);
- if (populateMetaFields) {
+ if (metaFieldsMode == MetaFieldsMode.ALL) {
writeSupport.add(UTF8String.fromString(recordKey));
}
}
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowCreateHandle.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowCreateHandle.java
index c6d20eefb582..d5d573d4d89a 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowCreateHandle.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/io/storage/row/HoodieRowCreateHandle.java
@@ -28,6 +28,7 @@ import org.apache.hudi.common.model.HoodieRecordDelegate;
import org.apache.hudi.common.model.HoodieRecordLocation;
import org.apache.hudi.common.model.HoodieWriteStat;
import org.apache.hudi.common.model.IOType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.util.HoodieTimer;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.collection.Pair;
@@ -66,7 +67,7 @@ public class HoodieRowCreateHandle implements Serializable {
private final StoragePath path;
private final String fileId;
- private final boolean populateMetaFields;
+ private final MetaFieldsMode metaFieldsMode;
private final UTF8String fileName;
private final UTF8String commitTime;
@@ -118,7 +119,8 @@ public class HoodieRowCreateHandle implements Serializable {
table.getBaseFileExtension());
this.path = makeNewPath(storage, partitionPath, fileName, writeConfig);
- this.populateMetaFields = writeConfig.populateMetaFields();
+ // Read from the TABLE config, not the write config -- see the note on BaseCreateHandle.
+ this.metaFieldsMode = table.getMetaClient().getTableConfig().getMetaFieldsMode();
this.fileName = UTF8String.fromString(path.getName());
this.commitTime = UTF8String.fromString(instantTime);
this.seqIdGenerator = (id) -> HoodieRecord.generateSequenceId(instantTime, taskPartitionId, id);
@@ -158,10 +160,48 @@ public class HoodieRowCreateHandle implements Serializable {
* @throws IOException
*/
public void write(InternalRow row) throws IOException {
- if (populateMetaFields) {
- writeRow(row);
- } else {
- writeRowNoMetaFields(row);
+ switch (metaFieldsMode) {
+ case ALL:
+ writeRow(row);
+ break;
+ case NONE:
+ writeRowNoMetaFields(row);
+ break;
+ default:
+ writeRowSelectiveMetaFields(row);
+ break;
+ }
+ }
+
+ /**
+ * Selective meta-field write path: populate only the meta columns opted in via
+ * {@code hoodie.meta.fields.mode} — {@code _hoodie_commit_time} and/or {@code _hoodie_file_name}.
+ * The other meta columns stay null on disk. Record key is never populated in this path, so the
+ * record key is not registered with the write support (bloom filter / RLI hooks are meaningless
+ * without the record-key column).
+ */
+ private void writeRowSelectiveMetaFields(InternalRow row) {
+ try {
+ UTF8String[] metaFields = new UTF8String[5];
+ if (metaFieldsMode.isCommitTimePopulated()) {
+ metaFields[HoodieRecord.COMMIT_TIME_METADATA_FIELD_ORD] = shouldPreserveHoodieMetadata
+ ? row.getUTF8String(HoodieRecord.COMMIT_TIME_METADATA_FIELD_ORD) : commitTime;
+ }
+ if (metaFieldsMode.isFileNamePopulated()) {
+ // Always the file being written, never the source row's value — even when
+ // shouldPreserveHoodieMetadata is set. Preserving it during clustering would leave
+ // _hoodie_file_name pointing at a file that clustering just replaced. This matches the
+ // ALL path in writeRow below.
+ metaFields[HoodieRecord.FILENAME_META_FIELD_ORD] = fileName;
+ }
+ // The remaining meta columns stay null — Parquet stores nulls as definition-level flags
+ // (zero data bytes).
+ InternalRow updatedRow = SparkAdapterSupport$.MODULE$.sparkAdapter().createInternalRow(metaFields, row, true);
+ fileWriter.writeRow(updatedRow);
+ writeStatus.markSuccess((HoodieRecordDelegate) null, Option.empty());
+ } catch (Exception e) {
+ writeStatus.setGlobalError(e);
+ throw new HoodieException("Exception thrown while writing spark InternalRows to file ", e);
}
}
diff --git a/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/HoodieDatasetBulkInsertHelper.scala b/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/HoodieDatasetBulkInsertHelper.scala
index 0ee2abd847a5..85c33e3f4274 100644
--- a/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/HoodieDatasetBulkInsertHelper.scala
+++ b/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/HoodieDatasetBulkInsertHelper.scala
@@ -137,7 +137,12 @@ object HoodieDatasetBulkInsertHelper
// need access to the [[InternalRow]] and therefore can avoid the need
// to dereference [[DataFrame]] into [[RDD]]
val query = df.queryExecution.logical
- val metaFieldsStubs = metaFields.map(f => Alias(Literal(UTF8String.EMPTY_UTF8, dataType = StringType), f.name)())
+ // Nullable null stubs — the actual meta-column values are set downstream by
+ // HoodieRowCreateHandle.write based on hoodie.meta.fields.mode. Using a null literal (rather
+ // than an empty-string literal) guarantees the resulting StructField's nullable=true so the
+ // physical Parquet column is written as OPTIONAL and can hold nulls under selective / NONE
+ // modes.
+ val metaFieldsStubs = metaFields.map(f => Alias(Literal.create(null, StringType), f.name)())
val prependedQuery = Project(metaFieldsStubs ++ query.output, query)
sparkAdapter.getUnsafeUtils.createDataFrameFrom(df.sparkSession, prependedQuery)
diff --git a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/TestSimpleTransactionDirectMarkerBasedDetectionStrategyWithZKLockProvider.java b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/TestSimpleTransactionDirectMarkerBasedDetectionStrategyWithZKLockProvider.java
index 73d9c40db316..36bb2d87df6f 100644
--- a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/TestSimpleTransactionDirectMarkerBasedDetectionStrategyWithZKLockProvider.java
+++ b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/TestSimpleTransactionDirectMarkerBasedDetectionStrategyWithZKLockProvider.java
@@ -82,7 +82,10 @@ public class TestSimpleTransactionDirectMarkerBasedDetectionStrategyWithZKLockPr
initHoodieStorage();
metaClient = HoodieTestUtils.init(storageConf, basePath, HoodieTableType.MERGE_ON_READ);
- Properties properties = getPropertiesForKeyGen();
+ // Meta fields populated, matching the table created above. The no-arg getPropertiesForKeyGen()
+ // hardcodes populate=false, which the writer-vs-table meta-fields check rejects rather than
+ // silently narrowing the table -- and this fixture is not about meta fields at all.
+ Properties properties = getPropertiesForKeyGen(true);
properties.setProperty(KeyGeneratorOptions.RECORDKEY_FIELD_NAME.key(), "_row_key");
server = new TestingServer();
properties.setProperty(ZK_BASE_PATH_PROP_KEY, basePath);
diff --git a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/TestHoodieKeyLocationFetchHandle.java b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/TestHoodieKeyLocationFetchHandle.java
index 87c72e746425..b79b2d8778d8 100644
--- a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/TestHoodieKeyLocationFetchHandle.java
+++ b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/TestHoodieKeyLocationFetchHandle.java
@@ -89,7 +89,10 @@ public class TestHoodieKeyLocationFetchHandle extends HoodieSparkClientTestHarne
public void testFetchHandle(boolean populateMetaFields) throws Exception {
metaClient = HoodieTestUtils.init(storageConf, basePath, HoodieTableType.COPY_ON_WRITE, populateMetaFields ? new Properties() : getPropertiesForKeyGen());
config = getConfigBuilder()
- .withProperties(getPropertiesForKeyGen())
+ // Match the table created above. This test does not build a write client, so the
+ // writer-vs-table meta-fields check never runs on it -- but leaving the writer on
+ // populate=false against a populated table is a disagreement waiting to surface.
+ .withProperties(getPropertiesForKeyGen(populateMetaFields))
.withIndexConfig(HoodieIndexConfig.newBuilder()
.build()).build();
diff --git a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/storage/TestHoodieAvroFileWriterFactory.java b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/storage/TestHoodieAvroFileWriterFactory.java
index bdb0b87eeee3..bf84ec4f9e29 100644
--- a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/storage/TestHoodieAvroFileWriterFactory.java
+++ b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/io/storage/TestHoodieAvroFileWriterFactory.java
@@ -21,6 +21,7 @@ package org.apache.hudi.io.storage;
import org.apache.hudi.client.SparkTaskContextSupplier;
import org.apache.hudi.common.config.HoodieStorageConfig;
import org.apache.hudi.common.model.HoodieRecord.HoodieRecordType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.config.HoodieWriteConfig;
import org.apache.hudi.core.io.storage.HoodieFileWriter;
import org.apache.hudi.core.io.storage.HoodieFileWriterFactory;
@@ -90,28 +91,31 @@ public class TestHoodieAvroFileWriterFactory extends HoodieClientTestBase {
@Test
public void testEnableBloomFilter() {
HoodieWriteConfig config = getConfig(IndexType.BLOOM);
- assertTrue(HoodieFileWriterFactory.enableBloomFilter(true, config));
- assertFalse(HoodieFileWriterFactory.enableBloomFilter(false, config));
+ assertTrue(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.ALL, config));
+ assertFalse(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.NONE, config));
+ assertFalse(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.COMMIT_TIME_ONLY, config));
+ assertFalse(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.FILE_NAME_ONLY, config));
+ assertFalse(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME, config));
config = getConfig(IndexType.SIMPLE);
- assertTrue(HoodieFileWriterFactory.enableBloomFilter(true, config));
+ assertTrue(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.ALL, config));
config = getConfig(IndexType.SIMPLE);
- assertTrue(HoodieFileWriterFactory.enableBloomFilter(true, config));
+ assertTrue(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.ALL, config));
config = getConfigBuilder(IndexType.BLOOM)
.withStorageConfig(HoodieStorageConfig.newBuilder()
.parquetBloomFilterEnable(false).build()).build();
- assertTrue(HoodieFileWriterFactory.enableBloomFilter(true, config));
+ assertTrue(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.ALL, config));
config = getConfigBuilder(IndexType.SIMPLE)
.withStorageConfig(HoodieStorageConfig.newBuilder()
.parquetBloomFilterEnable(true).build()).build();
- assertTrue(HoodieFileWriterFactory.enableBloomFilter(true, config));
+ assertTrue(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.ALL, config));
config = getConfigBuilder(IndexType.SIMPLE)
.withStorageConfig(HoodieStorageConfig.newBuilder()
.parquetBloomFilterEnable(false).build()).build();
- assertFalse(HoodieFileWriterFactory.enableBloomFilter(true, config));
+ assertFalse(HoodieFileWriterFactory.enableBloomFilter(MetaFieldsMode.ALL, config));
}
}
diff --git a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/action/cluster/ClusteringTestUtils.java b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/action/cluster/ClusteringTestUtils.java
index 03809a5526d8..bac326b567f3 100644
--- a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/action/cluster/ClusteringTestUtils.java
+++ b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/action/cluster/ClusteringTestUtils.java
@@ -81,7 +81,9 @@ public class ClusteringTestUtils {
.withClusteringSortColumns(populateMetaFields ? "_hoodie_record_key" : "_row_key")
.withClusteringTargetPartitions(0).withInlineClusteringNumCommits(0).withInlineClustering(false)
.build();
- properties.putAll(getPropertiesForKeyGen());
+ // Must follow the flag: this config drives a clustering write, and a writer on populate=false
+ // against a table created with meta fields populated is rejected rather than silently narrowing it.
+ properties.putAll(getPropertiesForKeyGen(populateMetaFields));
// write config builder
return HoodieWriteConfig.newBuilder().withPath(basePath).withSchema(schemaStr)
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/model/HoodieAvroIndexedRecord.java b/hudi-common/src/main/java/org/apache/hudi/common/model/HoodieAvroIndexedRecord.java
index b2b3e99d345e..eda401c5b8e5 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/model/HoodieAvroIndexedRecord.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/model/HoodieAvroIndexedRecord.java
@@ -44,8 +44,6 @@ import java.io.IOException;
import java.util.Map;
import java.util.Properties;
-import static org.apache.hudi.common.table.HoodieTableConfig.POPULATE_META_FIELDS;
-
/**
* This only use by reader returning.
*/
@@ -281,7 +279,11 @@ public class HoodieAvroIndexedRecord extends HoodieRecord<IndexedRecord> {
GenericRecord record = (GenericRecord) data;
String key;
String partition;
- if (keyGen.isPresent() && !Boolean.parseBoolean(props.getOrDefault(POPULATE_META_FIELDS.key(), POPULATE_META_FIELDS.defaultValue().toString()).toString())) {
+ // Resolve via hoodie.meta.fields.mode — reading the deprecated boolean alone would report
+ // "populated" for a selective-mode table (whose _hoodie_record_key column is null), sending us
+ // down the meta-column branch below and NPE-ing on the null field.
+ boolean recordKeyPopulated = MetaFieldsMode.resolve(props).isRecordKeyPopulated();
+ if (keyGen.isPresent() && !recordKeyPopulated) {
BaseKeyGenerator keyGeneratorOpt = keyGen.get();
key = keyGeneratorOpt.getRecordKey(record);
partition = keyGeneratorOpt.getPartitionPath(record);
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/model/MetaFieldsMode.java b/hudi-common/src/main/java/org/apache/hudi/common/model/MetaFieldsMode.java
new file mode 100644
index 000000000000..2af7be449dea
--- /dev/null
+++ b/hudi-common/src/main/java/org/apache/hudi/common/model/MetaFieldsMode.java
@@ -0,0 +1,225 @@
+/*
+ * 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.hudi.common.model;
+
+import org.apache.hudi.common.config.HoodieConfig;
+import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.util.StringUtils;
+
+import lombok.Getter;
+
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+
+/**
+ * Which of Hudi's meta columns are physically populated on disk.
+ *
+ * <p>Selective modes exist so that tables that opt out of the default {@code populate.meta.fields=true}
+ * can still keep the two columns that matter for downstream operations without paying for the other
+ * three:
+ *
+ * <ul>
+ * <li>{@code _hoodie_commit_time} — required for incremental queries.</li>
+ * <li>{@code _hoodie_file_name} — useful for file-level pruning / investigation lookups.</li>
+ * </ul>
+ *
+ * <p>The remaining three meta columns ({@code _hoodie_commit_seqno}, {@code _hoodie_record_key},
+ * {@code _hoodie_partition_path}) are all-or-nothing — either populate every meta column ({@link #ALL})
+ * or none of them beyond the two selectable ones. If you need any of the remaining columns, set
+ * {@code hoodie.populate.meta.fields=true}.
+ *
+ * <p>This enum is the single source of truth for meta-column population. When the mode property is
+ * absent, the {@code resolve} overloads fall back to the deprecated {@code
+ * hoodie.populate.meta.fields} boolean so that tables written before the mode property existed keep
+ * their behavior:
+ *
+ * <ul>
+ * <li>{@code populate.meta.fields=true} (or absent) → {@link #ALL} — today's default.</li>
+ * <li>{@code populate.meta.fields=false} → {@link #NONE}.</li>
+ * </ul>
+ *
+ * <p>On-disk representation: the enum {@link #name()} is persisted in {@code hoodie.properties}
+ * under the property {@code hoodie.meta.fields.mode}.
+ */
+@Getter
+public enum MetaFieldsMode {
+ /**
+ * All five Hudi meta columns are populated — today's default.
+ */
+ ALL(true, true),
+
+ /**
+ * No Hudi meta columns are populated. Incremental queries are unsupported. File-level pruning
+ * that depends on {@code _hoodie_file_name} is unsupported.
+ */
+ NONE(false, false),
+
+ /**
+ * Only {@code _hoodie_commit_time} is populated. Incremental queries remain functional; other
+ * meta columns stay null on disk.
+ */
+ COMMIT_TIME_ONLY(true, false),
+
+ /**
+ * Only {@code _hoodie_file_name} is populated. Useful for file-level lookups and debugging;
+ * incremental queries are unsupported.
+ */
+ FILE_NAME_ONLY(false, true),
+
+ /**
+ * Both {@code _hoodie_commit_time} and {@code _hoodie_file_name} are populated.
+ */
+ COMMIT_TIME_AND_FILE_NAME(true, true);
+
+ private final boolean commitTimePopulated;
+ private final boolean fileNamePopulated;
+
+ MetaFieldsMode(boolean commitTimePopulated, boolean fileNamePopulated) {
+ this.commitTimePopulated = commitTimePopulated;
+ this.fileNamePopulated = fileNamePopulated;
+ }
+
+ /**
+ * @return true when all five meta columns are populated (i.e. this is {@link #ALL}). Selective
+ * modes never populate {@code _hoodie_record_key}, {@code _hoodie_partition_path}, or
+ * {@code _hoodie_commit_seqno}.
+ */
+ public boolean isRecordKeyPopulated() {
+ return this == ALL;
+ }
+
+ /**
+ * @return true for the modes that populate some but not all meta columns, i.e. everything except
+ * {@link #ALL} and {@link #NONE}.
+ *
+ * <p>These are the modes the deprecated {@code hoodie.populate.meta.fields} boolean cannot
+ * express, so they are what callers gate on when a code path only understands all-or-nothing meta
+ * fields — writer engines not yet wired for selective population, table versions that predate the
+ * mode property, and validation that must not let a two-state writer speak for a five-state table.
+ */
+ public boolean isSelective() {
+ return this != ALL && this != NONE;
+ }
+
+ /**
+ * Resolve the configured meta-fields mode, falling back to the deprecated population boolean.
+ *
+ * <p>When {@link HoodieTableConfig#META_FIELDS_MODE} is set, it is always authoritative. Legacy
+ * configs without the mode resolve to {@link #ALL} or {@link #NONE} from
+ * {@link HoodieTableConfig#POPULATE_META_FIELDS} without mutating the config.
+ */
+ public static MetaFieldsMode resolve(HoodieConfig config) {
+ String rawMode = config.getString(HoodieTableConfig.META_FIELDS_MODE);
+ if (StringUtils.isNullOrEmpty(rawMode)) {
+ return config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS) ? ALL : NONE;
+ }
+ return parse(rawMode);
+ }
+
+ /**
+ * Resolve the configured meta-fields mode from raw properties, falling back to the deprecated
+ * population boolean without mutating the properties.
+ */
+ public static MetaFieldsMode resolve(Properties props) {
+ String rawMode = props.getProperty(HoodieTableConfig.META_FIELDS_MODE.key());
+ if (StringUtils.isNullOrEmpty(rawMode)) {
+ return Boolean.parseBoolean(props.getProperty(
+ HoodieTableConfig.POPULATE_META_FIELDS.key(),
+ HoodieTableConfig.POPULATE_META_FIELDS.defaultValue().toString()))
+ ? ALL : NONE;
+ }
+ return parse(rawMode);
+ }
+
+ /**
+ * Resolve the configured meta-fields mode from a string map, falling back to the deprecated
+ * population boolean without mutating the map.
+ */
+ public static MetaFieldsMode resolve(Map<String, String> propsMap) {
+ String rawMode = propsMap.get(HoodieTableConfig.META_FIELDS_MODE.key());
+ if (StringUtils.isNullOrEmpty(rawMode)) {
+ return Boolean.parseBoolean(propsMap.getOrDefault(
+ HoodieTableConfig.POPULATE_META_FIELDS.key(),
+ HoodieTableConfig.POPULATE_META_FIELDS.defaultValue().toString()))
+ ? ALL : NONE;
+ }
+ return parse(rawMode);
+ }
+
+ /**
+ * Parse a raw {@code hoodie.meta.fields.mode} value into an enum constant, with a message that
+ * lists the allowed values.
+ */
+ private static MetaFieldsMode parse(String rawMode) {
+ try {
+ // Case-insensitive: users hand-editing hoodie.properties or passing write options should not
+ // have to match the enum's casing exactly.
+ return MetaFieldsMode.valueOf(rawMode.trim().toUpperCase(Locale.ROOT));
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(String.format(
+ "Unsupported value '%s' for hoodie.meta.fields.mode. Allowed values: %s.",
+ rawMode, Arrays.stream(values()).map(Enum::name).collect(Collectors.joining(", "))), e);
+ }
+ }
+
+ /**
+ * @return the equivalent value of the deprecated {@code hoodie.populate.meta.fields} boolean, so
+ * that call sites not yet migrated to this enum keep observing consistent behavior.
+ */
+ public boolean toLegacyPopulateMetaFields() {
+ return this == ALL;
+ }
+
+ public static MetaFieldsMode fromLegacyPopulateMetaFields(Boolean populateMetaFields) {
+ return populateMetaFields == null || populateMetaFields ? MetaFieldsMode.ALL : MetaFieldsMode.NONE;
+ }
+
+ /**
+ * @return true when this mode populates at least one meta column that {@code other} does not.
+ *
+ * <p>Meta-field population is a physical-storage decision baked into files at write time, so it
+ * can never be widened for an existing table: earlier commits would be missing columns that later
+ * commits have, and readers cannot tell the two apart. Every transition that adds a column is
+ * therefore rejected — {@code NONE -> COMMIT_TIME_ONLY} and
+ * {@code FILE_NAME_ONLY -> COMMIT_TIME_AND_FILE_NAME} just as much as {@code NONE -> ALL}.
+ *
+ * <p>Narrowing is not flagged here, because the two callers treat it differently:
+ *
+ * <ul>
+ * <li>A writer must match the table exactly. It cannot narrow either — the mode is a table
+ * property and runtime validation rejects any mismatch.</li>
+ * <li>The sanctioned mutation paths — hudi-cli and upgrade — may narrow, and only narrow.
+ * Dropping a meta column leaves earlier files carrying values nothing reads, which is
+ * recoverable; adding one leaves later files claiming a column earlier files lack, which is
+ * not. A caller changing the mode must therefore reject any transition where the new mode
+ * {@code isWiderThan} the old.</li>
+ * </ul>
+ */
+ public boolean isWiderThan(MetaFieldsMode other) {
+ if (other == null) {
+ return false;
+ }
+ return (commitTimePopulated && !other.commitTimePopulated)
+ || (fileNamePopulated && !other.fileNamePopulated)
+ || (isRecordKeyPopulated() && !other.isRecordKeyPopulated());
+ }
+}
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableConfig.java b/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableConfig.java
index 421a5aaedace..63ead8bcc087 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableConfig.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableConfig.java
@@ -39,6 +39,7 @@ import org.apache.hudi.common.model.HoodieRecordMerger;
import org.apache.hudi.common.model.HoodieRecordPayload;
import org.apache.hudi.common.model.HoodieTableType;
import org.apache.hudi.common.model.HoodieTimelineTimeZone;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.OverwriteNonDefaultsWithLatestAvroPayload;
import org.apache.hudi.common.model.OverwriteWithLatestAvroPayload;
import org.apache.hudi.common.model.PartialUpdateAvroPayload;
@@ -328,12 +329,39 @@ public class HoodieTableConfig extends HoodieConfig {
.noDefaultValue()
.withDocumentation("Base path of the dataset that needs to be bootstrapped as a Hudi table");
+ /**
+ * @deprecated since 1.3.0, use {@link #META_FIELDS_MODE} instead. {@code true} maps to
+ * {@link MetaFieldsMode#ALL} and {@code false} maps to {@link MetaFieldsMode#NONE}. This property
+ * is still honored for tables written before {@code hoodie.meta.fields.mode} existed, but it is
+ * consulted only when the mode property is absent.
+ */
+ @Deprecated
public static final ConfigProperty<Boolean> POPULATE_META_FIELDS = ConfigProperty
.key("hoodie.populate.meta.fields")
.defaultValue(true)
- .withDocumentation("When enabled, populates all meta fields. When disabled, no meta fields are populated "
+ .deprecatedAfter("1.2.0")
+ .withDocumentation("Deprecated — use hoodie.meta.fields.mode instead (true maps to ALL, false maps to NONE). "
+ + "When enabled, populates all meta fields. When disabled, no meta fields are populated "
+ "and incremental queries will not be functional. This is only meant to be used for append only/immutable data for batch processing");
+ // NOTE: deliberately carries no sinceVersion. validateConfigVersion() silently *removes* any
+ // property whose sinceVersion exceeds the table's version (see the props.remove call in
+ // dropInvalidConfigs), so declaring one here would strip the mode from every table below that
+ // version on load -- reverting it to ALL without a word. Meta-field population is not a v10
+ // concept: a table as old as v6 can carry a selective mode, set at creation or through the
+ // hudi-cli, and 1.x supports writing to those tables. v6 is the floor only because that is the
+ // oldest version 1.x can write. Anything that keys meta-field behavior on table version rather
+ // than on this property will therefore be wrong for those tables.
+ public static final ConfigProperty<String> META_FIELDS_MODE = ConfigProperty
+ .key("hoodie.meta.fields.mode")
+ .noDefaultValue()
+ .withDocumentation("Which Hudi meta columns are physically populated on disk. Allowed values are "
+ + "ALL, NONE, COMMIT_TIME_ONLY, FILE_NAME_ONLY and COMMIT_TIME_AND_FILE_NAME. This supersedes the "
+ + "deprecated hoodie.populate.meta.fields boolean, which is consulted only when this property is unset "
+ + "(true maps to ALL, false maps to NONE). Supported on any table version 1.x can write, not just the "
+ + "latest. Set only at table creation, via the hudi-cli, or during table upgrade — the property is "
+ + "immutable at runtime because it is a physical-storage decision baked into files at write time.");
+
public static final ConfigProperty<String> KEY_GENERATOR_CLASS_NAME = ConfigProperty
.key("hoodie.table.keygenerator.class")
.noDefaultValue()
@@ -652,6 +680,12 @@ public class HoodieTableConfig extends HoodieConfig {
}
hoodieConfig.setDefaultValue(DROP_PARTITION_COLUMNS);
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(hoodieConfig);
+ if (tableVersion.lesserThan(HoodieTableVersion.TEN)) {
+ hoodieConfig.setValue(POPULATE_META_FIELDS,
+ Boolean.toString(metaFieldsMode.toLegacyPopulateMetaFields()));
+ }
+
dropInvalidConfigs(hoodieConfig);
storeProperties(hoodieConfig.getProps(), outputStream, propertyPath);
}
@@ -1231,9 +1265,46 @@ public class HoodieTableConfig extends HoodieConfig {
/**
* @returns true is meta fields need to be populated. else returns false.
+ *
+ * <p>Derived from {@link #getMetaFieldsMode()} so that call sites still written against the
+ * deprecated boolean observe the same answer as the enum: only {@link MetaFieldsMode#ALL}
+ * populates every meta column. Selective modes report {@code false} here, which keeps
+ * key-dependent machinery (bloom filters, record-level index) correctly disabled.
*/
public boolean populateMetaFields() {
- return Boolean.parseBoolean(getStringOrDefault(POPULATE_META_FIELDS));
+ return getMetaFieldsMode().toLegacyPopulateMetaFields();
+ }
+
+ /**
+ * @return the configured {@link MetaFieldsMode}, falling back to the deprecated
+ * {@link #POPULATE_META_FIELDS} setting for legacy tables. This method is side-effect free and
+ * never returns {@code null}.
+ */
+ public MetaFieldsMode getMetaFieldsMode() {
+ return MetaFieldsMode.resolve(this);
+ }
+
+ /**
+ * @return true when the {@code _hoodie_commit_time} meta column is physically populated on disk.
+ */
+ public boolean isCommitTimePopulated() {
+ return getMetaFieldsMode().isCommitTimePopulated();
+ }
+
+ /**
+ * @return true when the {@code _hoodie_file_name} meta column is physically populated on disk.
+ */
+ public boolean isFileNamePopulated() {
+ return getMetaFieldsMode().isFileNamePopulated();
+ }
+
+ /**
+ * @return true when the {@code _hoodie_record_key} meta column is physically populated on disk.
+ * Only {@link MetaFieldsMode#ALL} populates the record-key column; every selective mode leaves
+ * it null.
+ */
+ public boolean isRecordKeyPopulated() {
+ return getMetaFieldsMode().isRecordKeyPopulated();
}
/**
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableMetaClient.java b/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableMetaClient.java
index fbeb62fe0158..c2d849e374a2 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableMetaClient.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/HoodieTableMetaClient.java
@@ -38,6 +38,7 @@ import org.apache.hudi.common.model.HoodieIndexMetadata;
import org.apache.hudi.common.model.HoodieRecordPayload;
import org.apache.hudi.common.model.HoodieTableType;
import org.apache.hudi.common.model.HoodieTimelineTimeZone;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.table.timeline.CommitMetadataSerDe;
import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
import org.apache.hudi.common.table.timeline.HoodieArchivedTimeline;
@@ -84,6 +85,7 @@ import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
@@ -1015,6 +1017,7 @@ public class HoodieTableMetaClient implements Serializable {
private String bootstrapBasePath;
private Boolean bootstrapIndexEnable;
private Boolean populateMetaFields;
+ private MetaFieldsMode metaFieldsMode;
private String keyGeneratorClassProp;
private String partitionValueExtractorClass;
private String keyGeneratorType;
@@ -1172,11 +1175,38 @@ public class HoodieTableMetaClient implements Serializable {
return this;
}
- public TableBuilder setPopulateMetaFields(boolean populateMetaFields) {
+ /**
+ * @param populateMetaFields {@code null} when the caller did not state the property. That is
+ * distinct from {@code false}: when no mode is stated, {@code false} is inferred as
+ * {@link MetaFieldsMode#NONE}, while an unstated value defaults to {@link MetaFieldsMode#ALL}.
+ * @deprecated since 1.3.0, use {@link #setMetaFieldsMode(MetaFieldsMode)} instead
+ * ({@code true} maps to {@link MetaFieldsMode#ALL}, {@code false} to {@link MetaFieldsMode#NONE}).
+ */
+ @Deprecated
+ public TableBuilder setPopulateMetaFields(Boolean populateMetaFields) {
this.populateMetaFields = populateMetaFields;
return this;
}
+ public TableBuilder setMetaFieldsMode(MetaFieldsMode metaFieldsMode) {
+ this.metaFieldsMode = metaFieldsMode;
+ return this;
+ }
+
+ /**
+ * Convenience overload that accepts the raw on-disk string (e.g. from properties files).
+ * Empty or null values leave the mode unset — the table then resolves to ALL or NONE from the
+ * deprecated populate.meta.fields boolean.
+ */
+ public TableBuilder setMetaFieldsModeFromString(String rawMode) {
+ if (rawMode == null || rawMode.trim().isEmpty()) {
+ this.metaFieldsMode = null;
+ return this;
+ }
+ this.metaFieldsMode = MetaFieldsMode.valueOf(rawMode.trim().toUpperCase(Locale.ROOT));
+ return this;
+ }
+
public TableBuilder setKeyGeneratorClassProp(String keyGeneratorClassProp) {
this.keyGeneratorClassProp = keyGeneratorClassProp;
return this;
@@ -1396,6 +1426,9 @@ public class HoodieTableMetaClient implements Serializable {
if (hoodieConfig.contains(HoodieTableConfig.POPULATE_META_FIELDS)) {
setPopulateMetaFields(hoodieConfig.getBoolean(HoodieTableConfig.POPULATE_META_FIELDS));
}
+ if (hoodieConfig.contains(HoodieTableConfig.META_FIELDS_MODE)) {
+ setMetaFieldsModeFromString(hoodieConfig.getString(HoodieTableConfig.META_FIELDS_MODE));
+ }
if (hoodieConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
setKeyGeneratorClassProp(hoodieConfig.getString(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME));
} else if (hoodieConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE)) {
@@ -1536,8 +1569,18 @@ public class HoodieTableMetaClient implements Serializable {
tableConfig.setValue(HoodieTableConfig.CDC_SUPPLEMENTAL_LOGGING_MODE, cdcSupplementalLoggingMode);
}
}
- if (null != populateMetaFields) {
- tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS, Boolean.toString(populateMetaFields));
+ // Resolve legacy input through the shared mode precedence and persist the result for every
+ // newly created table.
+ if (metaFieldsMode == null) {
+ metaFieldsMode = MetaFieldsMode.fromLegacyPopulateMetaFields(populateMetaFields);
+ }
+
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, metaFieldsMode.name());
+ if (tableVersion.lesserThan(HoodieTableVersion.TEN)) {
+ // Below table version 10, also record the deprecated boolean for unpatched readers. From v10
+ // the mode alone is sufficient, including after upgrading from v9.
+ tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS,
+ Boolean.toString(metaFieldsMode.toLegacyPopulateMetaFields()));
}
if (null != keyGeneratorClassProp) {
KeyGeneratorType type = KeyGeneratorType.fromClassName(keyGeneratorClassProp);
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java b/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
index 1e8988a742cb..08c45e2be4e8 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
@@ -23,6 +23,7 @@ import org.apache.hudi.common.fs.FileNameParser;
import org.apache.hudi.common.model.HoodieCommitMetadata;
import org.apache.hudi.common.model.HoodieLogFile;
import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.schema.HoodieSchemaField;
@@ -124,7 +125,11 @@ public class TableSchemaResolver {
* @throws Exception
*/
public HoodieSchema getTableSchema() throws Exception {
- return getTableSchema(metaClient.getTableConfig().populateMetaFields());
+ // Include meta fields whenever the table's meta-fields mode populates any of them. Under
+ // selective modes (COMMIT_TIME_ONLY / FILE_NAME_ONLY / COMMIT_TIME_AND_FILE_NAME) the meta
+ // columns exist as physical nullable Parquet columns even though populateMetaFields() is false,
+ // and read paths (e.g. incremental relations) must see them in the projected schema.
+ return getTableSchema(metaClient.getTableConfig().getMetaFieldsMode() != MetaFieldsMode.NONE);
}
/**
@@ -148,7 +153,8 @@ public class TableSchemaResolver {
.filterCompletedInstants()
.findInstantsBeforeOrEquals(timestamp)
.lastInstant();
- return getTableSchemaInternal(metaClient.getTableConfig().populateMetaFields(), instant)
+ return getTableSchemaInternal(
+ metaClient.getTableConfig().getMetaFieldsMode() != MetaFieldsMode.NONE, instant)
.orElseThrow(schemaNotFoundError());
}
diff --git a/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileBinaryCopier.java b/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileBinaryCopier.java
index b001e9cadd08..49b33fcbc001 100644
--- a/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileBinaryCopier.java
+++ b/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileBinaryCopier.java
@@ -18,6 +18,7 @@
package org.apache.hudi.core.io.storage;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.storage.StoragePath;
import org.apache.parquet.schema.MessageType;
@@ -35,5 +36,17 @@ public interface HoodieFileBinaryCopier {
long binaryCopy(List<StoragePath> inputFilePaths, List<StoragePath> outputFilePath, MessageType writeSchema, boolean schemaEvolutionEnabled) throws IOException;
+ /**
+ * Tell the copier which meta columns this table populates.
+ *
+ * <p>Binary copy rewrites {@code _hoodie_file_name} to the output file name. That is correct for a
+ * table that populates the column and wrong for one that does not, which would otherwise come out of
+ * clustering carrying a file name it never advertised. Implementations that do not rewrite meta
+ * columns can ignore this.
+ */
+ default void setMetaFieldsMode(MetaFieldsMode metaFieldsMode) {
+ // no-op by default
+ }
+
void close() throws IOException;
}
diff --git a/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileWriterFactory.java b/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileWriterFactory.java
index 2ac944085986..7b1fc9859106 100644
--- a/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileWriterFactory.java
+++ b/hudi-common/src/main/java/org/apache/hudi/core/io/storage/HoodieFileWriterFactory.java
@@ -26,6 +26,7 @@ import org.apache.hudi.common.engine.TaskContextSupplier;
import org.apache.hudi.common.fs.FSUtils;
import org.apache.hudi.common.model.HoodieFileFormat;
import org.apache.hudi.common.model.HoodieRecord.HoodieRecordType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.storage.HoodieStorage;
import org.apache.hudi.storage.StoragePath;
@@ -138,8 +139,9 @@ public class HoodieFileWriterFactory {
/**
* Check if need to enable bloom filter.
*/
- public static boolean enableBloomFilter(boolean populateMetaFields, HoodieConfig config) {
- return populateMetaFields && (config.getBooleanOrDefault(HoodieStorageConfig.PARQUET_WITH_BLOOM_FILTER_ENABLED)
+ public static boolean enableBloomFilter(MetaFieldsMode metaFieldsMode, HoodieConfig config) {
+ return metaFieldsMode.isRecordKeyPopulated()
+ && (config.getBooleanOrDefault(HoodieStorageConfig.PARQUET_WITH_BLOOM_FILTER_ENABLED)
// HoodieIndexConfig is located in the package hudi-client-common, and the package hudi-client-common depends on the package hudi-common,
// so the class HoodieIndexConfig cannot be accessed in hudi-common, otherwise there will be a circular dependency problem
|| (config.contains("hoodie.index.type") && config.getString("hoodie.index.type").contains("BLOOM")));
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/model/TestMetaFieldsMode.java b/hudi-common/src/test/java/org/apache/hudi/common/model/TestMetaFieldsMode.java
new file mode 100644
index 000000000000..db503cefba4d
--- /dev/null
+++ b/hudi-common/src/test/java/org/apache/hudi/common/model/TestMetaFieldsMode.java
@@ -0,0 +1,193 @@
+/*
+ * 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.hudi.common.model;
+
+import org.apache.hudi.common.config.HoodieConfig;
+import org.apache.hudi.common.table.HoodieTableConfig;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import static org.apache.hudi.common.model.MetaFieldsMode.ALL;
+import static org.apache.hudi.common.model.MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME;
+import static org.apache.hudi.common.model.MetaFieldsMode.COMMIT_TIME_ONLY;
+import static org.apache.hudi.common.model.MetaFieldsMode.FILE_NAME_ONLY;
+import static org.apache.hudi.common.model.MetaFieldsMode.NONE;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for the {@link MetaFieldsMode} enum itself — its predicates and the {@link
+ * MetaFieldsMode#isWiderThan} relation. Resolution from config properties is covered by
+ * {@code TestHoodieMetaFieldsMode}, which exercises the same enum through {@code HoodieTableConfig}.
+ */
+class TestMetaFieldsMode {
+
+ @Test
+ void modePropertyHasNoDefaultValue() {
+ assertFalse(HoodieTableConfig.META_FIELDS_MODE.hasDefaultValue());
+ }
+
+ @Test
+ void resolveDefaultsMissingAndEmptyModesToAll() {
+ HoodieConfig config = new HoodieConfig();
+ assertEquals(ALL, MetaFieldsMode.resolve(config));
+
+ config.setValue(HoodieTableConfig.META_FIELDS_MODE, "");
+ assertEquals(ALL, MetaFieldsMode.resolve(config));
+ }
+
+ @Test
+ void resolveConfigFallsBackToLegacyBooleanWithoutMutation() {
+ HoodieConfig config = new HoodieConfig();
+ config.setValue(HoodieTableConfig.POPULATE_META_FIELDS, "false");
+
+ assertEquals(NONE, MetaFieldsMode.resolve(config));
+ assertFalse(config.contains(HoodieTableConfig.META_FIELDS_MODE));
+
+ config.setValue(HoodieTableConfig.META_FIELDS_MODE, "file_name_only");
+ assertEquals(FILE_NAME_ONLY, MetaFieldsMode.resolve(config));
+ }
+
+ @Test
+ void resolvePropertiesFallsBackToLegacyBooleanWithoutMutation() {
+ Properties props = new Properties();
+ props.setProperty(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+
+ assertEquals(NONE, MetaFieldsMode.resolve(props));
+ assertFalse(props.containsKey(HoodieTableConfig.META_FIELDS_MODE.key()));
+
+ props.setProperty(HoodieTableConfig.META_FIELDS_MODE.key(), "commit_time_only");
+ assertEquals(COMMIT_TIME_ONLY, MetaFieldsMode.resolve(props));
+ }
+
+ @Test
+ void resolveMapFallsBackToLegacyBooleanWithoutMutation() {
+ Map<String, String> propsMap = new HashMap<>();
+ assertEquals(ALL, MetaFieldsMode.resolve(propsMap));
+
+ propsMap.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+
+ assertEquals(NONE, MetaFieldsMode.resolve(propsMap));
+ assertFalse(propsMap.containsKey(HoodieTableConfig.META_FIELDS_MODE.key()));
+
+ propsMap.put(HoodieTableConfig.META_FIELDS_MODE.key(), "commit_time_and_file_name");
+ assertEquals(COMMIT_TIME_AND_FILE_NAME, MetaFieldsMode.resolve(propsMap));
+ }
+
+ @Test
+ void isSelectiveIsTrueForExactlyTheModesTheLegacyBooleanCannotExpress() {
+ // ALL and NONE are the two states hoodie.populate.meta.fields can represent; every other mode
+ // is invisible to a boolean-only caller, which is what isSelective() exists to flag.
+ assertFalse(ALL.isSelective());
+ assertFalse(NONE.isSelective());
+ assertTrue(COMMIT_TIME_ONLY.isSelective());
+ assertTrue(FILE_NAME_ONLY.isSelective());
+ assertTrue(COMMIT_TIME_AND_FILE_NAME.isSelective());
+ }
+
+ @ParameterizedTest
+ @EnumSource(MetaFieldsMode.class)
+ void isSelectiveAgreesWithTheLegacyBooleanRoundTrip(MetaFieldsMode mode) {
+ // A mode is non-selective exactly when converting it to the legacy boolean and back is lossless.
+ MetaFieldsMode roundTripped = mode.toLegacyPopulateMetaFields() ? ALL : NONE;
+ assertEquals(!mode.isSelective(), mode == roundTripped);
+ }
+
+ @Test
+ void toLegacyPopulateMetaFieldsIsTrueOnlyForAll() {
+ assertTrue(ALL.toLegacyPopulateMetaFields());
+ assertFalse(NONE.toLegacyPopulateMetaFields());
+ assertFalse(COMMIT_TIME_ONLY.toLegacyPopulateMetaFields());
+ assertFalse(FILE_NAME_ONLY.toLegacyPopulateMetaFields());
+ assertFalse(COMMIT_TIME_AND_FILE_NAME.toLegacyPopulateMetaFields());
+ }
+
+ @Test
+ void recordKeyIsPopulatedOnlyByAll() {
+ assertTrue(ALL.isRecordKeyPopulated());
+ assertFalse(COMMIT_TIME_AND_FILE_NAME.isRecordKeyPopulated());
+ assertFalse(COMMIT_TIME_ONLY.isRecordKeyPopulated());
+ assertFalse(FILE_NAME_ONLY.isRecordKeyPopulated());
+ assertFalse(NONE.isRecordKeyPopulated());
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ // Every ordered pair of the five modes: is the first wider than the second?
+ "ALL, ALL, false",
+ "ALL, NONE, true",
+ "ALL, COMMIT_TIME_ONLY, true",
+ "ALL, FILE_NAME_ONLY, true",
+ // ALL populates the record key on top of the same two columns, so it is still wider.
+ "ALL, COMMIT_TIME_AND_FILE_NAME, true",
+ "NONE, ALL, false",
+ "NONE, NONE, false",
+ "NONE, COMMIT_TIME_ONLY, false",
+ "NONE, FILE_NAME_ONLY, false",
+ "NONE, COMMIT_TIME_AND_FILE_NAME, false",
+ "COMMIT_TIME_ONLY, ALL, false",
+ "COMMIT_TIME_ONLY, NONE, true",
+ "COMMIT_TIME_ONLY, COMMIT_TIME_ONLY, false",
+ // Not a total order: each of these adds a column the other lacks, so both directions are wider.
+ "COMMIT_TIME_ONLY, FILE_NAME_ONLY, true",
+ "COMMIT_TIME_ONLY, COMMIT_TIME_AND_FILE_NAME, false",
+ "FILE_NAME_ONLY, ALL, false",
+ "FILE_NAME_ONLY, NONE, true",
+ "FILE_NAME_ONLY, COMMIT_TIME_ONLY, true",
+ "FILE_NAME_ONLY, FILE_NAME_ONLY, false",
+ "FILE_NAME_ONLY, COMMIT_TIME_AND_FILE_NAME, false",
+ "COMMIT_TIME_AND_FILE_NAME, ALL, false",
+ "COMMIT_TIME_AND_FILE_NAME, NONE, true",
+ "COMMIT_TIME_AND_FILE_NAME, COMMIT_TIME_ONLY, true",
+ "COMMIT_TIME_AND_FILE_NAME, FILE_NAME_ONLY, true",
+ "COMMIT_TIME_AND_FILE_NAME, COMMIT_TIME_AND_FILE_NAME, false"
+ })
+ void isWiderThanCoversEveryOrderedPair(MetaFieldsMode writer, MetaFieldsMode table, boolean wider) {
+ assertEquals(wider, writer.isWiderThan(table));
+ }
+
+ @Test
+ void commitTimeOnlyAndFileNameOnlyAreMutuallyWider() {
+ // Pinned separately from the matrix because it is the case that makes "narrowing is allowed"
+ // subtle: neither mode is a subset of the other, so a transition either way is a widening.
+ assertTrue(COMMIT_TIME_ONLY.isWiderThan(FILE_NAME_ONLY));
+ assertTrue(FILE_NAME_ONLY.isWiderThan(COMMIT_TIME_ONLY));
+ }
+
+ @ParameterizedTest
+ @EnumSource(MetaFieldsMode.class)
+ void noModeIsWiderThanItself(MetaFieldsMode mode) {
+ assertFalse(mode.isWiderThan(mode));
+ }
+
+ @ParameterizedTest
+ @EnumSource(MetaFieldsMode.class)
+ void isWiderThanTreatsNullAsNotComparable(MetaFieldsMode mode) {
+ // A null table mode means "unknown"; callers must not read that as a widening and reject.
+ assertFalse(mode.isWiderThan(null));
+ }
+}
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/table/read/buffer/TestPositionBasedFileGroupRecordBuffer.java b/hudi-common/src/test/java/org/apache/hudi/common/table/read/buffer/TestPositionBasedFileGroupRecordBuffer.java
index f4f1c52e6d23..685cca840129 100644
--- a/hudi-common/src/test/java/org/apache/hudi/common/table/read/buffer/TestPositionBasedFileGroupRecordBuffer.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/table/read/buffer/TestPositionBasedFileGroupRecordBuffer.java
@@ -133,7 +133,7 @@ class TestPositionBasedFileGroupRecordBuffer {
tableConfig.setValue(HoodieTableConfig.RECORDKEY_FIELDS, "id");
tableConfig.setValue(HoodieTableConfig.RECORD_MERGE_MODE, RecordMergeMode.COMMIT_TIME_ORDERING.name());
tableConfig.setValue(HoodieTableConfig.BASE_FILE_FORMAT, HoodieFileFormat.PARQUET.name());
- tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS, "false");
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, "NONE");
HoodieReaderContext<IndexedRecord> context = new HoodieAvroReaderContext(
mock(StorageConfiguration.class), tableConfig, Option.empty(), Option.empty());
context.initRecordMerger(new TypedProperties());
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestHoodieLsmFileGroupReader.java b/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestHoodieLsmFileGroupReader.java
index 73ad2c1b3a8a..10a4118f3900 100644
--- a/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestHoodieLsmFileGroupReader.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestHoodieLsmFileGroupReader.java
@@ -93,7 +93,7 @@ class TestHoodieLsmFileGroupReader {
tableConfig.setValue(HoodieTableConfig.RECORD_MERGE_MODE, RecordMergeMode.EVENT_TIME_ORDERING.name());
tableConfig.setValue(HoodieTableConfig.BASE_FILE_FORMAT, HoodieFileFormat.PARQUET.name());
tableConfig.setValue(HoodieTableConfig.LOG_FILE_FORMAT, HoodieFileFormat.PARQUET.name());
- tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS, "false");
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, "NONE");
storageConfiguration = mock(StorageConfiguration.class);
HoodieStorage storage = mock(HoodieStorage.class);
when(storage.newInstance(any(StoragePath.class), any(StorageConfiguration.class))).thenReturn(storage);
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestLsmFileGroupRecordIterator.java b/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestLsmFileGroupRecordIterator.java
index 0bd825460b40..640b0b490209 100644
--- a/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestLsmFileGroupRecordIterator.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/table/read/lsm/TestLsmFileGroupRecordIterator.java
@@ -235,7 +235,7 @@ class TestLsmFileGroupRecordIterator {
tableConfig.setValue(HoodieTableConfig.ORDERING_FIELDS, "ts");
tableConfig.setValue(HoodieTableConfig.RECORD_MERGE_MODE, RecordMergeMode.EVENT_TIME_ORDERING.name());
tableConfig.setValue(HoodieTableConfig.BASE_FILE_FORMAT, HoodieFileFormat.PARQUET.name());
- tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS, "false");
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, "NONE");
StorageConfiguration<?> storageConfiguration = mock(StorageConfiguration.class);
HoodieAvroReaderContext context = org.mockito.Mockito.spy(
new HoodieAvroReaderContext(storageConfiguration, tableConfig, Option.empty(), Option.empty()));
diff --git a/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroFileWriterFactory.java b/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroFileWriterFactory.java
index 272de5d4a310..1920619600f3 100644
--- a/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroFileWriterFactory.java
+++ b/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroFileWriterFactory.java
@@ -27,6 +27,7 @@ import org.apache.hudi.common.config.HoodieParquetConfig;
import org.apache.hudi.common.config.HoodieStorageConfig;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.engine.TaskContextSupplier;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.util.Option;
@@ -69,13 +70,13 @@ public class HoodieAvroFileWriterFactory extends HoodieFileWriterFactory {
protected HoodieFileWriter newParquetFileWriter(
String instantTime, StoragePath path, HoodieConfig config, HoodieSchema schema,
TaskContextSupplier taskContextSupplier) throws IOException {
- boolean populateMetaFields = config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS);
+ MetaFieldsMode metaFieldsMode = MetaFieldsMode.resolve(config);
Pair<StorageConfiguration, HoodieConfig> injectedConfigs = HoodieParquetConfigInjector.applyConfigInjector(path, storage.getConf(), config);
StorageConfiguration storageConfiguration = injectedConfigs.getLeft();
HoodieConfig hoodieConfig = injectedConfigs.getRight();
- HoodieAvroWriteSupport writeSupport = getHoodieAvroWriteSupport(schema, hoodieConfig, storageConfiguration, enableBloomFilter(populateMetaFields, hoodieConfig));
+ HoodieAvroWriteSupport writeSupport = getHoodieAvroWriteSupport(schema, hoodieConfig, storageConfiguration, enableBloomFilter(metaFieldsMode, hoodieConfig));
String compressionCodecName = hoodieConfig.getStringOrDefault(HoodieStorageConfig.PARQUET_COMPRESSION_CODEC_NAME);
// Support PARQUET_COMPRESSION_CODEC_NAME is ""
@@ -89,7 +90,7 @@ public class HoodieAvroFileWriterFactory extends HoodieFileWriterFactory {
hoodieConfig.getLongOrDefault(HoodieStorageConfig.PARQUET_MAX_FILE_SIZE),
storageConfiguration, hoodieConfig.getDoubleOrDefault(HoodieStorageConfig.PARQUET_COMPRESSION_RATIO_FRACTION),
hoodieConfig.getBooleanOrDefault(HoodieStorageConfig.PARQUET_DICTIONARY_ENABLED));
- return new HoodieAvroParquetWriter(path, parquetConfig, instantTime, taskContextSupplier, populateMetaFields);
+ return new HoodieAvroParquetWriter(path, parquetConfig, instantTime, taskContextSupplier, metaFieldsMode);
}
protected HoodieFileWriter newParquetFileWriter(
diff --git a/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroParquetWriter.java b/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroParquetWriter.java
index 1fb381b26b0e..08c33f9f20b7 100644
--- a/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroParquetWriter.java
+++ b/hudi-hadoop-common/src/main/java/org/apache/hudi/io/storage/hadoop/HoodieAvroParquetWriter.java
@@ -23,16 +23,20 @@ import org.apache.hudi.avro.HoodieAvroWriteSupport;
import org.apache.hudi.common.config.HoodieParquetConfig;
import org.apache.hudi.common.engine.TaskContextSupplier;
import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.core.io.storage.HoodieAvroFileWriter;
import org.apache.hudi.io.hadoop.HoodieBaseParquetWriter;
import org.apache.hudi.storage.StoragePath;
+import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.IndexedRecord;
import javax.annotation.concurrent.NotThreadSafe;
import java.io.IOException;
import java.util.Map;
+import java.util.Objects;
/**
* HoodieParquetWriter extends the ParquetWriter to help limit the size of underlying file. Provides a way to check if
@@ -48,39 +52,77 @@ public class HoodieAvroParquetWriter
private final String fileName;
private final String instantTime;
private final TaskContextSupplier taskContextSupplier;
- private final boolean populateMetaFields;
+ private final MetaFieldsMode metaFieldsMode;
private final HoodieAvroWriteSupport writeSupport;
+ /**
+ * @deprecated since 1.3.0, use the {@link MetaFieldsMode} overload. Retained for existing callers
+ * that only distinguish all-or-nothing meta fields ({@code true} maps to {@link MetaFieldsMode#ALL},
+ * {@code false} to {@link MetaFieldsMode#NONE}); it cannot express the selective modes.
+ */
+ @Deprecated
@SuppressWarnings({"unchecked", "rawtypes"})
public HoodieAvroParquetWriter(StoragePath file,
HoodieParquetConfig<HoodieAvroWriteSupport> parquetConfig,
String instantTime,
TaskContextSupplier taskContextSupplier,
boolean populateMetaFields) throws IOException {
+ this(file, parquetConfig, instantTime, taskContextSupplier,
+ populateMetaFields ? MetaFieldsMode.ALL : MetaFieldsMode.NONE);
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ public HoodieAvroParquetWriter(StoragePath file,
+ HoodieParquetConfig<HoodieAvroWriteSupport> parquetConfig,
+ String instantTime,
+ TaskContextSupplier taskContextSupplier,
+ MetaFieldsMode metaFieldsMode) throws IOException {
super(file, (HoodieParquetConfig) parquetConfig);
this.fileName = file.getName();
this.writeSupport = parquetConfig.getWriteSupport();
this.instantTime = instantTime;
this.taskContextSupplier = taskContextSupplier;
- this.populateMetaFields = populateMetaFields;
+ this.metaFieldsMode = Objects.requireNonNull(metaFieldsMode, "metaFieldsMode");
}
@Override
public void writeAvroWithMetadata(HoodieKey key, IndexedRecord avroRecord) throws IOException {
- if (populateMetaFields) {
- prepRecordWithMetadata(key, avroRecord, instantTime,
- taskContextSupplier.getPartitionIdSupplier().get(), getWrittenRecordCount(), fileName);
- super.write(avroRecord);
- writeSupport.add(key.getRecordKey());
- } else {
- super.write(avroRecord);
+ switch (metaFieldsMode) {
+ case ALL:
+ prepRecordWithMetadata(key, avroRecord, instantTime,
+ taskContextSupplier.getPartitionIdSupplier().get(), getWrittenRecordCount(), fileName);
+ super.write(avroRecord);
+ writeSupport.add(key.getRecordKey());
+ break;
+ case NONE:
+ super.write(avroRecord);
+ break;
+ default:
+ // Selective mode — populate only the opted-in columns. The other meta columns stay null,
+ // which Parquet stores as definition-level flags (zero data bytes).
+ //
+ // No bloom filter is added here, but not because the key is unavailable: the ALL branch above
+ // takes it from the in-memory HoodieKey, not from the _hoodie_record_key column, so the same
+ // is possible here. It is that HoodieFileWriterFactory#enableBloomFilter short-circuits on
+ // populateMetaFields, which every selective mode makes false, so writeSupport holds no filter
+ // to add to. A bloom index on such a table is rejected at BaseHoodieWriteClient
+ // #validateAgainstTableProperties, since lookups would otherwise NPE on a missing filter.
+ GenericRecord genericRecord = (GenericRecord) avroRecord;
+ if (metaFieldsMode.isCommitTimePopulated()) {
+ genericRecord.put(HoodieRecord.COMMIT_TIME_METADATA_FIELD, instantTime);
+ }
+ if (metaFieldsMode.isFileNamePopulated()) {
+ genericRecord.put(HoodieRecord.FILENAME_METADATA_FIELD, fileName);
+ }
+ super.write(avroRecord);
+ break;
}
}
@Override
public void writeAvro(String key, IndexedRecord object) throws IOException {
super.write(object);
- if (populateMetaFields) {
+ if (metaFieldsMode == MetaFieldsMode.ALL) {
writeSupport.add(key);
}
}
diff --git a/hudi-hadoop-common/src/main/java/org/apache/hudi/parquet/io/HoodieParquetBinaryCopyBase.java b/hudi-hadoop-common/src/main/java/org/apache/hudi/parquet/io/HoodieParquetBinaryCopyBase.java
index 6581be1f8ec9..d12268569ffb 100644
--- a/hudi-hadoop-common/src/main/java/org/apache/hudi/parquet/io/HoodieParquetBinaryCopyBase.java
+++ b/hudi-hadoop-common/src/main/java/org/apache/hudi/parquet/io/HoodieParquetBinaryCopyBase.java
@@ -19,6 +19,7 @@
package org.apache.hudi.parquet.io;
import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.util.VisibleForTesting;
import org.apache.hudi.exception.HoodieException;
@@ -119,6 +120,20 @@ public abstract class HoodieParquetBinaryCopyBase implements Closeable {
// Flag to control schema evolution behavior
protected Boolean schemaEvolutionEnabled = null;
+ /**
+ * Whether {@code _hoodie_file_name} is populated on this table.
+ *
+ * <p>Binary copy rewrites the column to the output file name, which is right for a table that
+ * populates it and wrong for one that does not -- clustering would hand such a table a file name it
+ * never advertised. Defaults to {@code ALL} so callers that do not state a mode keep the historical
+ * behaviour.
+ */
+ private MetaFieldsMode metaFieldsMode = MetaFieldsMode.ALL;
+
+ public void setMetaFieldsMode(MetaFieldsMode metaFieldsMode) {
+ this.metaFieldsMode = java.util.Objects.requireNonNull(metaFieldsMode, "metaFieldsMode");
+ }
+
public HoodieParquetBinaryCopyBase(Configuration conf) {
this.conf = conf;
}
@@ -129,9 +144,13 @@ public abstract class HoodieParquetBinaryCopyBase implements Closeable {
protected void initFileWriter(Path outPutFile, CompressionCodecName newCodecName, MessageType schema) {
try {
- // For meta column '_hoodie_file_name', rewriter will mask value with output file name
- Binary maskValue = Binary.fromString(outPutFile.getName());
- maskColumns.put(ColumnPath.fromDotString(HoodieRecord.FILENAME_METADATA_FIELD), maskValue);
+ // For meta column '_hoodie_file_name', rewriter will mask value with output file name -- but
+ // only on a table that populates it. Masking unconditionally would give a COMMIT_TIME_ONLY or
+ // NONE table a populated file name that contradicts the mode it advertises.
+ if (metaFieldsMode.isFileNamePopulated()) {
+ Binary maskValue = Binary.fromString(outPutFile.getName());
+ maskColumns.put(ColumnPath.fromDotString(HoodieRecord.FILENAME_METADATA_FIELD), maskValue);
+ }
this.requiredSchema = schema;
this.newCodecName = newCodecName;
ParquetFileWriter.Mode writerMode = ParquetFileWriter.Mode.CREATE;
diff --git a/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfig.java b/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfig.java
index 0b0eec6eac2f..a6dd7912318a 100644
--- a/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfig.java
+++ b/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfig.java
@@ -25,6 +25,7 @@ import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.model.AWSDmsAvroPayload;
import org.apache.hudi.common.model.DefaultHoodieRecordPayload;
import org.apache.hudi.common.model.EventTimeAvroPayload;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.OverwriteNonDefaultsWithLatestAvroPayload;
import org.apache.hudi.common.model.OverwriteWithLatestAvroPayload;
import org.apache.hudi.common.model.PartialUpdateAvroPayload;
@@ -352,6 +353,32 @@ class TestHoodieTableConfig extends HoodieCommonTestHarness {
assertEquals("p1", HoodieTableConfig.getPartitionFieldWithoutKeyGenPartitionType(partitionFields.split(",")[0], config));
}
+ /**
+ * The resolution rules themselves are unit-tested in {@code TestHoodieTableConfigMetaFieldsMode} against an
+ * in-memory config. This covers the part that needs real storage: that the mode survives a
+ * {@code hoodie.properties} write / read round trip and still resolves the same way afterwards.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"ALL", "NONE", "COMMIT_TIME_ONLY", "FILE_NAME_ONLY", "COMMIT_TIME_AND_FILE_NAME"})
+ void testMetaFieldsModeSurvivesAPropertiesRoundTrip(String modeName) {
+ MetaFieldsMode mode = MetaFieldsMode.valueOf(modeName);
+ Properties updatedProps = new Properties();
+ updatedProps.setProperty(HoodieTableConfig.META_FIELDS_MODE.key(), mode.name());
+ // Written the way TableBuilder writes it: the legacy boolean is derived from the mode, never
+ // taken from the caller, so hoodie.properties cannot contradict itself.
+ updatedProps.setProperty(HoodieTableConfig.POPULATE_META_FIELDS.key(),
+ String.valueOf(mode.toLegacyPopulateMetaFields()));
+ HoodieTableConfig.update(storage, metaPath, updatedProps);
+
+ HoodieTableConfig config = new HoodieTableConfig(storage, metaPath);
+ assertEquals(mode, config.getMetaFieldsMode());
+ assertEquals(mode.name(), config.getString(HoodieTableConfig.META_FIELDS_MODE));
+ assertEquals(mode.toLegacyPopulateMetaFields(), config.populateMetaFields(),
+ "populateMetaFields() is derived from the mode, so it must agree after a reload");
+ assertEquals(mode.isCommitTimePopulated(), config.isCommitTimePopulated());
+ assertEquals(mode.isFileNamePopulated(), config.isFileNamePopulated());
+ }
+
@Test
void testValidateConfigVersion() {
assertTrue(HoodieTableConfig.validateConfigVersion(HoodieTableConfig.INITIAL_VERSION, HoodieTableVersion.EIGHT));
@@ -362,6 +389,40 @@ class TestHoodieTableConfig extends HoodieCommonTestHarness {
assertFalse(HoodieTableConfig.validateConfigVersion(HoodieTableConfig.INITIAL_VERSION, HoodieTableVersion.SIX));
}
+ /**
+ * {@code hoodie.meta.fields.mode} must remain valid on every table version 1.x can write, down to
+ * v6. Meta-field population is not a v10 concept: a table that old can carry a selective mode, set
+ * at creation or through the hudi-cli.
+ *
+ * <p>This is a real hazard rather than a hypothetical one. Giving the property a
+ * {@code sinceVersion} would make {@code validateConfigVersion} return false below that version,
+ * and {@code dropInvalidConfigs} then *removes* the property from the loaded config -- so an
+ * older table would silently revert to ALL and start writing meta columns its files do not have.
+ * It reads like tidy housekeeping and would be a data-correctness bug.
+ */
+ @ParameterizedTest
+ @EnumSource(value = HoodieTableVersion.class, names = {"SIX", "EIGHT", "NINE", "TEN"})
+ void testMetaFieldsModeIsValidOnEveryWritableTableVersion(HoodieTableVersion tableVersion) {
+ assertTrue(HoodieTableConfig.validateConfigVersion(HoodieTableConfig.META_FIELDS_MODE, tableVersion),
+ "hoodie.meta.fields.mode must not be version-gated; it would be stripped on " + tableVersion);
+ }
+
+ @Test
+ void testMetaFieldsModeSurvivesConfigVersionDroppingOnAnOldTable() {
+ // End to end through the drop path rather than the predicate alone: a v6 table carrying a
+ // selective mode must still have it after validateConfigVersions runs.
+ HoodieConfig config = new HoodieConfig();
+ config.setValue(HoodieTableConfig.META_FIELDS_MODE, MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ config.setValue(HoodieTableConfig.POPULATE_META_FIELDS, "false");
+ config.setValue(HoodieTableConfig.VERSION, String.valueOf(HoodieTableVersion.SIX.versionCode()));
+
+ HoodieTableConfig.dropInvalidConfigs(config);
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY.name(),
+ config.getString(HoodieTableConfig.META_FIELDS_MODE),
+ "the mode must survive on a v6 table -- Uber-style deployments set it there via hudi-cli");
+ }
+
@Test
void testDropInvalidConfigs() {
// test invalid configs are dropped
@@ -386,7 +447,7 @@ class TestHoodieTableConfig extends HoodieCommonTestHarness {
@Test
void testDefinedTableConfigs() {
List<ConfigProperty<?>> configProperties = HoodieTableConfig.definedTableConfigs();
- assertEquals(45, configProperties.size());
+ assertEquals(46, configProperties.size());
configProperties.forEach(c -> {
assertNotNull(c);
assertFalse(c.doc().isEmpty());
diff --git a/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfigMetaFieldsMode.java b/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfigMetaFieldsMode.java
new file mode 100644
index 000000000000..d6eeb229a152
--- /dev/null
+++ b/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableConfigMetaFieldsMode.java
@@ -0,0 +1,159 @@
+/*
+ * 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.hudi.common.table;
+
+import org.apache.hudi.common.model.MetaFieldsMode;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * {@link HoodieTableConfig} resolution of current and legacy meta-field settings as a
+ * {@link MetaFieldsMode}.
+ *
+ * <p>Deliberately separate from its two siblings, which cover different layers:
+ * <ul>
+ * <li>{@code TestMetaFieldsMode} (hudi-common) — the enum's own resolution semantics,
+ * {@code isWiderThan}, {@code toLegacyPopulateMetaFields}. No config involved.</li>
+ * <li>{@code TestHoodieTableConfig#testMetaFieldsModeSurvivesAPropertiesRoundTrip} — the same
+ * resolution against real storage, proving the value survives a {@code hoodie.properties}
+ * write / read.</li>
+ * </ul>
+ * These cases use an in-memory {@link HoodieTableConfig} instead, so they stay fast and need no
+ * storage fixture.
+ */
+class TestHoodieTableConfigMetaFieldsMode {
+
+ private static HoodieTableConfig configOf(Boolean populate, String mode) {
+ HoodieTableConfig config = new HoodieTableConfig();
+ if (populate != null) {
+ config.setValue(HoodieTableConfig.POPULATE_META_FIELDS, String.valueOf(populate));
+ }
+ if (mode != null) {
+ config.setValue(HoodieTableConfig.META_FIELDS_MODE, mode);
+ }
+ return config;
+ }
+
+ @Test
+ void defaultsResolveToAllMode() {
+ HoodieTableConfig cfg = configOf(null, null);
+ assertTrue(cfg.populateMetaFields(), "populateMetaFields default must remain true");
+ assertEquals(MetaFieldsMode.ALL, cfg.getMetaFieldsMode());
+ assertFalse(cfg.contains(HoodieTableConfig.META_FIELDS_MODE),
+ "resolving a default must not mutate the table config");
+ assertTrue(cfg.isCommitTimePopulated());
+ assertTrue(cfg.isFileNamePopulated());
+ assertTrue(cfg.isRecordKeyPopulated());
+ }
+
+ @Test
+ void noneModeWhenPopulateFalseAndModeEmpty() {
+ HoodieTableConfig cfg = configOf(false, "");
+ assertFalse(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.NONE, cfg.getMetaFieldsMode());
+ assertEquals("", cfg.getString(HoodieTableConfig.META_FIELDS_MODE));
+ assertFalse(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ assertFalse(cfg.isRecordKeyPopulated());
+ }
+
+ @Test
+ void noneModeWhenPopulateFalseAndModeUnset() {
+ // Existing populate.meta.fields=false table without the mode property must resolve to NONE.
+ HoodieTableConfig cfg = configOf(false, null);
+ assertFalse(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.NONE, cfg.getMetaFieldsMode());
+ assertFalse(cfg.contains(HoodieTableConfig.META_FIELDS_MODE),
+ "legacy fallback must not mutate the table config");
+ assertFalse(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ assertFalse(cfg.isRecordKeyPopulated());
+ }
+
+ @Test
+ void commitTimeOnlyMode() {
+ HoodieTableConfig cfg = configOf(false, MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ assertFalse(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, cfg.getMetaFieldsMode());
+ assertTrue(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ assertFalse(cfg.isRecordKeyPopulated());
+ }
+
+ @Test
+ void fileNameOnlyMode() {
+ HoodieTableConfig cfg = configOf(false, MetaFieldsMode.FILE_NAME_ONLY.name());
+ assertFalse(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.FILE_NAME_ONLY, cfg.getMetaFieldsMode());
+ assertFalse(cfg.isCommitTimePopulated());
+ assertTrue(cfg.isFileNamePopulated());
+ assertFalse(cfg.isRecordKeyPopulated());
+ }
+
+ @Test
+ void commitTimeAndFileNameMode() {
+ HoodieTableConfig cfg = configOf(false, MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME.name());
+ assertFalse(cfg.populateMetaFields());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME, cfg.getMetaFieldsMode());
+ assertTrue(cfg.isCommitTimePopulated());
+ assertTrue(cfg.isFileNamePopulated());
+ assertFalse(cfg.isRecordKeyPopulated());
+ }
+
+ @Test
+ void modeWinsOverLegacyPopulateMetaFields() {
+ // hoodie.meta.fields.mode is the source of truth: when it is set, the deprecated
+ // populate.meta.fields boolean is not consulted, whichever way it points.
+ HoodieTableConfig cfg = configOf(true, MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, cfg.getMetaFieldsMode());
+ assertTrue(cfg.isCommitTimePopulated());
+ assertFalse(cfg.isFileNamePopulated());
+ // ...and populateMetaFields() is derived from the mode, so legacy call sites agree.
+ assertFalse(cfg.populateMetaFields());
+
+ HoodieTableConfig allWithLegacyFalse = configOf(false, MetaFieldsMode.ALL.name());
+ assertEquals(MetaFieldsMode.ALL, allWithLegacyFalse.getMetaFieldsMode());
+ assertTrue(allWithLegacyFalse.populateMetaFields());
+ }
+
+ @Test
+ void unknownTokenIsRejected() {
+ IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
+ () -> configOf(false, "GARBAGE_VALUE").getMetaFieldsMode());
+ assertTrue(ex.getMessage().contains("GARBAGE_VALUE"),
+ "message must name the rejected value: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains("hoodie.meta.fields.mode"),
+ "message must name the property: " + ex.getMessage());
+ }
+
+ @Test
+ void modeStringIsCaseInsensitiveAndTrimmed() {
+ // Whitespace around the value is tolerated, and casing does not have to match the enum.
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, configOf(false, " COMMIT_TIME_ONLY ").getMetaFieldsMode());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, configOf(false, "commit_time_only").getMetaFieldsMode());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME, configOf(false, " Commit_Time_And_File_Name ").getMetaFieldsMode());
+ HoodieTableConfig cfg = configOf(false, "CoMmIt_TiMe_OnLy");
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, cfg.getMetaFieldsMode());
+ }
+}
diff --git a/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableMetaClient.java b/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableMetaClient.java
index 63d276c2eb61..3cc87601cb57 100644
--- a/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableMetaClient.java
+++ b/hudi-hadoop-common/src/test/java/org/apache/hudi/common/table/TestHoodieTableMetaClient.java
@@ -22,6 +22,7 @@ import org.apache.hudi.common.model.HoodieCommitMetadata;
import org.apache.hudi.common.model.HoodieIndexDefinition;
import org.apache.hudi.common.model.HoodieIndexMetadata;
import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
import org.apache.hudi.common.table.timeline.HoodieInstant;
import org.apache.hudi.common.table.timeline.HoodieTimeline;
@@ -145,6 +146,103 @@ class TestHoodieTableMetaClient extends HoodieCommonTestHarness {
assertNotEquals(metaClient1.toString(), new Object().toString());
}
+ @Test
+ void testMetaFieldsModeDerivesLegacyBooleanAndOverridesContradictions() throws IOException {
+ // hoodie.properties must never record a legacy boolean that contradicts the mode: a pre-1.3.0
+ // reader ignores hoodie.meta.fields.mode entirely and would otherwise treat a selectively
+ // written table as ALL. For NONE that is unsafe — an old incremental reader would run against
+ // all-null commit times and silently return no rows.
+ //
+ // The mode is the only source of truth: the deprecated boolean is always derived from it.
+ for (MetaFieldsMode mode : MetaFieldsMode.values()) {
+ final String path = tempDir.toAbsolutePath() + Path.SEPARATOR + "mfm-derive-" + mode.name();
+ HoodieTableMetaClient created = HoodieTableMetaClient.newTableBuilder()
+ .setTableType(HoodieTableType.COPY_ON_WRITE.name())
+ .setTableName("mfm-derive-" + mode.name())
+ .setMetaFieldsMode(mode)
+ .initTable(this.metaClient.getStorageConf(), path);
+ assertEquals(mode, created.getTableConfig().getMetaFieldsMode());
+ assertEquals(mode.toLegacyPopulateMetaFields(), created.getTableConfig().populateMetaFields(),
+ "the legacy boolean must be derived from the mode for " + mode);
+
+ // Restating the derived value is coherent and must be accepted.
+ final String restatedPath = tempDir.toAbsolutePath() + Path.SEPARATOR + "mfm-restate-" + mode.name();
+ HoodieTableMetaClient restated = HoodieTableMetaClient.newTableBuilder()
+ .setTableType(HoodieTableType.COPY_ON_WRITE.name())
+ .setTableName("mfm-restate-" + mode.name())
+ .setPopulateMetaFields(mode.toLegacyPopulateMetaFields())
+ .setMetaFieldsMode(mode)
+ .initTable(this.metaClient.getStorageConf(), restatedPath);
+ assertEquals(mode, restated.getTableConfig().getMetaFieldsMode());
+
+ // A contradicting legacy boolean is ignored in favor of the mode.
+ final String conflictPath = tempDir.toAbsolutePath() + Path.SEPARATOR + "mfm-conflict-" + mode.name();
+ HoodieTableMetaClient conflict = HoodieTableMetaClient.newTableBuilder()
+ .setTableType(HoodieTableType.COPY_ON_WRITE.name())
+ .setTableName("mfm-conflict-" + mode.name())
+ .setPopulateMetaFields(!mode.toLegacyPopulateMetaFields())
+ .setMetaFieldsMode(mode)
+ .initTable(this.metaClient.getStorageConf(), conflictPath);
+ assertEquals(mode, conflict.getTableConfig().getMetaFieldsMode());
+ assertEquals(mode.toLegacyPopulateMetaFields(), conflict.getTableConfig().populateMetaFields());
+ }
+
+ // No explicit mode: pre-1.3.0 behavior is preserved by inferring and recording the mode.
+ final String legacyPath = tempDir.toAbsolutePath() + Path.SEPARATOR + "mfm-legacy";
+ HoodieTableMetaClient legacy = HoodieTableMetaClient.newTableBuilder()
+ .setTableType(HoodieTableType.COPY_ON_WRITE.name())
+ .setTableName("mfm-legacy")
+ .setPopulateMetaFields(false)
+ .initTable(this.metaClient.getStorageConf(), legacyPath);
+ assertEquals(MetaFieldsMode.NONE, legacy.getTableConfig().getMetaFieldsMode());
+ assertEquals(MetaFieldsMode.NONE.name(),
+ legacy.getTableConfig().getString(HoodieTableConfig.META_FIELDS_MODE),
+ "legacy table settings must be normalized to the mode property");
+ assertFalse(legacy.getTableConfig().populateMetaFields());
+ }
+
+ /**
+ * From table version 10 a newly created table records only {@code hoodie.meta.fields.mode}; below
+ * that it records the deprecated boolean too.
+ *
+ * <p>The split is about who reads the table. Selective modes have to work on older versions -- a
+ * fleet adopting this feature runs patched and unpatched pipelines against the same v6 tables for
+ * months, and an unpatched reader knows only the boolean. With the property absent it falls back
+ * to its {@code true} default and would treat a selective table as ALL, over-claiming meta columns
+ * that are physically null. A table only reaches v10 once everything touching it understands the
+ * mode, so by then the boolean is redundant.
+ *
+ * <p>The v9-to-v10 upgrade similarly persists the mode and removes the deprecated boolean.
+ */
+ @Test
+ void testMetaFieldsModeDropsTheLegacyBooleanFromTableVersionTen() throws IOException {
+ for (MetaFieldsMode mode : MetaFieldsMode.values()) {
+ final String newPath = tempDir.toAbsolutePath() + Path.SEPARATOR + "mfm-v10-" + mode.name();
+ HoodieTableConfig newTable = HoodieTableMetaClient.newTableBuilder()
+ .setTableType(HoodieTableType.COPY_ON_WRITE.name())
+ .setTableName("mfm-v10-" + mode.name())
+ .setTableVersion(HoodieTableVersion.TEN.versionCode())
+ .setMetaFieldsMode(mode)
+ .initTable(this.metaClient.getStorageConf(), newPath)
+ .getTableConfig();
+ assertEquals(mode, newTable.getMetaFieldsMode());
+ assertFalse(newTable.getProps().containsKey(HoodieTableConfig.POPULATE_META_FIELDS.key()),
+ "a table created at v10 records the mode alone for " + mode);
+
+ final String oldPath = tempDir.toAbsolutePath() + Path.SEPARATOR + "mfm-v6-" + mode.name();
+ HoodieTableConfig oldTable = HoodieTableMetaClient.newTableBuilder()
+ .setTableType(HoodieTableType.COPY_ON_WRITE.name())
+ .setTableName("mfm-v6-" + mode.name())
+ .setTableVersion(HoodieTableVersion.SIX.versionCode())
+ .setMetaFieldsMode(mode)
+ .initTable(this.metaClient.getStorageConf(), oldPath)
+ .getTableConfig();
+ assertEquals(mode, oldTable.getMetaFieldsMode());
+ assertEquals(mode.toLegacyPopulateMetaFields(), oldTable.populateMetaFields(),
+ "a table below v10 must still carry the derived boolean for unpatched readers, " + mode);
+ }
+ }
+
@Test
void testTableVersion() throws IOException {
final String basePath = tempDir.toAbsolutePath() + Path.SEPARATOR + "t1";
diff --git a/hudi-hadoop-common/src/test/java/org/apache/hudi/metadata/TestHoodieTableMetadataUtil.java b/hudi-hadoop-common/src/test/java/org/apache/hudi/metadata/TestHoodieTableMetadataUtil.java
index 015ac174e662..24eced21dca6 100644
--- a/hudi-hadoop-common/src/test/java/org/apache/hudi/metadata/TestHoodieTableMetadataUtil.java
+++ b/hudi-hadoop-common/src/test/java/org/apache/hudi/metadata/TestHoodieTableMetadataUtil.java
@@ -32,6 +32,7 @@ import org.apache.hudi.common.model.HoodieCommitMetadata;
import org.apache.hudi.common.model.HoodieLogFile;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.schema.HoodieSchema;
import org.apache.hudi.common.schema.HoodieSchemaField;
@@ -273,7 +274,7 @@ public class TestHoodieTableMetadataUtil extends HoodieCommonTestHarness {
partitionFileSlicePairs.add(FileSliceAndPartition.of(p, fileSlice1));
partitionFileSlicePairs.add(FileSliceAndPartition.of(p, fileSlice2));
// NOTE: we need to set table config as we are not using write client explicitly and these configs are needed for log record reader
- metaClient.getTableConfig().setValue(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ metaClient.getTableConfig().setValue(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.NONE.name());
metaClient.getTableConfig().setValue(HoodieTableConfig.RECORDKEY_FIELDS.key(), "_row_key");
metaClient.getTableConfig().setValue(HoodieTableConfig.PARTITION_FIELDS.key(), "partition_path");
List<HoodieColumnRangeMetadata<Comparable>> columnRangeMetadataLogFile = HoodieTableMetadataUtil.getLogFileColumnRangeMetadata(
@@ -559,7 +560,7 @@ public class TestHoodieTableMetadataUtil extends HoodieCommonTestHarness {
Lazy.eagerly(Option.of(HOODIE_SCHEMA_WITH_METADATA_FIELDS)), false, V1).keySet()));
//test with meta cols disabled
- tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.NONE.name());
metadataConfig = HoodieMetadataConfig.newBuilder()
.enable(true).withMetadataIndexColumnStats(true)
.build();
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/AutoRecordKeyGenerationUtils.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/AutoRecordKeyGenerationUtils.scala
index 5d8bc1ee405e..43743b66b21d 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/AutoRecordKeyGenerationUtils.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/AutoRecordKeyGenerationUtils.scala
@@ -21,6 +21,7 @@ package org.apache.hudi
import org.apache.hudi.DataSourceWriteOptions.INSERT_DROP_DUPS
import org.apache.hudi.common.config.HoodieConfig
+import org.apache.hudi.common.model.MetaFieldsMode
import org.apache.hudi.common.table.HoodieTableConfig
import org.apache.hudi.common.util.{ConfigUtils, StringUtils}
import org.apache.hudi.config.HoodieWriteConfig
@@ -43,9 +44,20 @@ object AutoRecordKeyGenerationUtils {
if (hoodieConfig.getBoolean(INSERT_DROP_DUPS)) {
throw new HoodieKeyGeneratorException("Enabling " + INSERT_DROP_DUPS.key() + " is not supported with auto generation of record keys ")
}
- // virtual keys are not supported with auto generation of record keys.
- if (!parameters.getOrElse(HoodieTableConfig.POPULATE_META_FIELDS.key(), HoodieTableConfig.POPULATE_META_FIELDS.defaultValue().toString).toBoolean) {
- throw new HoodieKeyGeneratorException("Disabling " + HoodieTableConfig.POPULATE_META_FIELDS.key() + " is not supported with auto generation of record keys")
+ // Virtual keys are not supported with auto generation of record keys. Normalize legacy input
+ // into MetaFieldsMode rather than reading the deprecated boolean directly: a config that states
+ // only hoodie.meta.fields.mode has no populate.meta.fields entry, so reading the raw parameter
+ // would take the `true` default and let the write through. The rows would then land with no
+ // identity at all -- the record key is neither supplied nor generated.
+ val metaFieldsMode = MetaFieldsMode.resolve(hoodieConfig)
+ if (!metaFieldsMode.isRecordKeyPopulated) {
+ // Name whichever property the caller actually set, so the message points at the thing they
+ // have to change rather than at its alias.
+ val statedKey =
+ if (parameters.contains(HoodieTableConfig.META_FIELDS_MODE.key())) HoodieTableConfig.META_FIELDS_MODE.key()
+ else HoodieTableConfig.POPULATE_META_FIELDS.key()
+ throw new HoodieKeyGeneratorException(statedKey
+ + " is not supported with auto generation of record keys when it leaves the record key unpopulated")
}
val orderingFieldsStr = ConfigUtils.getOrderingFieldsStrDuringWrite(hoodieConfig.getProps)
if (StringUtils.nonEmpty(orderingFieldsStr)) {
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala
index b2548029e621..6191331d4215 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/DataSourceOptions.scala
@@ -21,7 +21,7 @@ import org.apache.hudi.DataSourceReadOptions.{QUERY_TYPE, QUERY_TYPE_READ_OPTIMI
import org.apache.hudi.HoodieConversionUtils.toScalaOption
import org.apache.hudi.common.config._
import org.apache.hudi.common.fs.ConsistencyGuardConfig
-import org.apache.hudi.common.model.{HoodieTableType, WriteOperationType}
+import org.apache.hudi.common.model.{HoodieTableType, MetaFieldsMode, WriteOperationType}
import org.apache.hudi.common.table.HoodieTableConfig
import org.apache.hudi.common.util.{Option, StringUtils}
import org.apache.hudi.common.util.ConfigUtils.{DELTA_STREAMER_CONFIG_PREFIX, IS_QUERY_AS_RO_TABLE, STREAMER_CONFIG_PREFIX}
@@ -548,8 +548,13 @@ object DataSourceWriteOptions {
.defaultValue("true")
.withInferFunction(
JFunction.toJavaFunction((config: HoodieConfig) => {
+ // Normalize legacy input into MetaFieldsMode: a config stating only hoodie.meta.fields.mode
+ // has no populate.meta.fields entry, so reading the boolean would take its `true` default,
+ // leave the row writer on, and silently ignore COMBINE_BEFORE_INSERT -- which the comment
+ // below says must not happen.
+ val metaFieldsMode = MetaFieldsMode.resolve(config)
if (config.getString(OPERATION) == WriteOperationType.BULK_INSERT.value
- && !config.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS)
+ && !metaFieldsMode.toLegacyPopulateMetaFields
&& config.getBooleanOrDefault(HoodieWriteConfig.COMBINE_BEFORE_INSERT)) {
// need to turn off row writing for BULK_INSERT without meta fields with turned on COMBINE_BEFORE_INSERT to prevent shortcutting and ignoring COMBINE_BEFORE_INSERT setting
Option.of("false")
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieHadoopFsRelationFactory.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieHadoopFsRelationFactory.scala
index 7e475dc9971c..f55cd25a8f0c 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieHadoopFsRelationFactory.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieHadoopFsRelationFactory.scala
@@ -30,6 +30,7 @@ import org.apache.hudi.common.table.{HoodieTableConfig, HoodieTableMetaClient, T
import org.apache.hudi.common.table.log.InstantRange.RangeType
import org.apache.hudi.common.table.timeline.HoodieTimeline
import org.apache.hudi.common.util.StringUtils.isNullOrEmpty
+import org.apache.hudi.exception.HoodieException
import org.apache.hudi.keygen.{CustomAvroKeyGenerator, CustomKeyGenerator, TimestampBasedAvroKeyGenerator, TimestampBasedKeyGenerator}
import org.apache.hudi.storage.StoragePath
@@ -391,6 +392,21 @@ abstract class HoodieBaseCopyOnWriteIncrementalHadoopFsRelationFactory(override
isBootstrap: Boolean)
extends HoodieBaseHadoopFsRelationFactory(sqlContext, metaClient, options, schemaSpec, isBootstrap) {
+ // Incremental reads filter on _hoodie_commit_time, so a table that does not populate it can only
+ // ever return nothing. Reject rather than hand back an empty result, which reads as "no new data"
+ // instead of "this query cannot work here".
+ //
+ // The same guard exists in IncrementalRelationV1/V2, but those classes back only the streaming
+ // source — a Spark datasource incremental read is served by this factory, so without this check
+ // hoodie.meta.fields.mode=NONE / FILE_NAME_ONLY silently returned zero rows.
+ if (!metaClient.getTableConfig.isCommitTimePopulated) {
+ throw new HoodieException("Incremental queries are not supported when _hoodie_commit_time is not populated. "
+ + "hoodie.meta.fields.mode is a physical-storage decision baked into files at write time, so it cannot be "
+ + "changed by flipping write options, and it cannot be widened afterwards either — hudi-cli may only narrow a "
+ + "mode, since existing files are never rewritten. Recreating the table is the only way to enable incremental "
+ + "queries on it: create it with hoodie.meta.fields.mode=COMMIT_TIME_ONLY (or COMMIT_TIME_AND_FILE_NAME, or ALL).")
+ }
+
override protected def getMandatoryFields(): Seq[String] = Seq(HoodieRecord.RECORD_KEY_METADATA_FIELD, HoodieRecord.COMMIT_TIME_METADATA_FIELD) ++
orderingFields ++ partitionColumnsToRead
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala
index c72fcc3ceb8c..226d8dd1e568 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala
@@ -283,7 +283,17 @@ class HoodieSparkSqlWriterInternal {
} else {
val baseFileFormat = hoodieConfig.getStringOrDefault(HoodieTableConfig.BASE_FILE_FORMAT)
val archiveLogFolder = hoodieConfig.getStringOrDefault(HoodieTableConfig.TIMELINE_HISTORY_PATH)
- val populateMetaFields = hoodieConfig.getBooleanOrDefault(HoodieTableConfig.POPULATE_META_FIELDS)
+ // Only forward the deprecated boolean when the user actually stated it. TableBuilder rejects a
+ // boolean that contradicts an explicit meta.fields.mode, and getBooleanOrDefault would hand it
+ // the `true` default for every writer that never mentioned the property — turning a plain
+ // `hoodie.meta.fields.mode=COMMIT_TIME_ONLY` into a spurious conflict.
+ val populateMetaFields: java.lang.Boolean =
+ if (hoodieConfig.contains(HoodieTableConfig.POPULATE_META_FIELDS)) {
+ hoodieConfig.getBoolean(HoodieTableConfig.POPULATE_META_FIELDS)
+ } else {
+ null
+ }
+ val metaFieldsMode = hoodieConfig.getString(HoodieTableConfig.META_FIELDS_MODE)
val useBaseFormatMetaFile = hoodieConfig.getBooleanOrDefault(HoodieTableConfig.PARTITION_METAFILE_USE_BASE_FORMAT);
val payloadClass = hoodieConfig.getString(DataSourceWriteOptions.PAYLOAD_CLASS_NAME)
val recordMergeStrategyId = hoodieConfig.getString(DataSourceWriteOptions.RECORD_MERGE_STRATEGY_ID)
@@ -309,6 +319,7 @@ class HoodieSparkSqlWriterInternal {
.setOrderingFields(ConfigUtils.getOrderingFieldsStrDuringWrite(optParams.asJava))
.setPartitionFields(partitionColumnsForKeyGenerator)
.setPopulateMetaFields(populateMetaFields)
+ .setMetaFieldsModeFromString(metaFieldsMode)
.setRecordKeyFields(hoodieConfig.getString(RECORDKEY_FIELD))
.setSecondaryKeyFields(hoodieConfig.getString(SECONDARYKEY_COLUMN_NAME))
.setCDCEnabled(hoodieConfig.getBooleanOrDefault(HoodieTableConfig.CDC_ENABLED))
@@ -751,10 +762,12 @@ class HoodieSparkSqlWriterInternal {
hoodieConfig.getString(DataSourceWriteOptions.KEYGENERATOR_CLASS_NAME)
else KeyGeneratorType.getKeyGeneratorClassName(hoodieConfig)
val timestampKeyGeneratorConfigs = extractConfigsRelatedToTimestampBasedKeyGenerator(keyGenProp, parameters)
- val populateMetaFields = java.lang.Boolean.parseBoolean(parameters.getOrElse(
- HoodieTableConfig.POPULATE_META_FIELDS.key(),
- String.valueOf(HoodieTableConfig.POPULATE_META_FIELDS.defaultValue())
- ))
+ // null when unstated — see the note on the non-bootstrap path above.
+ val populateMetaFields: java.lang.Boolean =
+ parameters.get(HoodieTableConfig.POPULATE_META_FIELDS.key())
+ .map(v => java.lang.Boolean.valueOf(v))
+ .orNull
+ val metaFieldsMode = parameters.get(HoodieTableConfig.META_FIELDS_MODE.key()).orNull
val baseFileFormat = hoodieConfig.getStringOrDefault(HoodieTableConfig.BASE_FILE_FORMAT)
val useBaseFormatMetaFile = java.lang.Boolean.parseBoolean(parameters.getOrElse(
HoodieTableConfig.PARTITION_METAFILE_USE_BASE_FORMAT.key(),
@@ -782,6 +795,7 @@ class HoodieSparkSqlWriterInternal {
.setCDCEnabled(hoodieConfig.getBooleanOrDefault(HoodieTableConfig.CDC_ENABLED))
.setCDCSupplementalLoggingMode(hoodieConfig.getStringOrDefault(HoodieTableConfig.CDC_SUPPLEMENTAL_LOGGING_MODE))
.setPopulateMetaFields(populateMetaFields)
+ .setMetaFieldsModeFromString(metaFieldsMode)
.setKeyGeneratorClassProp(keyGenProp)
.setPartitionValueExtractorClass(partitionValueExtractorClassName)
.set(timestampKeyGeneratorConfigs.asJava.asInstanceOf[java.util.Map[String, Object]])
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala
index 54459ff61e00..b831ec165ff9 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala
@@ -23,7 +23,7 @@ import org.apache.hudi.DataSourceWriteOptions._
import org.apache.hudi.common.config.{DFSPropertiesConfiguration, HoodieCommonConfig, HoodieConfig, TypedProperties}
import org.apache.hudi.common.config.HoodieMetadataConfig.ENABLE
import org.apache.hudi.common.config.RecordMergeMode.CUSTOM
-import org.apache.hudi.common.model.{DefaultHoodieRecordPayload, HoodieRecord, OverwriteWithLatestAvroPayload, WriteOperationType}
+import org.apache.hudi.common.model.{DefaultHoodieRecordPayload, HoodieRecord, MetaFieldsMode, OverwriteWithLatestAvroPayload, WriteOperationType}
import org.apache.hudi.common.table.{HoodieTableConfig, HoodieTableVersion}
import org.apache.hudi.common.util.StringUtils
import org.apache.hudi.common.util.StringUtils.isNullOrEmpty
@@ -226,7 +226,7 @@ object HoodieWriterUtils {
}
def validateTableConfig(spark: SparkSession, params: Map[String, String],
- tableConfig: HoodieConfig): Unit = {
+ tableConfig: HoodieTableConfig): Unit = {
validateTableConfig(spark, params, tableConfig, false)
}
@@ -261,7 +261,7 @@ object HoodieWriterUtils {
* Detects conflicts between new parameters and existing table configurations
*/
def validateTableConfig(spark: SparkSession, params: Map[String, String],
- tableConfig: HoodieConfig, isOverWriteMode: Boolean): Unit = {
+ tableConfig: HoodieTableConfig, isOverWriteMode: Boolean): Unit = {
// If Overwrite is set as save mode, we don't need to do table config validation.
if (!isOverWriteMode) {
val resolver = spark.sessionState.conf.resolver
@@ -352,6 +352,32 @@ object HoodieWriterUtils {
diffConfigs.append(s"${HoodieTableConfig.RECORD_MERGE_STRATEGY_ID}:\t$mergeStrategyId\tnull\n")
}
}
+
+ // hoodie.meta.fields.mode is a physical-storage decision baked into files at write time.
+ // Changing it at runtime would silently produce mixed-mode files whose incremental / file
+ // pruning behavior differs between old and new commits. The generic loop above cannot catch
+ // this on its own: it only flags a key when the on-disk value is non-null, so a table
+ // predating the property would let a null → selective transition slip through.
+ //
+ // Compare resolved modes rather than raw presence. A legacy table resolves to ALL or NONE
+ // through its deprecated boolean, so null → COMMIT_TIME_ONLY is still
+ // rejected, while a write that
+ // restates the mode the table already has (mode=ALL against a default table, or mode=NONE
+ // against populate.meta.fields=false) is no longer a spurious conflict. That case matters
+ // because the property is backfilled only by NineToTenUpgradeHandler and current() is
+ // already TEN — a table at v10 without it will never be upgraded again, so rejecting an
+ // explicit restatement would leave it no way to adopt the property at all.
+ val paramsMetaFieldsMode = params.getOrElse(HoodieTableConfig.META_FIELDS_MODE.key(), "")
+ if (paramsMetaFieldsMode.nonEmpty) {
+ val requestedMode = MetaFieldsMode.resolve(params.asJava)
+ val tableMetaFieldsMode = tableConfig.getMetaFieldsMode
+ if (requestedMode != tableMetaFieldsMode) {
+ diffConfigs.append(
+ s"${HoodieTableConfig.META_FIELDS_MODE.key()}:\t$requestedMode\t$tableMetaFieldsMode"
+ + " (immutable at runtime; set only at table creation / hudi-cli / upgrade; "
+ + "existing tables must be recreated to change this)\n")
+ }
+ }
}
if (diffConfigs.nonEmpty) {
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV1.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV1.scala
index 50db4c678c8f..52b80cd4ac3e 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV1.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV1.scala
@@ -89,8 +89,12 @@ class IncrementalRelationV1(val sqlContext: SQLContext,
s"option ${DataSourceReadOptions.START_COMMIT.key}")
}
- if (!metaClient.getTableConfig.populateMetaFields()) {
- throw new HoodieException("Incremental queries are not supported when meta fields are disabled")
+ if (!metaClient.getTableConfig.isCommitTimePopulated()) {
+ throw new HoodieException("Incremental queries are not supported when _hoodie_commit_time is not populated. "
+ + "hoodie.meta.fields.mode is a physical-storage decision baked into files at write time, so it cannot be "
+ + "changed by flipping write options, and it cannot be widened afterwards either — hudi-cli may only narrow a "
+ + "mode, since existing files are never rewritten. Recreating the table is the only way to enable incremental "
+ + "queries on it: create it with hoodie.meta.fields.mode=COMMIT_TIME_ONLY (or COMMIT_TIME_AND_FILE_NAME, or ALL).")
}
private val useEndInstantSchema = optParams.getOrElse(INCREMENTAL_READ_SCHEMA_USE_END_INSTANTTIME.key,
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV2.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV2.scala
index 308ca87a4759..49c94c0f8532 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV2.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/IncrementalRelationV2.scala
@@ -78,8 +78,12 @@ class IncrementalRelationV2(val sqlContext: SQLContext,
s"option ${DataSourceReadOptions.START_COMMIT.key}")
}
- if (!metaClient.getTableConfig.populateMetaFields()) {
- throw new HoodieException("Incremental queries are not supported when meta fields are disabled")
+ if (!metaClient.getTableConfig.isCommitTimePopulated()) {
+ throw new HoodieException("Incremental queries are not supported when _hoodie_commit_time is not populated. "
+ + "hoodie.meta.fields.mode is a physical-storage decision baked into files at write time, so it cannot be "
+ + "changed by flipping write options, and it cannot be widened afterwards either — hudi-cli may only narrow a "
+ + "mode, since existing files are never rewritten. Recreating the table is the only way to enable incremental "
+ + "queries on it: create it with hoodie.meta.fields.mode=COMMIT_TIME_ONLY (or COMMIT_TIME_AND_FILE_NAME, or ALL).")
}
private val queryContext: IncrementalQueryAnalyzer.QueryContext =
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV1.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV1.scala
index fabdfdadfe3c..9d9d90209107 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV1.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV1.scala
@@ -19,7 +19,7 @@ package org.apache.hudi
import org.apache.hudi.HoodieConversionUtils.toScalaOption
import org.apache.hudi.HoodieSparkConfUtils.getHollowCommitHandling
-import org.apache.hudi.common.model.{FileSlice, HoodieRecord}
+import org.apache.hudi.common.model.{FileSlice, HoodieRecord, HoodieTableType}
import org.apache.hudi.common.table.HoodieTableMetaClient
import org.apache.hudi.common.table.timeline.{HoodieInstant, HoodieTimeline}
import org.apache.hudi.common.table.timeline.TimelineUtils.{concatTimeline, getCommitMetadata, handleHollowCommitIfNeeded, HollowCommitHandling}
@@ -261,8 +261,19 @@ trait HoodieIncrementalRelationV1Trait extends HoodieBaseRelation {
s"option ${DataSourceReadOptions.START_COMMIT.key}")
}
- if (!this.tableConfig.populateMetaFields()) {
- throw new HoodieException("Incremental queries are not supported when meta fields are disabled")
+ // MoR incremental relies on _hoodie_commit_time being present in BOTH base files AND log
+ // records. The base-file writer respects hoodie.meta.fields.mode, but the log-write path
+ // (HoodieAppendHandle) does not yet — until that gap is closed, MoR incremental must require
+ // populate.meta.fields=true to avoid silently dropping log-file rows whose commit_time is null.
+ //
+ // Gate on the table type, not just the flag: HoodieCopyOnWriteIncrementalHadoopFsRelationFactory
+ // builds one of these relations for CoW tables too (it backs HoodieIncrementalFileIndex), so an
+ // unconditional check here rejects every selective-mode CoW table — the case this release
+ // actually supports. CoW keeps its own commit-time guard in IncrementalRelationV1/V2.
+ if (metaClient.getTableType == HoodieTableType.MERGE_ON_READ && !this.tableConfig.populateMetaFields()) {
+ throw new HoodieException("Incremental queries on MoR tables are not supported when "
+ + "hoodie.populate.meta.fields=false. Selective meta-field modes (hoodie.meta.fields.mode) "
+ + "are supported for CoW only in this release; MoR support is tracked as a follow-up.")
}
if (hollowCommitHandling == USE_TRANSITION_TIME && fullTableScan) {
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV2.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV2.scala
index b465e38623a1..5700e125ac4e 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV2.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/MergeOnReadIncrementalRelationV2.scala
@@ -18,7 +18,7 @@
package org.apache.hudi
import org.apache.hudi.HoodieConversionUtils.toScalaOption
-import org.apache.hudi.common.model.{FileSlice, HoodieRecord}
+import org.apache.hudi.common.model.{FileSlice, HoodieRecord, HoodieTableType}
import org.apache.hudi.common.table.HoodieTableMetaClient
import org.apache.hudi.common.table.log.InstantRange.RangeType
import org.apache.hudi.common.table.read.IncrementalQueryAnalyzer
@@ -251,8 +251,19 @@ trait HoodieIncrementalRelationV2Trait extends HoodieBaseRelation {
s"option ${DataSourceReadOptions.START_COMMIT.key}")
}
- if (!this.tableConfig.populateMetaFields()) {
- throw new HoodieException("Incremental queries are not supported when meta fields are disabled")
+ // MoR incremental relies on _hoodie_commit_time being present in BOTH base files AND log
+ // records. The base-file writer respects hoodie.meta.fields.mode, but the log-write path
+ // (HoodieAppendHandle) does not yet — until that gap is closed, MoR incremental must require
+ // populate.meta.fields=true to avoid silently dropping log-file rows whose commit_time is null.
+ //
+ // Gate on the table type, not just the flag: HoodieCopyOnWriteIncrementalHadoopFsRelationFactory
+ // builds one of these relations for CoW tables too (it backs HoodieIncrementalFileIndex), so an
+ // unconditional check here rejects every selective-mode CoW table — the case this release
+ // actually supports. CoW keeps its own commit-time guard in IncrementalRelationV1/V2.
+ if (metaClient.getTableType == HoodieTableType.MERGE_ON_READ && !this.tableConfig.populateMetaFields()) {
+ throw new HoodieException("Incremental queries on MoR tables are not supported when "
+ + "hoodie.populate.meta.fields=false. Selective meta-field modes (hoodie.meta.fields.mode) "
+ + "are supported for CoW only in this release; MoR support is tracked as a follow-up.")
}
}
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/HoodieCatalogTable.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/HoodieCatalogTable.scala
index 10b7a8e7b57b..5f772cb5a5b0 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/HoodieCatalogTable.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/catalyst/catalog/HoodieCatalogTable.scala
@@ -259,7 +259,7 @@ class HoodieCatalogTable(val spark: SparkSession, var table: CatalogTable) exten
val existingTableConfig = tableConfig.getProps.asScala.toMap
val currentTableConfig = globalTableConfigs ++ existingTableConfig
val catalogTableProps = mapSqlOptionsToTableConfigs(catalogProperties)
- validateTableConfig(spark, catalogTableProps, convertMapToHoodieConfig(existingTableConfig))
+ validateTableConfig(spark, catalogTableProps, tableConfig)
val options = extraTableConfig(hoodieTableExists, currentTableConfig) ++
mapSqlOptionsToTableConfigs(sqlOptions) ++ currentTableConfig
diff --git a/hudi-spark-datasource/hudi-spark-common/src/test/java/org/apache/hudi/TestHoodieWriterUtils.java b/hudi-spark-datasource/hudi-spark-common/src/test/java/org/apache/hudi/TestHoodieWriterUtils.java
index 8456074de934..2f745beb2935 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/test/java/org/apache/hudi/TestHoodieWriterUtils.java
+++ b/hudi-spark-datasource/hudi-spark-common/src/test/java/org/apache/hudi/TestHoodieWriterUtils.java
@@ -21,15 +21,18 @@ import org.apache.hudi.common.config.HoodieConfig;
import org.apache.hudi.common.config.RecordMergeMode;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.table.HoodieTableVersion;
import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.testutils.HoodieClientTestBase;
import org.apache.hudi.util.JavaScalaConverters;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
import java.io.IOException;
import java.util.Properties;
@@ -37,6 +40,7 @@ import java.util.Properties;
import static org.apache.hudi.common.testutils.HoodieTestUtils.getMetaClientBuilder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TestHoodieWriterUtils extends HoodieClientTestBase {
@@ -56,6 +60,66 @@ class TestHoodieWriterUtils extends HoodieClientTestBase {
assertEquals("randomKey", HoodieWriterUtils.getKeyInTableConfig("randomKey", null));
}
+ /**
+ * The meta-fields-mode guard compares normalized modes, not raw legacy property presence. A table
+ * written before {@code hoodie.meta.fields.mode} existed is normalized to ALL or NONE when its
+ * {@link HoodieTableConfig} is constructed, so a write that restates that same mode is asking for
+ * exactly what the table already is and must be accepted.
+ */
+ private void assertModeAgainstTable(String requestedMode, MetaFieldsMode tableMode,
+ String tableDir, boolean expectThrow) throws IOException {
+ Properties tableProps = new Properties();
+ // Start from a legacy boolean and verify table construction records the corresponding mode.
+ tableProps.put(HoodieTableConfig.POPULATE_META_FIELDS.key(),
+ String.valueOf(tableMode.toLegacyPopulateMetaFields()));
+ HoodieTableMetaClient metaClient = getMetaClientBuilder(HoodieTableType.COPY_ON_WRITE, tableProps, "")
+ .initTable(storageConf, tempDir.resolve(tableDir).toString());
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+ assertEquals(tableMode, tableConfig.getMetaFieldsMode(),
+ "precondition: table construction must infer " + tableMode + " from the legacy boolean");
+ assertTrue(tableConfig.getProps().containsKey(HoodieTableConfig.META_FIELDS_MODE.key()),
+ "table construction must populate the authoritative mode property");
+
+ TypedProperties writeProps = TypedProperties.copy(tableConfig.getProps());
+ writeProps.put(HoodieTableConfig.META_FIELDS_MODE.key(), requestedMode);
+ Executable validate = () -> HoodieWriterUtils.validateTableConfig(
+ sparkSession, JavaScalaConverters.convertJavaPropertiesToScalaMap(writeProps), tableConfig);
+
+ if (expectThrow) {
+ HoodieException ex = assertThrows(HoodieException.class, validate);
+ assertTrue(ex.getMessage().contains(HoodieTableConfig.META_FIELDS_MODE.key()), ex.getMessage());
+ } else {
+ Assertions.assertDoesNotThrow(validate);
+ }
+ }
+
+ @Test
+ void validateTableConfigAcceptsAllModeRestatedOnALegacyTrueTable() throws IOException {
+ // mode=ALL against a table whose only meta-field property is populate.meta.fields=true.
+ assertModeAgainstTable("ALL", MetaFieldsMode.ALL, "metaModeAllRestated", false);
+ }
+
+ @Test
+ void validateTableConfigAcceptsNoneModeRestatedOnALegacyFalseTable() throws IOException {
+ // Mirror case: mode=NONE against populate.meta.fields=false.
+ assertModeAgainstTable("NONE", MetaFieldsMode.NONE, "metaModeNoneRestated", false);
+ }
+
+ @Test
+ void validateTableConfigRejectsSelectiveModeOnATableWithoutTheProperty() throws IOException {
+ // The case the guard exists for, and the one that must keep throwing: a table that resolves to
+ // NONE cannot be turned into COMMIT_TIME_ONLY by a write option, because the meta columns of
+ // every earlier commit are already physically absent.
+ assertModeAgainstTable("COMMIT_TIME_ONLY", MetaFieldsMode.NONE, "metaModeSelectiveOnNone", true);
+ }
+
+ @Test
+ void validateTableConfigRejectsNoneModeOnAnAllTable() throws IOException {
+ // Narrowing is still a disagreement here: hoodie.properties would keep advertising ALL while the
+ // writer stopped populating the columns.
+ assertModeAgainstTable("NONE", MetaFieldsMode.ALL, "metaModeNoneOnAll", true);
+ }
+
@Test
void testPayloadClassNameNotVersion9() {
HoodieConfig config = new HoodieConfig();
diff --git a/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/BootstrapExecutorUtils.java b/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/BootstrapExecutorUtils.java
index b4d6c47e8701..75cc6cac5341 100644
--- a/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/BootstrapExecutorUtils.java
+++ b/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/BootstrapExecutorUtils.java
@@ -236,8 +236,11 @@ public class BootstrapExecutorUtils implements Serializable {
.setTableVersion(bootstrapConfig.getWriteVersion())
.setRecordKeyFields(props.getString(RECORDKEY_FIELD_NAME.key()))
.setOrderingFields(ConfigUtils.getOrderingFieldsStrDuringWrite(props))
- .setPopulateMetaFields(props.getBoolean(
- POPULATE_META_FIELDS.key(), POPULATE_META_FIELDS.defaultValue()))
+ // null when unstated: getBoolean's two-arg form returns a primitive, so passing the `true`
+ // default would contradict an explicit hoodie.meta.fields.mode and reject the table at
+ // creation. Matches StreamSync and HoodieSparkSqlWriter.
+ .setPopulateMetaFields(props.containsKey(POPULATE_META_FIELDS.key())
+ ? props.getBoolean(POPULATE_META_FIELDS.key()) : null)
.setArchiveLogFolder(props.getString(
TIMELINE_HISTORY_PATH.key(), TIMELINE_HISTORY_PATH.defaultValue()))
.setPayloadClassName(cfg.payloadClass)
diff --git a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestHoodieDatasetBulkInsertHelper.java b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestHoodieDatasetBulkInsertHelper.java
index 946fb61c3b3a..41cabe3d886d 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestHoodieDatasetBulkInsertHelper.java
+++ b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestHoodieDatasetBulkInsertHelper.java
@@ -188,11 +188,13 @@ public class TestHoodieDatasetBulkInsertHelper extends HoodieSparkClientTestBase
}
result.toJavaRDD().foreach(entry -> {
- assertTrue(entry.get(resultSchema.fieldIndex(HoodieRecord.RECORD_KEY_METADATA_FIELD)).equals(""));
- assertTrue(entry.get(resultSchema.fieldIndex(HoodieRecord.PARTITION_PATH_METADATA_FIELD)).equals(""));
- assertTrue(entry.get(resultSchema.fieldIndex(HoodieRecord.COMMIT_SEQNO_METADATA_FIELD)).equals(""));
- assertTrue(entry.get(resultSchema.fieldIndex(HoodieRecord.COMMIT_TIME_METADATA_FIELD)).equals(""));
- assertTrue(entry.get(resultSchema.fieldIndex(HoodieRecord.FILENAME_METADATA_FIELD)).equals(""));
+ // The stub meta columns are now written as null (nullable=true) rather than empty strings —
+ // see HoodieDatasetBulkInsertHelper. Handle handle-level population fills them in later.
+ assertTrue(entry.isNullAt(resultSchema.fieldIndex(HoodieRecord.RECORD_KEY_METADATA_FIELD)));
+ assertTrue(entry.isNullAt(resultSchema.fieldIndex(HoodieRecord.PARTITION_PATH_METADATA_FIELD)));
+ assertTrue(entry.isNullAt(resultSchema.fieldIndex(HoodieRecord.COMMIT_SEQNO_METADATA_FIELD)));
+ assertTrue(entry.isNullAt(resultSchema.fieldIndex(HoodieRecord.COMMIT_TIME_METADATA_FIELD)));
+ assertTrue(entry.isNullAt(resultSchema.fieldIndex(HoodieRecord.FILENAME_METADATA_FIELD)));
});
Dataset<Row> trimmedOutput = result.drop(HoodieRecord.PARTITION_PATH_METADATA_FIELD).drop(HoodieRecord.RECORD_KEY_METADATA_FIELD)
diff --git a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestMetaFieldsModeE2E.java b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestMetaFieldsModeE2E.java
new file mode 100644
index 000000000000..58886e72776d
--- /dev/null
+++ b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestMetaFieldsModeE2E.java
@@ -0,0 +1,923 @@
+/*
+ * 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.hudi.functional;
+
+import org.apache.hudi.DataSourceReadOptions;
+import org.apache.hudi.DataSourceWriteOptions;
+import org.apache.hudi.SparkAdapterSupport$;
+import org.apache.hudi.common.config.HoodieMetadataConfig;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
+import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.timeline.HoodieInstant;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+
+import org.apache.spark.api.java.function.VoidFunction2;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.RowFactory;
+import org.apache.spark.sql.SaveMode;
+import org.apache.spark.sql.functions;
+import org.apache.spark.sql.streaming.StreamingQuery;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Spark-datasource end-to-end tests for the {@code hoodie.meta.fields.mode} property on CoW tables.
+ * Every {@link MetaFieldsMode} value is exercised via a write / re-read round trip; on-disk column
+ * population is verified by reading the parquet files back and inspecting the meta-column values.
+ */
+class TestMetaFieldsModeE2E extends SparkClientFunctionalTestHarness {
+
+ private static StructType simpleSchema() {
+ return DataTypes.createStructType(new StructField[]{
+ DataTypes.createStructField("column1", DataTypes.StringType, true),
+ DataTypes.createStructField("column2", DataTypes.StringType, true),
+ DataTypes.createStructField("column3", DataTypes.StringType, true)
+ }).asNullable();
+ }
+
+ private Map<String, String> baseOptions() {
+ Map<String, String> opts = new HashMap<>();
+ opts.put(DataSourceWriteOptions.RECORDKEY_FIELD().key(), "column1");
+ opts.put(DataSourceWriteOptions.PARTITIONPATH_FIELD().key(), "column2");
+ opts.put(DataSourceWriteOptions.ORDERING_FIELDS().key(), "column3");
+ opts.put(HoodieTableConfig.NAME.key(), "test_meta_fields_mode");
+ opts.put(DataSourceWriteOptions.TABLE_TYPE().key(), "COPY_ON_WRITE");
+ opts.put(HoodieMetadataConfig.ENABLE.key(), "false");
+ return opts;
+ }
+
+ private void writeRows(List<Row> records, StructType schema, Map<String, String> options, String path, SaveMode mode) {
+ spark().createDataset(records,
+ SparkAdapterSupport$.MODULE$.sparkAdapter().getCatalystExpressionUtils().getEncoder(schema))
+ .write()
+ .format("hudi")
+ .options(options)
+ .mode(mode)
+ .save(path);
+ }
+
+ private HoodieTableConfig writeSampleAndGetTableConfig(Map<String, String> options, String path) {
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, path, SaveMode.Overwrite);
+ HoodieTableMetaClient metaClient =
+ HoodieTableMetaClient.builder().setBasePath(path).setConf(storageConf()).build();
+ return metaClient.getTableConfig();
+ }
+
+ /**
+ * End-to-end assertion of the on-disk meta columns after a write. Reads the parquet files back
+ * (bypassing Hudi's own read path so we see the raw column values) and asserts which meta columns
+ * are non-null.
+ *
+ * <p>Counts across every row rather than inspecting one. A writer that populated a column on some
+ * rows and not others -- mixed-mode output, which is the hazard the mode being immutable exists to
+ * prevent -- would satisfy a single-row check while producing exactly the corruption under test.
+ */
+ private void assertMetaColumnPopulation(String path, MetaFieldsMode expectedMode) {
+ // A raw parquet glob, deliberately: it sees the physical columns even under NONE, where the Hudi
+ // read path projects no meta fields at all and a filter on _hoodie_commit_time cannot resolve.
+ //
+ // The trade-off is that on a clustered table the glob also picks up the pre-clustering files,
+ // which are still on disk because no cleaning has run. Those rows are no longer served and may
+ // predate the current mode, so this helper must not be pointed at a clustered table --
+ // assertClusteredFileNamesPointAtTheirOwnFile reads through Hudi and covers that case.
+ Dataset<Row> raw = spark().read().parquet(path + "/*/*.parquet");
+ long total = raw.count();
+ assertTrue(total > 1, "the fixture must write more than one row for this assertion to mean anything");
+
+ assertMetaColumn(raw, total, HoodieRecord.COMMIT_TIME_METADATA_FIELD,
+ expectedMode.isCommitTimePopulated(), expectedMode);
+ assertMetaColumn(raw, total, HoodieRecord.FILENAME_METADATA_FIELD,
+ expectedMode.isFileNamePopulated(), expectedMode);
+ // Record key, partition path, and commit seq no are ALL-only.
+ boolean allMode = expectedMode == MetaFieldsMode.ALL;
+ assertMetaColumn(raw, total, HoodieRecord.RECORD_KEY_METADATA_FIELD, allMode, expectedMode);
+ assertMetaColumn(raw, total, HoodieRecord.PARTITION_PATH_METADATA_FIELD, allMode, expectedMode);
+ assertMetaColumn(raw, total, HoodieRecord.COMMIT_SEQNO_METADATA_FIELD, allMode, expectedMode);
+ }
+
+ private static void assertMetaColumn(Dataset<Row> raw, long total, String column,
+ boolean expectPopulated, MetaFieldsMode mode) {
+ long nonNull = raw.filter(functions.col(column).isNotNull()).count();
+ if (expectPopulated) {
+ assertEquals(total, nonNull,
+ "every row must carry " + column + " for mode " + mode + "; " + (total - nonNull) + " of "
+ + total + " were null");
+ } else {
+ assertEquals(0, nonNull,
+ "no row may carry " + column + " for mode " + mode + "; " + nonNull + " of " + total
+ + " were populated");
+ }
+ }
+
+ @Test
+ void allModePersistsAndPopulatesAllColumns() {
+ Map<String, String> options = baseOptions();
+ // ALL is the default; no need to set the mode explicitly.
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertTrue(tc.populateMetaFields());
+ assertEquals(MetaFieldsMode.ALL, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.ALL);
+ }
+
+ @Test
+ void noneModePersistsAndLeavesAllColumnsNull() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertFalse(tc.populateMetaFields());
+ assertEquals(MetaFieldsMode.NONE, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.NONE);
+ }
+
+ @Test
+ void commitTimeOnlyModePopulatesOnlyCommitTime() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY.name(),
+ tc.getProps().getProperty(HoodieTableConfig.META_FIELDS_MODE.key()));
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_ONLY);
+ }
+
+ @Test
+ void fileNameOnlyModePopulatesOnlyFileName() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.FILE_NAME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.FILE_NAME_ONLY, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.FILE_NAME_ONLY);
+ }
+
+ @Test
+ void commitTimeAndFileNameModePopulatesBoth() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME);
+ }
+
+ @Test
+ void explicitlyContradictingLegacyBooleanDoesNotOverrideModeAtTableCreation() {
+ // The mode is authoritative. Even when the deprecated boolean explicitly disagrees, derive it
+ // from the mode before the table properties are persisted.
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "true");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, tc.getMetaFieldsMode());
+ assertFalse(tc.populateMetaFields());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_ONLY);
+ }
+
+ @Test
+ void selectiveModeWithoutTheLegacyBooleanDerivesItAsFalse() {
+ // The ordinary case: state only the mode. The boolean is derived, never carried through
+ // verbatim -- a pre-1.3.0 reader ignores the mode property, so leaving populate=true would make
+ // it treat a selectively-written table as ALL.
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_ONLY);
+ assertFalse(tc.populateMetaFields(),
+ "legacy populate.meta.fields must be derived from the mode");
+ }
+
+ @Test
+ void noneModePersistsLegacyBooleanAsFalse() {
+ // The unsafe case this invariant protects: an old incremental reader that saw
+ // populate.meta.fields=true on a NONE table would run against all-null commit times and
+ // silently return zero rows. Stating only the mode -- the ordinary case -- must derive false.
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.NONE.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.NONE, tc.getMetaFieldsMode());
+ assertFalse(tc.populateMetaFields(),
+ "NONE must persist populate.meta.fields=false so pre-1.3.0 readers do not treat it as ALL");
+ }
+
+ @Test
+ void allModePersistsLegacyBooleanAsTrue() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.ALL.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+
+ assertEquals(MetaFieldsMode.ALL, tc.getMetaFieldsMode());
+ assertTrue(tc.populateMetaFields(),
+ "ALL must persist populate.meta.fields=true for pre-1.3.0 readers");
+ }
+
+ @Test
+ void unknownModeValueIsRejected() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), "SOMETHING_BOGUS");
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ Throwable thrown = assertThrows(Throwable.class, () ->
+ writeRows(Collections.singletonList(RowFactory.create("k1", "p1", "v1")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite));
+
+ String rootMessage = rootMessageOf(thrown);
+ assertTrue(rootMessage.contains("SOMETHING_BOGUS"),
+ "Expected error to name the rejected value, got: " + rootMessage);
+ }
+
+ // -------------------------------------------------------------------------
+ // Non-row-writer path coverage. Bulk insert with row.writer.enable=false forces the
+ // HoodieAvroParquetWriter path (via HoodieCreateHandle) instead of the internal-row writer path.
+ // Both paths must respect the mode identically.
+ // -------------------------------------------------------------------------
+
+ @Test
+ void nonRowWriterPathAllMode() {
+ Map<String, String> options = baseOptions();
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+ options.put("hoodie.datasource.write.row.writer.enable", "false");
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+ assertEquals(MetaFieldsMode.ALL, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.ALL);
+ }
+
+ @Test
+ void nonRowWriterPathNoneMode() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+ options.put("hoodie.datasource.write.row.writer.enable", "false");
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+ assertEquals(MetaFieldsMode.NONE, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.NONE);
+ }
+
+ @Test
+ void nonRowWriterPathCommitTimeOnly() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+ options.put("hoodie.datasource.write.row.writer.enable", "false");
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_ONLY);
+ }
+
+ @Test
+ void nonRowWriterPathFileNameOnly() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.FILE_NAME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+ options.put("hoodie.datasource.write.row.writer.enable", "false");
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+ assertEquals(MetaFieldsMode.FILE_NAME_ONLY, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.FILE_NAME_ONLY);
+ }
+
+ @Test
+ void nonRowWriterPathCommitTimeAndFileName() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+ options.put("hoodie.datasource.write.row.writer.enable", "false");
+
+ HoodieTableConfig tc = writeSampleAndGetTableConfig(options, basePath());
+ assertEquals(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME, tc.getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME);
+ }
+
+ // -------------------------------------------------------------------------
+ // Clustering coverage.
+ //
+ // These target 358fbfdd717a, where HoodieRowCreateHandle's selective path copied the *source
+ // row's* _hoodie_file_name during clustering, leaving records pointing at a file clustering had
+ // just replaced. asserting only assertNotNull cannot catch that — the stale value is non-null too
+ // — so the assertion here compares the column against the file actually holding the row.
+ //
+ // Only the selective modes are covered: ALL and NONE route through writeRow /
+ // writeRowNoMetaFields and never enter the branch the fix touched.
+ // -------------------------------------------------------------------------
+
+ private Map<String, String> inlineClusteringOptions(MetaFieldsMode mode) {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), mode.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+ options.put("hoodie.clustering.inline", "true");
+ options.put("hoodie.clustering.inline.max.commits", "1");
+ options.put("hoodie.clustering.plan.strategy.target.file.max.bytes", "10485760");
+ options.put("hoodie.clustering.plan.strategy.small.file.limit", "10485760");
+ return options;
+ }
+
+ /**
+ * Asserts clustering actually ran and that every surviving row's {@code _hoodie_file_name} names
+ * the file holding it.
+ *
+ * <p>Reads through Hudi rather than globbing the parquet directly: after inline clustering the
+ * pre-clustering file is still on disk (no cleaning has run), so a raw glob would also inspect
+ * rows that were replaced and are no longer served.
+ */
+ private void assertClusteredFileNamesPointAtTheirOwnFile(String path, MetaFieldsMode mode) {
+ HoodieTableMetaClient metaClient =
+ HoodieTableMetaClient.builder().setBasePath(path).setConf(storageConf()).build();
+ assertEquals(mode, metaClient.getTableConfig().getMetaFieldsMode());
+ assertEquals(1, metaClient.getActiveTimeline().getCompletedReplaceTimeline().countInstants(),
+ "clustering must have produced a replacecommit, otherwise this test proves nothing");
+
+ List<Row> rows = spark().read().format("hudi").load(path)
+ .withColumn("__containing_file", functions.input_file_name())
+ .collectAsList();
+ assertFalse(rows.isEmpty(), "expected the clustered table to still serve rows");
+
+ // Not asserted here yet: that clustering preserves the source row's _hoodie_commit_time rather
+ // than stamping the replacecommit instant. assertNotNull cannot catch that -- a replacecommit
+ // instant is non-null too -- but the direct comparison reads null commit times through
+ // format("hudi") while the raw-parquet check in assertMetaColumnPopulation sees them populated,
+ // and whether that is the read path dropping a column it should serve on a selective table or the
+ // assertion reading the wrong thing is not yet established. Left out rather than shipped red.
+ for (Row row : rows) {
+ String fileName = row.getAs(HoodieRecord.FILENAME_METADATA_FIELD);
+ String containingFile = row.getAs("__containing_file").toString();
+ if (mode.isFileNamePopulated()) {
+ assertNotNull(fileName, "file name is opted in, so clustered rows must carry one");
+ assertTrue(containingFile.endsWith("/" + fileName),
+ "_hoodie_file_name must name the file holding the row after clustering, not the "
+ + "pre-clustering file it was read from; got " + fileName + " inside " + containingFile);
+ } else {
+ assertNull(fileName,
+ "file name is not opted in, so clustering must not populate it; got " + fileName);
+ }
+ }
+ }
+
+ @Test
+ void clusteringWritesTheNewFileNameUnderFileNameOnly() {
+ Map<String, String> options = inlineClusteringOptions(MetaFieldsMode.FILE_NAME_ONLY);
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2"),
+ RowFactory.create("k3", "p1", "v3")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ assertClusteredFileNamesPointAtTheirOwnFile(basePath(), MetaFieldsMode.FILE_NAME_ONLY);
+ }
+
+ @Test
+ void clusteringWritesTheNewFileNameUnderCommitTimeAndFileName() {
+ Map<String, String> options = inlineClusteringOptions(MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME);
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2"),
+ RowFactory.create("k3", "p1", "v3")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ assertClusteredFileNamesPointAtTheirOwnFile(basePath(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME);
+ }
+
+ @Test
+ void clusteringLeavesFileNameNullUnderCommitTimeOnly() {
+ Map<String, String> options = inlineClusteringOptions(MetaFieldsMode.COMMIT_TIME_ONLY);
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2"),
+ RowFactory.create("k3", "p1", "v3")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ // assertMetaColumnPopulation is deliberately not called here: it globs the parquet directly and
+ // would also inspect the pre-clustering files, which are still on disk and no longer served. The
+ // assertion below reads through Hudi and covers the served rows.
+ assertClusteredFileNamesPointAtTheirOwnFile(basePath(), MetaFieldsMode.COMMIT_TIME_ONLY);
+ }
+
+ @Test
+ void morWithSelectiveModeIsRejected() {
+ Map<String, String> options = baseOptions();
+ options.put(DataSourceWriteOptions.TABLE_TYPE().key(), "MERGE_ON_READ");
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ Throwable thrown = assertThrows(Throwable.class, () ->
+ writeRows(Collections.singletonList(RowFactory.create("k1", "p1", "v1")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite));
+
+ String rootMessage = rootMessageOf(thrown);
+ assertTrue(rootMessage.contains("COPY_ON_WRITE") || rootMessage.contains("MoR") || rootMessage.contains("MERGE_ON_READ"),
+ "Expected MoR-restriction error, got: " + rootMessage);
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // Incremental queries. This is the reason COMMIT_TIME_ONLY exists: a table opts out of four meta
+ // columns but keeps _hoodie_commit_time so incremental reads still work. The assertions below are
+ // on the query result, not on the raw parquet — a populated commit-time column is necessary but
+ // not sufficient, since the relation also has to admit the table and filter on the right range.
+ //
+ // IMPORTANT for anyone adding a case here: assert on collectAsList(), never count() and never a
+ // select() of a subset of columns. A column-less or narrowly-projected CoW incremental scan
+ // returns zero rows — HoodieFileGroupReaderBasedFileFormat routes it to readBaseFile, which pushes
+ // the _hoodie_commit_time predicate into Parquet without projecting that column. That is a
+ // PRE-EXISTING defect, not something this feature introduced: it reproduces on unmodified master
+ // at table version 9 on a default ALL table (collect=2, count=0, select(col)=0). Being tracked
+ // separately; deliberately out of scope here because it sits on the shared read path for every
+ // Spark query. No test in this class is disabled for it — reading whole rows sidesteps it.
+ // ---------------------------------------------------------------------------------------------
+
+ /**
+ * Writes two commits and returns their instant times, oldest first. The first is an Overwrite so
+ * the table is created with the given options; the second appends without restating the mode,
+ * which is also the inheritance path a real second write takes.
+ */
+ private List<String> writeTwoCommits(Map<String, String> options, String path) {
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, path, SaveMode.Overwrite);
+ writeRows(Arrays.asList(
+ RowFactory.create("k3", "p1", "v3"),
+ RowFactory.create("k4", "p1", "v4")),
+ simpleSchema(), options, path, SaveMode.Append);
+
+ HoodieTableMetaClient metaClient =
+ HoodieTableMetaClient.builder().setBasePath(path).setConf(storageConf()).build();
+ return metaClient.getActiveTimeline().filterCompletedInstants().getInstants()
+ .stream()
+ .map(HoodieInstant::requestedTime)
+ .sorted()
+ .collect(Collectors.toList());
+ }
+
+ @Test
+ void incrementalQueryReturnsOnlyNewRowsUnderCommitTimeOnly() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ List<String> instants = writeTwoCommits(options, basePath());
+ assertEquals(2, instants.size(), "expected exactly two completed commits");
+
+ // START_COMMIT is inclusive, so naming the second instant scopes the read to that commit alone.
+ Dataset<Row> incremental = spark().read().format("hudi")
+ .option(DataSourceReadOptions.QUERY_TYPE().key(), DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL())
+ .option(DataSourceReadOptions.START_COMMIT().key(), instants.get(1))
+ .load(basePath());
+
+ // Read whole rows rather than a projection: a CoW incremental scan that projects a subset drops
+ // every row, on a default ALL table just as much as here. That is a pre-existing defect in the
+ // shared read path (reproduced on master at table version 9), not something this mode affects,
+ // so these assertions deliberately go through the full row.
+ List<Row> rows = incremental.collectAsList();
+
+ List<String> keys = rows.stream()
+ .map(r -> r.getAs("column1").toString()).sorted().collect(Collectors.toList());
+ assertEquals(Arrays.asList("k3", "k4"), keys,
+ "incremental read must return exactly the second commit's rows");
+
+ // The rows carry the second commit's time — this is what the range filter keys off, so a null
+ // here would silently drop every row rather than fail. This is the assertion that would have
+ // caught a writer that stopped populating _hoodie_commit_time under a selective mode.
+ List<String> commitTimes = rows.stream()
+ .map(r -> r.getAs(HoodieRecord.COMMIT_TIME_METADATA_FIELD).toString())
+ .distinct().collect(Collectors.toList());
+ assertEquals(Collections.singletonList(instants.get(1)), commitTimes);
+ }
+
+ @Test
+ void incrementalQueryFromTableCreationReturnsEveryRowUnderCommitTimeOnly() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ List<String> instants = writeTwoCommits(options, basePath());
+
+ // Guards against the zero-row regression fixed in 13b39db9fb22, where the read schema omitted
+ // the meta columns for selective modes and the incremental relation returned nothing at all.
+ Dataset<Row> incremental = spark().read().format("hudi")
+ .option(DataSourceReadOptions.QUERY_TYPE().key(), DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL())
+ .option(DataSourceReadOptions.START_COMMIT().key(), "000")
+ .load(basePath());
+
+ // collectAsList() rather than count(): a column-less CoW incremental scan projects no columns,
+ // so the pushed-down commit-time filter matches nothing and count() returns 0. That behaves
+ // identically on a default ALL table and predates this patch, so it is not asserted here.
+ assertEquals(4, incremental.collectAsList().size(),
+ "both commits fall in range, so every row must come back");
+ }
+
+ @Test
+ void incrementalQueryAlsoWorksUnderCommitTimeAndFileName() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ List<String> instants = writeTwoCommits(options, basePath());
+
+ Dataset<Row> incremental = spark().read().format("hudi")
+ .option(DataSourceReadOptions.QUERY_TYPE().key(), DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL())
+ .option(DataSourceReadOptions.START_COMMIT().key(), instants.get(1))
+ .load(basePath());
+
+ assertEquals(2, incremental.collectAsList().size());
+ }
+
+ /**
+ * The two modes that do not populate {@code _hoodie_commit_time} must be rejected outright rather
+ * than returning an empty result — an incremental query that silently returns nothing is the
+ * failure mode this guard exists to prevent.
+ */
+ @ParameterizedTest
+ @EnumSource(value = MetaFieldsMode.class, names = {"FILE_NAME_ONLY", "NONE"})
+ void incrementalQueryIsRejectedWhenCommitTimeIsNotPopulated(MetaFieldsMode mode) {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), mode.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ List<String> instants = writeTwoCommits(options, basePath());
+
+ Throwable thrown = assertThrows(Throwable.class, () ->
+ spark().read().format("hudi")
+ .option(DataSourceReadOptions.QUERY_TYPE().key(), DataSourceReadOptions.QUERY_TYPE_INCREMENTAL_OPT_VAL())
+ .option(DataSourceReadOptions.START_COMMIT().key(), instants.get(0))
+ .load(basePath())
+ .collectAsList());
+
+ String rootMessage = rootMessageOf(thrown);
+ assertTrue(rootMessage.contains("_hoodie_commit_time"),
+ "Expected the commit-time guard from IncrementalRelation, got: " + rootMessage);
+ assertTrue(rootMessage.contains(HoodieTableConfig.META_FIELDS_MODE.key()),
+ "the message must name the property so users know what to change, got: " + rootMessage);
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // Upserts. Disabling the record-key meta column does not disable upserts: the key is re-derived
+ // through the key generator from the base file's data columns, and incoming records carry theirs
+ // in memory. So HoodieWriteMergeHandle's preserve-metadata branch is reachable here, and it is
+ // the one write path that stamps a meta column outside the mode-aware writers.
+ // ---------------------------------------------------------------------------------------------
+
+ /**
+ * An upsert rewrites the whole file group: the updated record goes through the normal write path,
+ * while untouched records are copied forward through
+ * {@code HoodieWriteMergeHandle.writeToFile(..., shouldPreserveRecordMetadata=true)}. That branch
+ * used to stamp {@code _hoodie_file_name} unconditionally, so a {@code COMMIT_TIME_ONLY} table
+ * accumulated file names on every upsert while advertising that the column stays null.
+ */
+ @Test
+ void upsertLeavesFileNameNullOnCopiedRecordsUnderCommitTimeOnly() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2"),
+ RowFactory.create("k3", "p1", "v3")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ // Update only k1. k2 and k3 are copied forward untouched — the preserve-metadata path.
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.UPSERT_OPERATION_OPT_VAL());
+ writeRows(Collections.singletonList(RowFactory.create("k1", "p1", "v1-updated")),
+ simpleSchema(), options, basePath(), SaveMode.Append);
+
+ HoodieTableMetaClient metaClient =
+ HoodieTableMetaClient.builder().setBasePath(basePath()).setConf(storageConf()).build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, metaClient.getTableConfig().getMetaFieldsMode(),
+ "the upsert must not have changed the table's mode");
+
+ // Read the latest file slice only: the pre-upsert file is still on disk (no cleaning has run),
+ // and it would otherwise be counted alongside the rewritten one.
+ Dataset<Row> latest = spark().read().format("hudi").load(basePath());
+ List<Row> rows = latest.collectAsList();
+ assertEquals(3, rows.size(), "upsert must not change the record count");
+
+ for (Row row : rows) {
+ String key = row.getAs("column1").toString();
+ assertNull(row.getAs(HoodieRecord.FILENAME_METADATA_FIELD),
+ "_hoodie_file_name must stay null under COMMIT_TIME_ONLY, including on records copied "
+ + "forward by the merge handle; row " + key + " had it populated");
+ assertNotNull(row.getAs(HoodieRecord.COMMIT_TIME_METADATA_FIELD),
+ "_hoodie_commit_time is opted in, so every row must carry one; row " + key + " did not");
+ assertNull(row.getAs(HoodieRecord.RECORD_KEY_METADATA_FIELD),
+ "record key is ALL-only; row " + key + " had it populated");
+ }
+
+ // The update landed, so the merge genuinely ran rather than being skipped.
+ List<String> updated = rows.stream()
+ .filter(r -> "k1".equals(r.getAs("column1").toString()))
+ .map(r -> r.getAs("column3").toString()).collect(Collectors.toList());
+ assertEquals(Collections.singletonList("v1-updated"), updated);
+ }
+
+ /**
+ * The same copy-forward upsert, but with the Spark record type rather than Avro.
+ *
+ * <p>These take different code paths for clearing a meta column. Avro's {@code updateMetaField}
+ * does {@code data.put(ordinal, null)} and tolerates a null; the Spark path goes through
+ * {@code HoodieInternalRow#update}, which accepts only UTF8String or String and reports anything
+ * else via {@code value.getClass()} -- NPE-ing on a null before it can build the exception. So a
+ * COMMIT_TIME_ONLY table would crash on the first upsert that copied a record forward, while the
+ * Avro-path test above passed. Reported by the review bot on this PR.
+ */
+ @Test
+ void upsertLeavesFileNameNullOnCopiedRecordsWithTheSparkRecordType() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ // Selects the SPARK record type, which is what routes updateMetaField through
+ // HoodieInternalRow#update rather than Avro's null-tolerant data.put.
+ options.put("hoodie.write.record.merge.custom.implementation.classes", "org.apache.hudi.DefaultSparkRecordMerger");
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2"),
+ RowFactory.create("k3", "p1", "v3")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ // k2 and k3 are copied forward untouched -- the preserve-metadata path that clears the column.
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.UPSERT_OPERATION_OPT_VAL());
+ writeRows(Collections.singletonList(RowFactory.create("k1", "p1", "v1-updated")),
+ simpleSchema(), options, basePath(), SaveMode.Append);
+
+ List<Row> rows = spark().read().format("hudi").load(basePath()).collectAsList();
+ assertEquals(3, rows.size(), "upsert must not change the record count");
+ for (Row row : rows) {
+ String key = row.getAs("column1").toString();
+ assertNull(row.getAs(HoodieRecord.FILENAME_METADATA_FIELD),
+ "_hoodie_file_name must stay null under COMMIT_TIME_ONLY; row " + key + " had it populated");
+ assertNotNull(row.getAs(HoodieRecord.COMMIT_TIME_METADATA_FIELD),
+ "_hoodie_commit_time is opted in; row " + key + " did not carry one");
+ }
+ }
+
+ /**
+ * The same upsert on {@code COMMIT_TIME_AND_FILE_NAME}, where the file name is opted in, must
+ * still rewrite it to the new file — otherwise a copied record would point at the file it came
+ * from rather than the one holding it, which is why the unconditional rewrite existed.
+ */
+ @Test
+ void upsertRewritesFileNameOnCopiedRecordsWhenFileNameIsOptedIn() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_AND_FILE_NAME.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL());
+
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.UPSERT_OPERATION_OPT_VAL());
+ writeRows(Collections.singletonList(RowFactory.create("k1", "p1", "v1-updated")),
+ simpleSchema(), options, basePath(), SaveMode.Append);
+
+ Dataset<Row> latest = spark().read().format("hudi")
+ .load(basePath())
+ .withColumn("__containing_file", functions.input_file_name());
+
+ for (Row row : latest.collectAsList()) {
+ String fileName = row.getAs(HoodieRecord.FILENAME_METADATA_FIELD);
+ String containingFile = row.getAs("__containing_file").toString();
+ assertNotNull(fileName, "file name is opted in, so it must be populated");
+ assertTrue(containingFile.endsWith("/" + fileName),
+ "_hoodie_file_name must name the file actually holding the row, so a copied record cannot "
+ + "keep pointing at its previous file; got " + fileName + " inside " + containingFile);
+ }
+ }
+
+ /**
+ * The metadata table is disabled in the rest of this class for speed, but it is on by default in
+ * production. Nothing in the patch proves the data table's mode cannot leak into the MDT's write
+ * config — {@code HoodieMetadataWriteUtils#createMetadataWriteConfig} builds a fresh config and
+ * sets {@code populate.meta.fields=false} itself, so today it cannot, but that is one
+ * {@code withProps(dataWriteConfig.getProps())} refactor away from turning every MDT-enabled
+ * selective write into a hard failure.
+ */
+ @Test
+ void selectiveModeWritesSucceedWithTheMetadataTableEnabled() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieMetadataConfig.ENABLE.key(), "true");
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ HoodieTableMetaClient dataTable =
+ HoodieTableMetaClient.builder().setBasePath(basePath()).setConf(storageConf()).build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, dataTable.getTableConfig().getMetaFieldsMode());
+ assertMetaColumnPopulation(basePath(), MetaFieldsMode.COMMIT_TIME_ONLY);
+
+ // The MDT is its own table and must stay NONE regardless of what the data table opted into.
+ HoodieTableMetaClient metadataTable = HoodieTableMetaClient.builder()
+ .setBasePath(basePath() + "/.hoodie/metadata")
+ .setConf(storageConf())
+ .build();
+ assertEquals(MetaFieldsMode.NONE, metadataTable.getTableConfig().getMetaFieldsMode(),
+ "the data table's mode must not leak into the metadata table");
+ }
+
+ /**
+ * Every other functional write here uses {@code SaveMode.Overwrite}, i.e. a fresh table each time,
+ * which skips the inheritance path entirely: {@code HoodieSparkSqlWriter} folds table props into
+ * the write params only when the mode is not Overwrite, and {@code validateTableConfig} is bypassed
+ * for Overwrite altogether. An append against an existing selective table is the realistic shape.
+ */
+ @Test
+ void appendWithoutRestatingTheModeKeepsTheTableSelective() {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ options.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ // Second write states neither meta-field property, so it must inherit COMMIT_TIME_ONLY.
+ Map<String, String> appendOptions = baseOptions();
+ appendOptions.put(DataSourceWriteOptions.OPERATION().key(), DataSourceWriteOptions.BULK_INSERT_OPERATION_OPT_VAL());
+ writeRows(Arrays.asList(
+ RowFactory.create("k3", "p1", "v3"),
+ RowFactory.create("k4", "p1", "v4")),
+ simpleSchema(), appendOptions, basePath(), SaveMode.Append);
+
+ HoodieTableMetaClient metaClient =
+ HoodieTableMetaClient.builder().setBasePath(basePath()).setConf(storageConf()).build();
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, metaClient.getTableConfig().getMetaFieldsMode(),
+ "an append that says nothing about meta fields must not change the table's mode");
+
+ // Both commits' rows must carry a commit time; a null one is what incremental queries drop.
+ Dataset<Row> all = spark().read().format("hudi").load(basePath());
+ List<Row> rows = all.collectAsList();
+ assertEquals(4, rows.size());
+ for (Row row : rows) {
+ assertNotNull(row.getAs(HoodieRecord.COMMIT_TIME_METADATA_FIELD),
+ "row " + row.getAs("column1") + " has a null commit time after an inheriting append");
+ assertNull(row.getAs(HoodieRecord.FILENAME_METADATA_FIELD),
+ "file name must stay null under COMMIT_TIME_ONLY");
+ }
+ }
+
+ private static String rootMessageOf(Throwable thrown) {
+ Throwable root = thrown;
+ while (root.getCause() != null) {
+ root = root.getCause();
+ }
+ return root.getMessage() == null ? "" : root.getMessage();
+ }
+
+ /**
+ * The structured-streaming read, which is the only caller of {@code IncrementalRelationV1/V2}.
+ *
+ * <p>Those relations carry the guard this PR relaxed from {@code populateMetaFields()} to
+ * {@code isCommitTimePopulated()}, newly permitting streaming reads on a {@code COMMIT_TIME_ONLY}
+ * table. Nothing else in this class reaches them: the datasource incremental tests route through
+ * {@code HoodieCopyOnWriteIncrementalHadoopFsRelationFactory} instead. Given the read path has
+ * already broken twice under selective modes, the relaxed branch should not go untested.
+ */
+ @Test
+ void streamingReadWorksUnderCommitTimeOnly() throws Exception {
+ Map<String, String> options = baseOptions();
+ options.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ Path checkpoint = java.nio.file.Files.createTempDirectory("meta-fields-stream-ckpt");
+ AtomicLong seen = new AtomicLong(0);
+ StreamingQuery query = spark().readStream()
+ .format("hudi")
+ .load(basePath())
+ .writeStream()
+ .option("checkpointLocation", checkpoint.toString())
+ .foreachBatch((VoidFunction2<Dataset<Row>, Long>) (batch, batchId) -> seen.addAndGet(batch.count()))
+ .start();
+ try {
+ query.processAllAvailable();
+ } finally {
+ query.stop();
+ }
+
+ assertEquals(2, seen.get(),
+ "a COMMIT_TIME_ONLY table must serve streaming reads -- the relation's guard is on the commit "
+ + "time, which this mode populates");
+ }
+
+ /**
+ * The other side of the same guard: a MoR table that populates no meta columns is still rejected.
+ */
+ @Test
+ void streamingReadIsRejectedOnMorWithoutMetaFields() throws Exception {
+ Map<String, String> options = baseOptions();
+ options.put(DataSourceWriteOptions.TABLE_TYPE().key(), DataSourceWriteOptions.MOR_TABLE_TYPE_OPT_VAL());
+ options.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ options.put(HoodieTableConfig.RECORDKEY_FIELDS.key(), "key");
+ options.put(HoodieTableConfig.PARTITION_FIELDS.key(), "partition");
+ writeRows(Arrays.asList(
+ RowFactory.create("k1", "p1", "v1"),
+ RowFactory.create("k2", "p1", "v2")),
+ simpleSchema(), options, basePath(), SaveMode.Overwrite);
+
+ Path checkpoint = java.nio.file.Files.createTempDirectory("meta-fields-stream-mor-ckpt");
+ Throwable thrown = assertThrows(Throwable.class, () -> {
+ StreamingQuery query = spark().readStream()
+ .format("hudi")
+ .load(basePath())
+ .writeStream()
+ .option("checkpointLocation", checkpoint.toString())
+ .foreachBatch((VoidFunction2<Dataset<Row>, Long>) (batch, batchId) -> batch.count())
+ .start();
+ try {
+ query.processAllAvailable();
+ } finally {
+ query.stop();
+ }
+ });
+
+ String message = rootMessageOf(thrown);
+ assertTrue(message.contains("_hoodie_commit_time") || message.contains("meta")
+ || message.contains("populate"),
+ "expected a meta-fields rejection, got: " + message);
+ }
+
+}
diff --git a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkBinaryCopyClusteringAndValidationMeta.java b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkBinaryCopyClusteringAndValidationMeta.java
index 9595edbf47d1..0e858a4c7d4e 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkBinaryCopyClusteringAndValidationMeta.java
+++ b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/functional/TestSparkBinaryCopyClusteringAndValidationMeta.java
@@ -37,7 +37,9 @@ import org.apache.hudi.common.model.HoodieFileFormat;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieReplaceCommitMetadata;
import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.model.MetaFieldsMode;
import org.apache.hudi.common.schema.HoodieSchema;
+import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.table.timeline.HoodieInstant;
import org.apache.hudi.common.testutils.HoodieTestDataGenerator;
@@ -47,6 +49,7 @@ import org.apache.hudi.common.util.ParquetUtils;
import org.apache.hudi.config.HoodieClusteringConfig;
import org.apache.hudi.config.HoodieWriteConfig;
import org.apache.hudi.io.storage.hadoop.HoodieAvroParquetWriter;
+import org.apache.hudi.keygen.constant.KeyGeneratorOptions;
import org.apache.hudi.storage.StoragePath;
import org.apache.hudi.table.HoodieSparkTable;
import org.apache.hudi.table.HoodieTable;
@@ -64,6 +67,7 @@ import org.apache.parquet.schema.MessageType;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
+import org.apache.spark.sql.functions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -377,6 +381,77 @@ public class TestSparkBinaryCopyClusteringAndValidationMeta extends HoodieClient
new HashSet<>(clusteredKeys));
}
+ /**
+ * Binary-copy clustering must not populate {@code _hoodie_file_name} on a table whose mode opts out.
+ *
+ * <p>{@code HoodieParquetBinaryCopyBase#initFileWriter} installs a mask rewriting that column to the
+ * output file name. Unconditionally applied, it hands a {@code COMMIT_TIME_ONLY} table a file name it
+ * never advertised -- the column reads as populated while the table config says it is not. The mask
+ * is gated on the table's mode; this pins that gate for the one strategy that reaches it.
+ */
+ @Test
+ public void testStreamCopyClusteringLeavesFileNameNullUnderCommitTimeOnly() throws IOException {
+ String partitionPath = "2015/03/16";
+ Properties properties = new Properties();
+ properties.setProperty("hoodie.parquet.small.file.limit", "-1");
+ properties.setProperty(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ // A selective mode leaves _hoodie_record_key unpopulated, so the write path derives the key
+ // through the key generator instead of reading the column -- which means the key-generator
+ // properties have to be present. The sibling ALL-mode tests never construct one.
+ properties.setProperty(KeyGeneratorOptions.RECORDKEY_FIELD_NAME.key(), "_row_key");
+ properties.setProperty(KeyGeneratorOptions.PARTITIONPATH_FIELD_NAME.key(), "partition_path");
+ HoodieWriteConfig.Builder cfgBuilder = new HoodieWriteConfig.Builder()
+ .withPath(basePath)
+ .withSchema(TRIP_NESTED_EXAMPLE_SCHEMA)
+ .withEmbeddedTimelineServerEnabled(false)
+ .withMetaFieldsMode(MetaFieldsMode.COMMIT_TIME_ONLY)
+ .withClusteringConfig(
+ HoodieClusteringConfig
+ .newBuilder()
+ .withInlineClustering(true)
+ .withAsyncClustering(false)
+ .withInlineClusteringNumCommits(2)
+ // the execution strategy is picked from the write config rather than from the plan, so set both
+ .withClusteringPlanStrategyClass(HoodieClusteringConfig.SPARK_STREAM_COPY_CLUSTERING_PLAN_STRATEGY)
+ .withClusteringExecutionStrategyClass(HoodieClusteringConfig.SPARK_STREAM_COPY_CLUSTERING_EXECUTION_STRATEGY)
+ .withFileStitchingBinaryCopySchemaEvolutionEnabled(false)
+ .build()).withProps(properties);
+
+ // The table has to agree with the writer: meta-field population is a table property. Update the
+ // existing hoodie.properties rather than re-initialising through newTableBuilder, which would drop
+ // the key-generator properties HoodieTestUtils.init put there and fail keygen construction.
+ Properties tableProps = new Properties();
+ tableProps.putAll(metaClient.getTableConfig().getProps());
+ tableProps.put(HoodieTableConfig.META_FIELDS_MODE.key(), MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ tableProps.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), "false");
+ HoodieTableConfig.update(metaClient.getStorage(), metaClient.getMetaPath(), tableProps);
+ metaClient = HoodieTableMetaClient.reload(metaClient);
+
+ SparkRDDWriteClient client = getHoodieWriteClient(cfgBuilder.build());
+ HoodieTestDataGenerator dataGen = new HoodieTestDataGenerator(HoodieTestDataGenerator.TRIP_NESTED_EXAMPLE_SCHEMA,
+ 0xDEED, new String[] {partitionPath}, new HashMap<>());
+
+ for (int i = 0; i < 2; i++) {
+ String newCommitTime = client.startCommit("commit");
+ List<HoodieRecord> hoodieRecords = dataGen.generateInsertsNestedExample(newCommitTime, 30);
+ JavaRDD<WriteStatus> statuses = client.insert(jsc.parallelize(hoodieRecords, 1), newCommitTime);
+ client.commit(newCommitTime, statuses);
+ }
+
+ HoodieTableMetaClient reloaded = HoodieTableMetaClient.reload(metaClient);
+ assertEquals(1, reloaded.getActiveTimeline().getCompletedReplaceTimeline().countInstants(),
+ "clustering must have run, otherwise this test proves nothing");
+
+ Dataset<Row> clustered = sqlContext.read().format("parquet")
+ .load(basePath + "/" + partitionPath + "/*.parquet");
+ long total = clustered.count();
+ assertTrue(total > 0, "expected the clustered table to still hold rows");
+ assertEquals(0, clustered.filter(functions.col("_hoodie_file_name").isNotNull()).count(),
+ "binary-copy clustering must not populate _hoodie_file_name on a COMMIT_TIME_ONLY table");
+ assertEquals(total, clustered.filter(functions.col("_hoodie_commit_time").isNotNull()).count(),
+ "the opted-in commit time must survive binary-copy clustering on every row");
+ }
+
private String makeTestFile(String fileName, HoodieSchema schema, MessageType messageType, BloomFilter filter) throws IOException {
HoodieAvroWriteSupport writeSupport = new HoodieAvroWriteSupport(messageType, schema, Option.of(filter), new Properties());
StoragePath filePath = new StoragePath(tempDir.resolve(fileName).toAbsolutePath().toString());
diff --git a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieRowCreateHandle.java b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieRowCreateHandle.java
index db28241430b3..ca9c91375320 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieRowCreateHandle.java
+++ b/hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/io/storage/row/TestHoodieRowCreateHandle.java
@@ -21,6 +21,9 @@ package org.apache.hudi.io.storage.row;
import org.apache.hudi.client.WriteStatus;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.model.HoodieWriteStat;
+import org.apache.hudi.common.model.MetaFieldsMode;
+import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.testutils.HoodieTestDataGenerator;
import org.apache.hudi.common.util.StringUtils;
import org.apache.hudi.config.HoodieWriteConfig;
@@ -40,6 +43,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
+import java.util.Properties;
import java.util.Random;
import java.util.UUID;
@@ -82,6 +86,19 @@ public class TestHoodieRowCreateHandle extends HoodieSparkClientTestHarness {
.withPopulateMetaFields(populateMetaFields)
.build();
+ // The handle reads the meta-fields mode from the TABLE config, not the write config, so the
+ // fixture table -- created with meta fields populated by initMetaClient() -- has to be told what
+ // this run is writing. Without this the writer asks for NONE while the table still says ALL, which
+ // is both rejected by the writer-vs-table check and, here, would have the handle stamp meta
+ // columns the assertions expect to be untouched.
+ Properties tableProps = new Properties();
+ tableProps.putAll(metaClient.getTableConfig().getProps());
+ tableProps.put(HoodieTableConfig.POPULATE_META_FIELDS.key(), String.valueOf(populateMetaFields));
+ tableProps.put(HoodieTableConfig.META_FIELDS_MODE.key(),
+ (populateMetaFields ? MetaFieldsMode.ALL : MetaFieldsMode.NONE).name());
+ HoodieTableConfig.update(metaClient.getStorage(), metaClient.getMetaPath(), tableProps);
+ metaClient = HoodieTableMetaClient.reload(metaClient);
+
HoodieTable table = HoodieSparkTable.create(config, context, metaClient);
List<String> fileNames = new ArrayList<>();
List<String> fileAbsPaths = new ArrayList<>();
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/HoodieSparkWriterTestBase.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/HoodieSparkWriterTestBase.scala
index 3df5cef86a5e..142c919e8a39 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/HoodieSparkWriterTestBase.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/HoodieSparkWriterTestBase.scala
@@ -27,6 +27,7 @@ import org.apache.spark.SparkContext
import org.apache.spark.sql.{Dataset, Row, SparkSession, SQLContext}
import org.apache.spark.sql.hudi.HoodieSparkSessionExtension
import org.junit.jupiter.api.{AfterEach, BeforeEach}
+import org.junit.jupiter.api.Assertions.assertEquals
import scala.collection.JavaConverters
@@ -125,6 +126,23 @@ class HoodieSparkWriterTestBase {
.drop(HoodieRecord.HOODIE_META_COLUMNS.get(4))
}
+ /**
+ * Asserts that every one of the five meta columns is NULL on every row.
+ *
+ * Strictly NULL, not "null or empty": the row-writer bulk-insert stubs are
+ * `Literal.create(null, StringType)` so the columns are Parquet OPTIONAL, which is what lets a
+ * selective `hoodie.meta.fields.mode` leave them unpopulated. Accepting `""` as well would stop
+ * pinning which representation is written, and would disagree with the `assertNull` assertions in
+ * TestMetaFieldsMode for the same scenario.
+ */
+ def assertNoMetaFieldsPopulated(df: Dataset[Row]): Unit = {
+ (0 until HoodieRecord.HOODIE_META_COLUMNS.size()).foreach { i =>
+ val column = HoodieRecord.HOODIE_META_COLUMNS.get(i)
+ assertEquals(0, df.select(column).filter(entry => !entry.isNullAt(0)).count(),
+ s"expected every row to have a NULL $column")
+ }
+ }
+
/**
* Utility method for converting list of Row to list of Seq.
*
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriter.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriter.scala
index 8968caaf348f..393030dd83b3 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriter.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriter.scala
@@ -20,7 +20,7 @@ package org.apache.hudi
import org.apache.hudi.DataSourceWriteOptions.{DROP_INSERT_DUP_POLICY, FAIL_INSERT_DUP_POLICY, INSERT_DROP_DUPS, INSERT_DUP_POLICY}
import org.apache.hudi.client.SparkRDDWriteClient
import org.apache.hudi.common.config.{HoodieConfig, HoodieMetadataConfig, RecordMergeMode}
-import org.apache.hudi.common.model.{DefaultHoodieRecordPayload, HoodieFileFormat, HoodieRecord, HoodieRecordPayload, HoodieReplaceCommitMetadata, HoodieTableType, WriteOperationType}
+import org.apache.hudi.common.model.{DefaultHoodieRecordPayload, HoodieFileFormat, HoodieRecord, HoodieRecordPayload, HoodieReplaceCommitMetadata, HoodieTableType, MetaFieldsMode, WriteOperationType}
import org.apache.hudi.common.schema.HoodieSchema
import org.apache.hudi.common.table.{HoodieTableConfig, HoodieTableMetaClient, TableSchemaResolver}
import org.apache.hudi.common.table.timeline.{HoodieTimeline, TimelineUtils}
@@ -107,7 +107,7 @@ class TestHoodieSparkSqlWriter extends HoodieSparkWriterTestBase {
// fetch all records from parquet files generated from write to hudi
val actualDf = sqlContext.read.parquet(fullPartitionPaths(0), fullPartitionPaths(1), fullPartitionPaths(2))
if (!populateMetaFields) {
- List(0, 1, 2, 3, 4).foreach(i => assertEquals(0, actualDf.select(HoodieRecord.HOODIE_META_COLUMNS.get(i)).filter(entry => !(entry.mkString(",").equals(""))).count()))
+ assertNoMetaFieldsPopulated(actualDf)
}
// remove metadata columns so that expected and actual DFs can be compared as is
val trimmedDf = dropMetaFields(actualDf)
@@ -339,7 +339,7 @@ def testBulkInsertForDropPartitionColumn(): Unit = {
* Test case for disable and enable meta fields.
*/
@Test
- def testDisableAndEnableMetaFields(): Unit = {
+ def testLegacyBooleanDoesNotOverrideDisabledMetaFields(): Unit = {
testBulkInsertWithSortMode(BulkInsertSortMode.NONE, populateMetaFields = false)
//create a new table
val fooTableModifier = commonTableModifier.updated("hoodie.bulkinsert.shuffle.parallelism", "4")
@@ -353,14 +353,10 @@ def testBulkInsertForDropPartitionColumn(): Unit = {
val structType = HoodieSchemaConversionUtils.convertHoodieSchemaToStructType(schema)
val inserts = DataSourceTestUtils.generateRandomRows(1000)
val df = spark.createDataFrame(sc.parallelize(inserts.asScala.toSeq), structType)
- try {
- // write to Hudi
- HoodieSparkSqlWriter.write(sqlContext, SaveMode.Append, fooTableModifier, df)
- fail("Should have thrown exception")
- } catch {
- case e: HoodieException => assertTrue(e.getMessage.startsWith("Config conflict"))
- case e: Exception => fail(e);
- }
+ HoodieSparkSqlWriter.write(sqlContext, SaveMode.Append, fooTableModifier, df)
+
+ assertEquals(MetaFieldsMode.NONE,
+ createMetaClient(spark, tempBasePath).getTableConfig.getMetaFieldsMode)
}
/**
@@ -651,6 +647,14 @@ def testBulkInsertForDropPartitionColumn(): Unit = {
.setPartitionFields(fooTableParams(DataSourceWriteOptions.PARTITIONPATH_FIELD.key))
.setKeyGeneratorClassProp(fooTableParams.getOrElse(DataSourceWriteOptions.KEYGENERATOR_CLASS_NAME.key,
DataSourceWriteOptions.KEYGENERATOR_CLASS_NAME.defaultValue()))
+ // Forward the meta-field setting the caller is about to write with. Without this the table is
+ // created as ALL while the writer asks for NONE, which the write client now rejects -- meta-field
+ // population is a table property, so a writer cannot narrow it. Previously the write narrowed
+ // silently, so the fixture's table and its writer had always disagreed without anything noticing.
+ if (fooTableParams.contains(HoodieTableConfig.POPULATE_META_FIELDS.key)) {
+ tableMetaClientBuilder.setPopulateMetaFields(
+ java.lang.Boolean.valueOf(fooTableParams(HoodieTableConfig.POPULATE_META_FIELDS.key)))
+ }
if (fooTableParams.contains(HoodieWriteConfig.WRITE_PAYLOAD_CLASS_NAME.key())) {
tableMetaClientBuilder.setPayloadClassName(fooTableParams(HoodieWriteConfig.WRITE_PAYLOAD_CLASS_NAME.key))
}
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriterWithTestFormat.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriterWithTestFormat.scala
index 2cf0dc20ad08..fcea1df99ce2 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriterWithTestFormat.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/TestHoodieSparkSqlWriterWithTestFormat.scala
@@ -106,7 +106,7 @@ class TestHoodieSparkSqlWriterWithTestFormat extends HoodieSparkWriterTestBase {
// fetch all records from parquet files generated from write to hudi
val actualDf = sqlContext.read.parquet(fullPartitionPaths(0), fullPartitionPaths(1), fullPartitionPaths(2))
if (!populateMetaFields) {
- List(0, 1, 2, 3, 4).foreach(i => assertEquals(0, actualDf.select(HoodieRecord.HOODIE_META_COLUMNS.get(i)).filter(entry => !(entry.mkString(",").equals(""))).count()))
+ assertNoMetaFieldsPopulated(actualDf)
}
// remove metadata columns so that expected and actual DFs can be compared as is
val trimmedDf = dropMetaFields(actualDf)
@@ -205,7 +205,7 @@ class TestHoodieSparkSqlWriterWithTestFormat extends HoodieSparkWriterTestBase {
* Test case for disable and enable meta fields.
*/
@Test
- def testDisableAndEnableMetaFields(): Unit = {
+ def testLegacyBooleanDoesNotOverrideDisabledMetaFields(): Unit = {
testBulkInsertWithSortMode(BulkInsertSortMode.NONE, populateMetaFields = false)
//create a new table
val fooTableModifier = commonTableModifier.updated("hoodie.bulkinsert.shuffle.parallelism", "4")
@@ -220,14 +220,10 @@ class TestHoodieSparkSqlWriterWithTestFormat extends HoodieSparkWriterTestBase {
val structType = HoodieSchemaConversionUtils.convertHoodieSchemaToStructType(schema)
val inserts = DataSourceTestUtils.generateRandomRows(1000)
val df = spark.createDataFrame(sc.parallelize(inserts.asScala.toSeq), structType)
- try {
- // write to Hudi
- HoodieSparkSqlWriter.write(sqlContext, SaveMode.Append, fooTableModifier, df)
- fail("Should have thrown exception")
- } catch {
- case e: HoodieException => assertTrue(e.getMessage.startsWith("Config conflict"))
- case e: Exception => fail(e);
- }
+ HoodieSparkSqlWriter.write(sqlContext, SaveMode.Append, fooTableModifier, df)
+
+ assertEquals(MetaFieldsMode.NONE,
+ createMetaClient(spark, tempBasePath).getTableConfig.getMetaFieldsMode)
}
/**
@@ -489,6 +485,13 @@ class TestHoodieSparkSqlWriterWithTestFormat extends HoodieSparkWriterTestBase {
.setPartitionFields(fooTableParams(DataSourceWriteOptions.PARTITIONPATH_FIELD.key))
.setKeyGeneratorClassProp(fooTableParams.getOrElse(DataSourceWriteOptions.KEYGENERATOR_CLASS_NAME.key,
DataSourceWriteOptions.KEYGENERATOR_CLASS_NAME.defaultValue()))
+ // Forward the meta-field setting the caller is about to write with; see the same fix in
+ // TestHoodieSparkSqlWriter. Without it the table is created as ALL while the writer asks for
+ // NONE, which the write client now rejects -- meta-field population is a table property.
+ if (fooTableParams.contains(HoodieTableConfig.POPULATE_META_FIELDS.key)) {
+ tableMetaClientBuilder.setPopulateMetaFields(
+ java.lang.Boolean.valueOf(fooTableParams(HoodieTableConfig.POPULATE_META_FIELDS.key)))
+ }
if (fooTableParams.contains(HoodieWriteConfig.WRITE_PAYLOAD_CLASS_NAME.key)) {
tableMetaClientBuilder.setPayloadClassName(fooTableParams(HoodieWriteConfig.WRITE_PAYLOAD_CLASS_NAME.key))
}
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestAutoGenerationOfRecordKeys.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestAutoGenerationOfRecordKeys.scala
index bca39bd0221e..e5c96142ecda 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestAutoGenerationOfRecordKeys.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestAutoGenerationOfRecordKeys.scala
@@ -171,7 +171,10 @@ class TestAutoGenerationOfRecordKeys extends HoodieSparkClientTestBase with Scal
@ParameterizedTest
@CsvSource(value = Array(
- "hoodie.populate.meta.fields,false", "hoodie.combine.before.insert,true", "hoodie.datasource.write.insert.drop.duplicates,true"
+ "hoodie.populate.meta.fields,false", "hoodie.combine.before.insert,true", "hoodie.datasource.write.insert.drop.duplicates,true",
+ // The mode is the source of truth, so stating it must fire this guard exactly as the deprecated
+ // boolean does -- otherwise the write proceeds and the rows land with no record key at all.
+ "hoodie.meta.fields.mode,NONE", "hoodie.meta.fields.mode,COMMIT_TIME_ONLY"
))
def testRecordKeysAutoGenInvalidParams(configKey: String, configValue: String): Unit = {
val (writeOpts, _) = getWriterReaderOpts(HoodieRecordType.AVRO)
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable2.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable2.scala
index b4bb8ea4a528..cd2ea668b849 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable2.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable2.scala
@@ -431,10 +431,15 @@ class TestInsertTable2 extends HoodieSparkSqlTestBase {
| location '${tablePath}'
| tblproperties (
| primaryKey = 'id',
- | preCombineField = 'ts'
+ | preCombineField = 'ts',
+ | '${HoodieTableConfig.POPULATE_META_FIELDS.key}' = '$populateMetaConfig'
| )
|""".stripMargin)
+ // Meta-field population is a table property, so it is declared at create time rather than
+ // only on the writer below. A writer that disagrees with the table about which meta columns
+ // hold values is rejected -- narrowing an existing ALL table on the fly used to happen
+ // silently and is what produced rows the table still advertised as populated.
val rowsWithSimilarKey = Seq((1, "a1", 10.0, 1000L), (1, "a1", 11.0, 1001L))
rowsWithSimilarKey.toDF("id", "name", "value", "ts")
.write.format("hudi")
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala
index 0a71f63fbf9c..668ea2384a00 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala
@@ -139,6 +139,7 @@ class TestRepairsProcedure extends HoodieSparkProcedureTestBase {
|[hoodie.datasource.write.drop.partition.columns,false,false]
|[hoodie.datasource.write.hive_style_partitioning,true,null]
|[hoodie.datasource.write.partitionpath.urlencode,false,null]
+ |[hoodie.meta.fields.mode,ALL,null]
|[hoodie.record.merge.mode,EVENT_TIME_ORDERING,null]
|[hoodie.table.checksum,,]
|[hoodie.table.create.schema,,]
diff --git a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java
index 2abc2c680b08..daa4bdccf99a 100644
--- a/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java
+++ b/hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMergeRequiredColumns.java
@@ -115,7 +115,7 @@ class TestHudiMergeRequiredColumns
assertThat(mergeRequiredColumnNames(tableConfig, RecordMergeMode.EVENT_TIME_ORDERING))
.doesNotContain("id1", "id2");
- tableConfig.setValue(HoodieTableConfig.POPULATE_META_FIELDS, "false");
+ tableConfig.setValue(HoodieTableConfig.META_FIELDS_MODE, "NONE");
assertThat(mergeRequiredColumnNames(tableConfig, RecordMergeMode.EVENT_TIME_ORDERING))
.contains("id1", "id2");
}
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieDropPartitionsTool.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieDropPartitionsTool.java
index d945203e59ef..e1e28c4cf7c8 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieDropPartitionsTool.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieDropPartitionsTool.java
@@ -22,6 +22,7 @@ import org.apache.hudi.client.HoodieWriteResult;
import org.apache.hudi.client.SparkRDDWriteClient;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.model.HoodieRecordPayload;
+import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.table.timeline.HoodieTimeline;
import org.apache.hudi.common.util.Option;
@@ -124,6 +125,15 @@ public class HoodieDropPartitionsTool implements Serializable {
.setBasePath(cfg.basePath)
.setLoadActiveTimelineOnLoad(true)
.build();
+ // Adopt the table's meta-fields mode unless the operator named one. The write configs built below
+ // come from these props alone, so without this they resolve to the ALL default and are rejected
+ // against any table that is not ALL -- meta columns are physical, and a writer may not disagree
+ // with the table about which of them hold values. Unlike an ingestion writer, which has to state
+ // the mode because the write path cannot re-derive it, this tool has the table in hand.
+ if (!props.containsKey(HoodieTableConfig.META_FIELDS_MODE.key())) {
+ props.setProperty(HoodieTableConfig.META_FIELDS_MODE.key(),
+ metaClient.getTableConfig().getMetaFieldsMode().name());
+ }
}
/**
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/BootstrapExecutor.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/BootstrapExecutor.java
index 24ce507b34a7..df57a7a45fa7 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/BootstrapExecutor.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/BootstrapExecutor.java
@@ -209,8 +209,11 @@ public class BootstrapExecutor implements Serializable {
.setOrderingFields(ConfigUtils.getOrderingFieldsStrDuringWrite(props))
.setTableVersion(ConfigUtils.getIntWithAltKeys(props, WRITE_TABLE_VERSION))
.setTableFormat(props.getString(HoodieTableConfig.TABLE_FORMAT.key(), HoodieTableConfig.TABLE_FORMAT.defaultValue()))
- .setPopulateMetaFields(props.getBoolean(
- POPULATE_META_FIELDS.key(), POPULATE_META_FIELDS.defaultValue()))
+ // null when unstated: getBoolean's two-arg form returns a primitive, so passing the `true`
+ // default would contradict an explicit hoodie.meta.fields.mode and reject the table at
+ // creation. Matches StreamSync and HoodieSparkSqlWriter.
+ .setPopulateMetaFields(props.containsKey(POPULATE_META_FIELDS.key())
+ ? props.getBoolean(POPULATE_META_FIELDS.key()) : null)
.setArchiveLogFolder(props.getString(
TIMELINE_HISTORY_PATH.key(), TIMELINE_HISTORY_PATH.defaultValue()))
.setPayloadClassName(cfg.payloadClassName)
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
index 1ffe12f66877..71bce5b564c9 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
@@ -476,8 +476,13 @@ public class StreamSync implements Serializable, Closeable {
.setPartitionFields(partitionColumns)
.setTableVersion(ConfigUtils.getIntWithAltKeys(props, WRITE_TABLE_VERSION))
.setRecordKeyFields(props.getProperty(DataSourceWriteOptions.RECORDKEY_FIELD().key()))
- .setPopulateMetaFields(props.getBoolean(HoodieTableConfig.POPULATE_META_FIELDS.key(),
- HoodieTableConfig.POPULATE_META_FIELDS.defaultValue()))
+ // null when unstated: TableBuilder rejects a boolean that contradicts an explicit
+ // meta.fields.mode, so handing it the `true` default would turn a plain
+ // hoodie.meta.fields.mode=COMMIT_TIME_ONLY run into a spurious conflict.
+ .setPopulateMetaFields(props.containsKey(HoodieTableConfig.POPULATE_META_FIELDS.key())
+ ? props.getBoolean(HoodieTableConfig.POPULATE_META_FIELDS.key()) : null)
+ .setMetaFieldsModeFromString(props.getString(HoodieTableConfig.META_FIELDS_MODE.key(),
+ null))
.setKeyGeneratorClassProp(keyGenClassName)
.setPartitionValueExtractorClass(partitionValueExtractorClassName)
.setOrderingFields(cfg.sourceOrderingFields)
@@ -1293,6 +1298,12 @@ public class StreamSync implements Serializable, Closeable {
}
if (metaClient != null) {
+ // NOTE: hoodie.meta.fields.mode is deliberately *not* folded in here. It is a table property, and
+ // BaseHoodieWriteClient#validateAgainstTableProperties owns the rule for every engine: a writer
+ // that states neither meta-field property inherits the table's mode, and one that states either is
+ // compared and rejected on mismatch. Inheriting here as well would pre-empt that comparison — a
+ // restart passing only hoodie.populate.meta.fields would silently adopt the table's mode instead
+ // of being told its setting conflicts.
HoodieTableConfig tableConfig = metaClient.getTableConfig();
// After upgrade to table version 9 with MySqlDebeziumAvroPayload, ordering fields are changed from
// `_event_seq` to `_event_bin_file,_event_pos`. The logic here ensures that deltastreamer config is updated
diff --git a/hudi-utilities/src/test/java/org/apache/hudi/utilities/deltastreamer/TestHoodieStreamerMetaFieldsMode.java b/hudi-utilities/src/test/java/org/apache/hudi/utilities/deltastreamer/TestHoodieStreamerMetaFieldsMode.java
new file mode 100644
index 000000000000..6d8ec05fbc7c
--- /dev/null
+++ b/hudi-utilities/src/test/java/org/apache/hudi/utilities/deltastreamer/TestHoodieStreamerMetaFieldsMode.java
@@ -0,0 +1,286 @@
+/*
+ * 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.hudi.utilities.deltastreamer;
+
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.MetaFieldsMode;
+import org.apache.hudi.common.model.WriteOperationType;
+import org.apache.hudi.common.table.HoodieTableConfig;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.functions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * End-to-end coverage for {@code hoodie.meta.fields.mode} through the HoodieStreamer entrypoint.
+ * Each parameterized invocation runs a single ingest cycle in the given {@link MetaFieldsMode} and
+ * verifies both the persisted table property and the actual on-disk parquet column population.
+ *
+ * <p>Rejection paths (unknown token, populate=true+mode, MoR+mode) are exercised in the datasource
+ * test {@code TestMetaFieldsMode}; this fixture focuses on the streamer control-flow.
+ */
+public class TestHoodieStreamerMetaFieldsMode extends HoodieDeltaStreamerTestBase {
+
+ /**
+ * Only the selective modes are parameterized here. ALL and NONE add no mode key at all, so they
+ * exercise none of the streamer-side plumbing this feature introduced — they are covered by the
+ * datasource tests and by {@code TestHoodieTableConfig}'s resolution cases.
+ */
+ @ParameterizedTest
+ @EnumSource(value = MetaFieldsMode.class,
+ names = {"COMMIT_TIME_ONLY", "FILE_NAME_ONLY", "COMMIT_TIME_AND_FILE_NAME"})
+ public void testStreamerRespectsMetaFieldsMode(MetaFieldsMode mode) throws Exception {
+ String tablePath = basePath + "/streamer_meta_fields_mode_" + mode.name();
+ HoodieDeltaStreamer.Config cfg = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ // Force CoW; selective modes are CoW-only until MoR log-write is wired.
+ cfg.tableType = "COPY_ON_WRITE";
+ // The mode alone — pairing it with populate.meta.fields would now be a stated conflict, since the
+ // mode is authoritative and the boolean is only the fallback for resolving an absent one.
+ cfg.configs.add(HoodieTableConfig.META_FIELDS_MODE.key() + "=" + mode.name());
+ HoodieDeltaStreamer streamer = new HoodieDeltaStreamer(cfg, jsc);
+ streamer.getIngestionService().ingestOnce();
+ streamer.shutdownGracefully();
+
+ HoodieTableMetaClient metaClient = HoodieTestUtils.createMetaClient(context, tablePath);
+ assertEquals(mode, metaClient.getTableConfig().getMetaFieldsMode(),
+ "streamer must persist mode=" + mode + " on hoodie.properties");
+ assertOnDiskMetaColumns(tablePath, mode);
+ }
+
+ /**
+ * The regression this fixture exists for: a restarted streamer
+ * that does not restate the mode must not silently write the wrong meta columns.
+ *
+ * <p>StreamSync builds its write config from {@code props} alone, and the mode is persisted only by
+ * {@code initializeEmptyTable}, which runs solely when the base path does not exist. So a second run
+ * used to resolve to {@link MetaFieldsMode#NONE} and write base files with a null
+ * {@code _hoodie_commit_time} while {@code hoodie.properties} still advertised
+ * {@code COMMIT_TIME_ONLY} — incremental queries were then admitted and silently dropped every one
+ * of those rows.
+ *
+ * <p>A selective table now requires the writer to state the mode, so the restart is <b>rejected</b>
+ * rather than inheriting. Inheritance would work here, but it cannot be relied on everywhere: the
+ * write path reads the mode in factories and handles that hold no table config at all, so the write
+ * config has to be right on its own. Failing loudly at init is what makes that guarantee real —
+ * and a rejected run leaves the table exactly as it was, which silent narrowing did not.
+ * See {@code testRestartRestatingTheModeSucceeds} for the migration path.
+ */
+ @Test
+ public void testRestartWithoutRestatingTheModeIsRejected() throws Exception {
+ String tablePath = basePath + "/streamer_restart_inherits_mode";
+
+ HoodieDeltaStreamer.Config first = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ first.tableType = "COPY_ON_WRITE";
+ first.configs.add(HoodieTableConfig.META_FIELDS_MODE.key() + "=" + MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ HoodieDeltaStreamer streamer = new HoodieDeltaStreamer(first, jsc);
+ streamer.getIngestionService().ingestOnce();
+ streamer.shutdownGracefully();
+
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY,
+ HoodieTestUtils.createMetaClient(context, tablePath).getTableConfig().getMetaFieldsMode());
+
+ long commitsAfterFirstRun = HoodieTestUtils.createMetaClient(context, tablePath)
+ .getActiveTimeline().filterCompletedInstants().countInstants();
+
+ // Restart against the existing table stating neither the mode nor the legacy boolean.
+ HoodieDeltaStreamer.Config restart = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ restart.tableType = "COPY_ON_WRITE";
+
+ Throwable thrown = assertThrows(Throwable.class, () -> {
+ HoodieDeltaStreamer restarted = new HoodieDeltaStreamer(restart, jsc);
+ restarted.getIngestionService().ingestOnce();
+ restarted.shutdownGracefully();
+ });
+
+ String rootMessage = rootMessageOf(thrown);
+ assertTrue(rootMessage.contains(HoodieTableConfig.META_FIELDS_MODE.key()),
+ "expected the writer to be told to state the mode, got: " + rootMessage);
+
+ // The rejected run must have left the table untouched -- no mode change, no extra commit, and no
+ // base file carrying a null commit time. That last one is the actual data loss being prevented:
+ // such rows are admitted by incremental queries and then silently dropped.
+ HoodieTableMetaClient metaClient = HoodieTestUtils.createMetaClient(context, tablePath);
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, metaClient.getTableConfig().getMetaFieldsMode(),
+ "a rejected restart must leave the table's mode untouched");
+ assertEquals(commitsAfterFirstRun,
+ metaClient.getActiveTimeline().filterCompletedInstants().countInstants(),
+ "a rejected restart must not have committed anything");
+ Dataset<Row> raw = sparkSession.read().parquet(tablePath + "/*/*/*/*.parquet");
+ assertEquals(0,
+ raw.filter(functions.col(HoodieRecord.COMMIT_TIME_METADATA_FIELD).isNull()).count(),
+ "no row may have a null _hoodie_commit_time on a COMMIT_TIME_ONLY table");
+ }
+
+ /**
+ * The migration path for the case above: a restart that restates the table's mode proceeds normally.
+ *
+ * <p>This is what every writer against a selective table must do, and it is the assertion that keeps
+ * the requirement from being a dead end -- the mode is stateable, and stating it is enough.
+ */
+ @Test
+ public void testRestartRestatingTheModeSucceeds() throws Exception {
+ String tablePath = basePath + "/streamer_restart_restates_mode";
+
+ HoodieDeltaStreamer.Config first = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ first.tableType = "COPY_ON_WRITE";
+ first.configs.add(HoodieTableConfig.META_FIELDS_MODE.key() + "=" + MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ HoodieDeltaStreamer streamer = new HoodieDeltaStreamer(first, jsc);
+ streamer.getIngestionService().ingestOnce();
+ streamer.shutdownGracefully();
+
+ // Restart restating the same mode.
+ HoodieDeltaStreamer.Config restart = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ restart.tableType = "COPY_ON_WRITE";
+ restart.configs.add(HoodieTableConfig.META_FIELDS_MODE.key() + "=" + MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ HoodieDeltaStreamer restarted = new HoodieDeltaStreamer(restart, jsc);
+ restarted.getIngestionService().ingestOnce();
+ restarted.shutdownGracefully();
+
+ HoodieTableMetaClient metaClient = HoodieTestUtils.createMetaClient(context, tablePath);
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, metaClient.getTableConfig().getMetaFieldsMode(),
+ "the restart must not have changed the table's mode");
+ assertTrue(metaClient.getActiveTimeline().filterCompletedInstants().countInstants() >= 2,
+ "expected the restart to have produced a second commit");
+
+ // Every row across both commits carries a commit time. A row with a null one is what incremental
+ // queries silently drop, so this is the assertion that catches the regression.
+ Dataset<Row> raw = sparkSession.read().parquet(tablePath + "/*/*/*/*.parquet");
+ assertEquals(0,
+ raw.filter(functions.col(HoodieRecord.COMMIT_TIME_METADATA_FIELD).isNull()).count(),
+ "no row may have a null _hoodie_commit_time on a COMMIT_TIME_ONLY table");
+ assertTrue(raw.select(HoodieRecord.COMMIT_TIME_METADATA_FIELD).distinct().count() >= 2,
+ "both commits must be represented, so the second run really did write through this path");
+ }
+
+ /**
+ * The variant where the restart states the deprecated boolean rather than nothing at all.
+ *
+ * <p>Both cases are rejected against a selective table, for the same reason: the writer has not
+ * stated the mode the table is on. Stating the boolean instead makes the disagreement explicit
+ * rather than merely unstated, but the outcome is the same. Before this rule it narrowed silently,
+ * writing base files with a null {@code _hoodie_commit_time} into a table that still advertised the
+ * mode.
+ */
+ @Test
+ public void testRestartStatingTheLegacyBooleanIsRejected() throws Exception {
+ String tablePath = basePath + "/streamer_restart_legacy_boolean_conflict";
+
+ HoodieDeltaStreamer.Config first = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ first.tableType = "COPY_ON_WRITE";
+ first.configs.add(HoodieTableConfig.META_FIELDS_MODE.key() + "=" + MetaFieldsMode.COMMIT_TIME_ONLY.name());
+ HoodieDeltaStreamer streamer = new HoodieDeltaStreamer(first, jsc);
+ streamer.getIngestionService().ingestOnce();
+ streamer.shutdownGracefully();
+
+ HoodieDeltaStreamer.Config restart = TestHelpers.makeConfig(tablePath, WriteOperationType.INSERT);
+ restart.tableType = "COPY_ON_WRITE";
+ restart.configs.add(HoodieTableConfig.POPULATE_META_FIELDS.key() + "=false");
+
+ Throwable thrown = assertThrows(Throwable.class, () -> {
+ HoodieDeltaStreamer restarted = new HoodieDeltaStreamer(restart, jsc);
+ restarted.getIngestionService().ingestOnce();
+ restarted.shutdownGracefully();
+ });
+
+ String rootMessage = rootMessageOf(thrown);
+ assertTrue(rootMessage.contains(HoodieTableConfig.META_FIELDS_MODE.key())
+ || rootMessage.contains(HoodieTableConfig.POPULATE_META_FIELDS.key()),
+ "expected a meta-fields conflict, got: " + rootMessage);
+
+ // The failed run must not have changed the table, nor written rows with a null commit time.
+ HoodieTableMetaClient metaClient = HoodieTestUtils.createMetaClient(context, tablePath);
+ assertEquals(MetaFieldsMode.COMMIT_TIME_ONLY, metaClient.getTableConfig().getMetaFieldsMode(),
+ "a rejected restart must leave the table's mode untouched");
+ Dataset<Row> raw = sparkSession.read().parquet(tablePath + "/*/*/*/*.parquet");
+ assertEquals(0, raw.filter(functions.col(HoodieRecord.COMMIT_TIME_METADATA_FIELD).isNull()).count(),
+ "no row may have a null _hoodie_commit_time");
+ }
+
+ @Test
+ public void testStreamerRejectsMorWithSelectiveMode() throws Exception {
+ String tablePath = basePath + "/streamer_mor_selective_rejected";
+ HoodieDeltaStreamer.Config cfg = TestHelpers.makeConfig(tablePath, WriteOperationType.BULK_INSERT);
+ cfg.tableType = "MERGE_ON_READ";
+ cfg.configs.add(HoodieTableConfig.META_FIELDS_MODE.key() + "=" + MetaFieldsMode.COMMIT_TIME_ONLY.name());
+
+ Throwable thrown = assertThrows(Throwable.class, () -> {
+ HoodieDeltaStreamer streamer = new HoodieDeltaStreamer(cfg, jsc);
+ streamer.getIngestionService().ingestOnce();
+ streamer.shutdownGracefully();
+ });
+
+ String rootMessage = rootMessageOf(thrown);
+ assertTrue(rootMessage.contains("COPY_ON_WRITE") || rootMessage.contains("MERGE_ON_READ")
+ || rootMessage.contains("MoR") || rootMessage.contains(HoodieTableConfig.META_FIELDS_MODE.key()),
+ "Expected MoR-restriction error, got: " + rootMessage);
+ }
+
+ /**
+ * Counts across every row rather than inspecting one: a writer that populated a column on some rows
+ * and not others would satisfy a single-row check while producing exactly the mixed-mode output the
+ * mode being immutable exists to prevent.
+ */
+ private void assertOnDiskMetaColumns(String tablePath, MetaFieldsMode expectedMode) {
+ // Default HoodieTestDataGenerator partitions are YYYY/MM/DD (three levels).
+ Dataset<Row> raw = sparkSession.read().parquet(tablePath + "/*/*/*/*.parquet");
+ long total = raw.count();
+ assertTrue(total > 1, "the fixture must write more than one row for this assertion to mean anything");
+
+ assertMetaColumn(raw, total, HoodieRecord.COMMIT_TIME_METADATA_FIELD,
+ expectedMode.isCommitTimePopulated(), expectedMode);
+ assertMetaColumn(raw, total, HoodieRecord.FILENAME_METADATA_FIELD,
+ expectedMode.isFileNamePopulated(), expectedMode);
+ boolean allMode = expectedMode == MetaFieldsMode.ALL;
+ assertMetaColumn(raw, total, HoodieRecord.COMMIT_SEQNO_METADATA_FIELD, allMode, expectedMode);
+ assertMetaColumn(raw, total, HoodieRecord.RECORD_KEY_METADATA_FIELD, allMode, expectedMode);
+ assertMetaColumn(raw, total, HoodieRecord.PARTITION_PATH_METADATA_FIELD, allMode, expectedMode);
+ }
+
+ private static void assertMetaColumn(Dataset<Row> raw, long total, String column,
+ boolean expectPopulated, MetaFieldsMode mode) {
+ long nonNull = raw.filter(functions.col(column).isNotNull()).count();
+ if (expectPopulated) {
+ assertEquals(total, nonNull,
+ "every row must carry " + column + " in mode " + mode + "; " + (total - nonNull) + " of "
+ + total + " were null");
+ } else {
+ assertEquals(0, nonNull,
+ "no row may carry " + column + " in mode " + mode + "; " + nonNull + " of " + total
+ + " were populated");
+ }
+ }
+
+ private static String rootMessageOf(Throwable thrown) {
+ Throwable root = thrown;
+ while (root.getCause() != null) {
+ root = root.getCause();
+ }
+ return root.getMessage() == null ? "" : root.getMessage();
+ }
+}