You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by "rahil-c (via GitHub)" <gi...@apache.org> on 2025/08/01 21:45:47 UTC
[PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
rahil-c opened a new pull request, #13669:
URL: https://github.com/apache/hudi/pull/13669
### Change Logs
_Describe context and summary for this change. Highlight if any code was copied._
### Impact
_Describe any public API or user-facing feature change or any performance impact._
### Risk level (write none, low medium or high below)
_If medium or high, explain what verification was done to mitigate the risks._
### Documentation Update
_Describe any necessary documentation update if there is any new feature, config, or user-facing change. If not, put "none"._
- _The config description must be updated if new configs are added or the default value of the configs are changed_
- _Any new feature or user-facing change requires updating the Hudi website. Please create a Jira ticket, attach the
ticket number here and follow the [instruction](https://hudi.apache.org/contribute/developer-setup#website) to make
changes to the website._
### Contributor's checklist
- [ ] Read through [contributor's guide](https://hudi.apache.org/contribute/how-to-contribute)
- [ ] Change Logs and Impact were stated clearly
- [ ] Adequate tests were added if applicable
- [ ] CI passed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146577972
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* bf1cd628b1f12ec551cede386e12ea4ac8f602ff Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459)
* e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249322638
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
When I unzip the files I see `__MACOSX` folder and `*.crc` files under base path, partition paths, and metadata folder. They can be deleted when creating the zip file as they are not needed for testing.
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
Is it possible to further reduce the table size to below 50KB per table?
##########
.gitignore:
##########
@@ -87,3 +87,6 @@ dependency-reduced-pom.xml
hudi-integ-test/compose_env
node_modules
package-lock.json
+
+# Spark Binaries used for testing
+hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/spark-versions/
Review Comment:
nit: new line at the end of the file
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/scala-templates/generate-fixture.scala:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+import org.apache.spark.sql.SaveMode
+import org.apache.hudi.DataSourceWriteOptions._
+import spark.implicits._
+
+val tableName = "${TABLE_NAME}"
+val basePath = "${BASE_PATH}"
+
+// Create simple test data with consistent schema
+val testData = Seq(
+ ("id1", "Alice", 1000L, "2023-01-01"),
+ ("id2", "Bob", 2000L, "2023-01-01"),
+ ("id3", "Charlie", 3000L, "2023-01-02"),
+ ("id4", "David", 4000L, "2023-01-02"),
+ ("id5", "Eve", 5000L, "2023-01-03")
+)
+
+val df = testData.toDF("id", "name", "ts", "partition")
+
+// Write initial batch (creates base files)
+df.write.format("hudi").
+ option(PRECOMBINE_FIELD.key, "ts").
+ option(RECORDKEY_FIELD.key, "id").
+ option(PARTITIONPATH_FIELD.key, "partition").
+ option("hoodie.table.name", tableName).
+ option("hoodie.datasource.write.table.type", "MERGE_ON_READ").
+ option("hoodie.datasource.write.operation", "insert").
+ mode(SaveMode.Overwrite).
+ save(basePath)
+
+println("Initial batch written")
+
+// Write update batch (creates log files)
+val updateData = Seq(
+ ("id1", "Alice_Updated", 1001L, "2023-01-01"),
+ ("id2", "Bob_Updated", 2001L, "2023-01-01"),
+ ("id6", "Frank", 6000L, "2023-01-03")
+)
+
+val updateDf = updateData.toDF("id", "name", "ts", "partition")
+
+updateDf.write.format("hudi").
+ option(PRECOMBINE_FIELD.key, "ts").
+ option(RECORDKEY_FIELD.key, "id").
+ option(PARTITIONPATH_FIELD.key, "partition").
+ option("hoodie.table.name", tableName).
+ option("hoodie.datasource.write.table.type", "MERGE_ON_READ").
+ option("hoodie.datasource.write.operation", "upsert").
+ mode(SaveMode.Append).
+ save(basePath)
+
+println("Update batch written")
+
+// Create one more insert to have multiple commits
+val insertData = Seq(
+ ("id7", "Grace", 7000L, "2023-01-04"),
+ ("id8", "Henry", 8000L, "2023-01-04")
+)
+
+val insertDf = insertData.toDF("id", "name", "ts", "partition")
+
+insertDf.write.format("hudi").
+ option(PRECOMBINE_FIELD.key, "ts").
+ option(RECORDKEY_FIELD.key, "id").
+ option(PARTITIONPATH_FIELD.key, "partition").
+ option("hoodie.table.name", tableName).
+ option("hoodie.datasource.write.table.type", "MERGE_ON_READ").
+ option("hoodie.datasource.write.operation", "insert").
+ mode(SaveMode.Append).
+ save(basePath)
+
+println("Additional insert written")
+println(s"Fixture ${FIXTURE_NAME} generated successfully!")
+
+System.exit(0)
Review Comment:
nit: check all new files to make sure they have a new line at the end.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252197938
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
Will follow up with JIRA with case of going from ( 6 -> 9 ) however autoUpgrade is true but write.table.version is 8 meaning the uprgade should stop at 8.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252521292
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
+ "TABLE_CHECKSUM should be set for V4");
+ String actualChecksum = tableConfig.getString(HoodieTableConfig.TABLE_CHECKSUM);
+ assertNotNull(actualChecksum, "TABLE_CHECKSUM should not be null");
+
+ // Validate that the checksum is valid by comparing with computed checksum
+ String expectedChecksum = String.valueOf(HoodieTableConfig.generateChecksum(tableConfig.getProps()));
+ assertEquals(expectedChecksum, actualChecksum,
+ "TABLE_CHECKSUM should match computed checksum");
+
+ // TABLE_METADATA_PARTITIONS should be properly set if present
+ // Note: This is optional based on whether metadata table was enabled during upgrade
+ if (tableConfig.contains(HoodieTableConfig.TABLE_METADATA_PARTITIONS)) {
+ String metadataPartitions = tableConfig.getString(HoodieTableConfig.TABLE_METADATA_PARTITIONS);
+ assertTrue(metadataPartitions.contains("files"),
+ "TABLE_METADATA_PARTITIONS should contain 'files' partition when set");
+ }
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path migration).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ // Version 5 upgrade validates that no deprecated default partition paths exist
Review Comment:
For now im going to assume then that `validateVersion6Properties` should call validateVersion5Properties, and `validateVersion5Properties` will call `validateVersion4Properties`
Simarily for `validateVersion9Properties` it will now call `validateVersion8Properties`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146577244
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* bf1cd628b1f12ec551cede386e12ea4ac8f602ff Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459)
* e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146623292
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249332755
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
Review Comment:
Could `extractFixtureToTempDir` method be reused by `TestHoodieFileGroupReaderBase`? `TestHoodieFileGroupReaderBase#extract` is almost the same as this.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
Review Comment:
The instantiation of the meta client reads the table config from the `hoodie.properties` file so validating the properties file, again, is redundant.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
Review Comment:
Also call `validateVersionSpecificProperties` to make sure table configs still follows the table version and are not changed?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
Review Comment:
nit: remove new line
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
Could `testRoundTripUpgradeDowngrade` and `testRollbackAndCompactionBehavior` be merged together for testing upgrades since `testRollbackAndCompactionBehavior` has more validation only while the upgrade logic is the same?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
Review Comment:
nit: return `Option<HoodieTableVersion>` to avoid `null`
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
Review Comment:
nit: use `HoodeTableVersion#greaterThan` and `HoodeTableVersion#lesserThan`
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
Review Comment:
nit: use `HoodieTableVersion#greaterThan`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250088158
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
Review Comment:
Will fix this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252315416
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
Review Comment:
Will do so
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152631218
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
}, {
"hash" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530",
"triggerID" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"triggerType" : "PUSH"
}, {
"hash" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* b3b60b6069bbd0d32f33a901387facd6894dcbe8 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530)
* f27fe28ad7878db5e3e32efa378bf878e321ce18 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252010769
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
For the bloom filters in Parquet files written by Hudi, they are controlled by `hoodie.parquet.bloom.filter.enabled`. It should still be enabled, just that we can set `hoodie.index.bloom.num_entries=100`, a much smaller value compared to the default, to reduce the size.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249323483
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
Another thing is the parquet file is large likely due to the bloom filter. Could you try reduce the bloom filter size and see if that helps reducing the zip file size?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249449883
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
@yihua Is the config to disable this `hoodie.parquet.bloom.filter.enabled` to keep the size down?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249472953
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
Review Comment:
Will do so.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252331318
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
Review Comment:
yea the naming for this is confusing let me fix to say `startVersion`.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
Review Comment:
yea the naming for this is confusing let me fix to say `startVersion`. Or current/original
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252254335
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
Review Comment:
nit: `targetVersion` is still original version?
```suggestion
public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
```
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
Review Comment:
It is not necessary to add all table configs to the write config. Might be OK for now.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
Review Comment:
nit: remove this line to fall through
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
Review Comment:
The timeline layout version should not be directly set by the user.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
Review Comment:
nit: remove this line to fall through
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252384352
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
Review Comment:
will remove this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252193438
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
Yes, let's track that in a JIRA
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152628345
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
}, {
"hash" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530",
"triggerID" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"triggerType" : "PUSH"
}, {
"hash" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 53f3c89aee5184a06c82890b5a082266e542da88 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511)
* b3b60b6069bbd0d32f33a901387facd6894dcbe8 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530)
* f27fe28ad7878db5e3e32efa378bf878e321ce18 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252197938
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
Will follow up with JIRA with case of going from ( 6 -> 9 ) however autoUpgrade is true but write.table.version is 8 meaning the uprgade should stop at 8. As well as write.table.version is 6 and then it should not even autoUpgrade.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [HUDI-9684] Add Upgrade/Downgrade Test Fixtures Framework [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152943436
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
}, {
"hash" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530",
"triggerID" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"triggerType" : "PUSH"
}, {
"hash" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7534",
"triggerID" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* f27fe28ad7878db5e3e32efa378bf878e321ce18 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7534)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145952783
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* a95f25079f6dd0d1199d5d66a7340bfdddce6325 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454)
* 72c416095c9078a3d7b9e28f7a72c55ceaf0b14e Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146027962
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 72c416095c9078a3d7b9e28f7a72c55ceaf0b14e Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455)
* fe58d1cccda2993538fbc1fbd7e6cc8197a160d8 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249322638
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
When I unzip the files I see `*.crc` files under base path, partition paths, and metadata folder. They can be deleted when creating the zip file as they are not needed for testing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250103946
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
Review Comment:
ack
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149459867
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 974231b204d4d7ccaff6ddf9f9c1a434983f585c Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500)
* 4682338fa47785195286281dec5303c00eaa86c7 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509)
* 53f3c89aee5184a06c82890b5a082266e542da88 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249472599
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
Think i got something to work to make tables under 50KB each
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152559319
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
}, {
"hash" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530",
"triggerID" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 53f3c89aee5184a06c82890b5a082266e542da88 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511)
* b3b60b6069bbd0d32f33a901387facd6894dcbe8 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250486049
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
I think we can track in a JIRA this as a fast follow?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249338370
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
Review Comment:
Most of the comments look to be redundant so they can be removed.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
Review Comment:
Let's track a JIRA to add a test on a table with default/null partition for default partition change (see `FourToFiveUpgradeHandler`).
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
+ LOG.debug("Read {} rows from table {}", rowCount, stage);
+
+ // Verify table metadata is accessible
+ assertNotNull(metaClient.getTableConfig(), "Table config should be accessible " + stage);
+ assertNotNull(metaClient.getTableConfig().getTableName(), "Table name should be accessible " + stage);
+
+ LOG.info("✓ Data validation passed {} (table accessible, {} rows)", stage, rowCount);
+ } catch (Exception e) {
+ throw new RuntimeException("Data validation failed " + stage, e);
+ }
+ }
+
+ /**
+ * Perform simple read validation and return the total row count.
+ */
+ private long performSimpleReadValidation(HoodieTableMetaClient metaClient) {
+ LOG.debug("Performing read validation on table at: {}", metaClient.getBasePath());
+ try {
+ // Log table information for debugging
+ String basePath = metaClient.getBasePath().toString();
+ LOG.debug("Table base path: {}", basePath);
+ LOG.debug("Table version: {}", metaClient.getTableConfig().getTableVersion());
+ LOG.debug("Table type: {}", metaClient.getTableConfig().getTableType());
+
+ // Read entire table using Spark's built-in Hudi support
+ LOG.debug("Attempting to read table using Spark SQL...");
+ Dataset<Row> tableData = sqlContext.read()
+ .format("hudi")
+ .load(basePath);
+
+ // Validate read operation succeeded
+ assertNotNull(tableData, "Table read should not return null");
+ LOG.debug("Table read operation succeeded");
+
+ // Count rows
+ LOG.debug("Counting rows...");
+ long rowCount = tableData.count();
+ assertTrue(rowCount >= 0, "Row count should be non-negative");
+
+ LOG.debug("Successfully read {} rows from table", rowCount);
Review Comment:
nit: remove debugging logs and comments
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
Review Comment:
A few more checks: `TABLE_CHECKSUM` should exist and be valid, `TABLE_METADATA_PARTITIONS` should be properly set if MDT is enabled (see `ThreeToFourUpgradeHandler`).
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
Review Comment:
Let's track another JIRA on auxiliary folder.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
Review Comment:
Let's do full Dataframe validation using `SparkClientFunctionalTestHarness#areDataframesEqual` by validation column values?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
Review Comment:
Similar here on checking all comments and removing them as needed.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
Is there a plan to add tests for different combinations of `fromVersion`, `toVersion`, and write table versions in a subsequent PR?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
Review Comment:
Similarly, fix all table version comparison to avoid calling `.versionCode()`.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
Review Comment:
Move this to `validateVersion8Properties `?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
Review Comment:
Similarly all comments in this method are redundant
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
Review Comment:
The logic in `validateUpgradeProperties` is mostly covered by `validateVersion8Properties`. Is it still needed?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
Review Comment:
Similarly, `TimelineLayoutVersion` should be determined by the table version independently, which does not depend on the "transition state" of downgrades.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
+ LOG.debug("Read {} rows from table {}", rowCount, stage);
+
+ // Verify table metadata is accessible
+ assertNotNull(metaClient.getTableConfig(), "Table config should be accessible " + stage);
+ assertNotNull(metaClient.getTableConfig().getTableName(), "Table name should be accessible " + stage);
Review Comment:
These seem redundant, or can be incorporated into table properties validation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249475447
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
Review Comment:
I think this is a good point let me look into separating these out so its clearer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [HUDI-9684] Add Upgrade/Downgrade Test Fixtures Framework [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152980234
@yihua can you merge this?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146075537
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* fe58d1cccda2993538fbc1fbd7e6cc8197a160d8 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457)
* bf1cd628b1f12ec551cede386e12ea4ac8f602ff Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145852202
cc @nsivabalan @yihua @linliu-code
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145964439
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* a95f25079f6dd0d1199d5d66a7340bfdddce6325 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454)
* 72c416095c9078a3d7b9e28f7a72c55ceaf0b14e Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455)
* fe58d1cccda2993538fbc1fbd7e6cc8197a160d8 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3148928782
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* e69e5e414dced40fe6c6aeb3f4e01ca78acca502 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250121489
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
Review Comment:
Ack will fix this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252384813
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
Review Comment:
will remove this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [HUDI-9684] Add Upgrade/Downgrade Test Fixtures Framework [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152767601
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
}, {
"hash" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530",
"triggerID" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"triggerType" : "PUSH"
}, {
"hash" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7534",
"triggerID" : "f27fe28ad7878db5e3e32efa378bf878e321ce18",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* b3b60b6069bbd0d32f33a901387facd6894dcbe8 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7530)
* f27fe28ad7878db5e3e32efa378bf878e321ce18 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7534)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250100650
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
Review Comment:
will remove
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149490095
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 4682338fa47785195286281dec5303c00eaa86c7 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509)
* 53f3c89aee5184a06c82890b5a082266e542da88 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249327583
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/generate-fixtures.sh:
##########
@@ -0,0 +1,341 @@
+#!/bin/bash
+
+# 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.
+
+# Script to generate Hudi MOR table fixtures for different versions
+# Used by TestUpgradeDowngradeFixtures for integration testing
+
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+FIXTURES_DIR="$SCRIPT_DIR/mor-tables"
+
+echo "Generating Hudi upgrade/downgrade test fixtures..."
+echo "Fixtures directory: $FIXTURES_DIR"
+
+# Parse command line arguments
+REQUESTED_VERSIONS=""
+HUDI_BUNDLE_PATH=""
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --version)
+ REQUESTED_VERSIONS="$2"
+ shift 2
+ ;;
+ --hudi-bundle-path)
+ HUDI_BUNDLE_PATH="$2"
+ shift 2
+ ;;
+ *)
+ echo "Unknown option: $1"
+ echo "Usage: $0 [--version <version_list>] [--hudi-bundle-path <path>]"
+ echo " --version <version_list> Comma-separated list of table versions to generate (e.g., 4,5,6)"
+ echo " --hudi-bundle-path <path> Path to locally built Hudi bundle JAR (required for version 9)"
+ echo ""
+ echo "Examples:"
+ echo " $0 # Generate all versions (except 9)"
+ echo " $0 --version 4,5 # Generate versions 4 and 5"
+ echo " $0 --version 9 --hudi-bundle-path /path/to/hudi-spark3.5-bundle_2.12-1.1.0-SNAPSHOT.jar"
+ echo ""
+ echo "Note: Version 9 requires a locally built Hudi bundle from master branch"
+ exit 1
+ ;;
+ esac
+done
+
+# Convert comma-separated versions to array
+if [ -n "$REQUESTED_VERSIONS" ]; then
+ IFS=',' read -ra VERSION_ARRAY <<< "$REQUESTED_VERSIONS"
+ echo "INFO: Generating specific versions: ${VERSION_ARRAY[@]}"
+else
+ echo "INFO: Generating all fixture versions"
+fi
+
+# Function to check if a version should be generated
+should_generate_version() {
+ local version=$1
+ # If no specific versions requested, generate all
+ if [ -z "$REQUESTED_VERSIONS" ]; then
+ return 0
+ fi
+ # Check if version is in the requested array
+ for requested in "${VERSION_ARRAY[@]}"; do
+ if [ "$requested" = "$version" ]; then
+ return 0
+ fi
+ done
+ return 1
+}
+
+# Validate version 9 requirements
+if should_generate_version "9"; then
+ if [ -z "$HUDI_BUNDLE_PATH" ]; then
+ echo "ERROR: Version 9 requires --hudi-bundle-path argument"
+ echo ""
+ echo "To generate table version 9, you need to:"
+ echo "1. Build Hudi from master branch:"
+ echo " cd <hudi-repo>"
+ echo " mvn clean install -DskipTests -Dspark3.5 -Dscala-2.12 -pl packaging/hudi-spark-bundle -am"
+ echo ""
+ echo "2. Provide the path to the built bundle:"
+ echo " $0 --version 9 --hudi-bundle-path <hudi-repo>/packaging/hudi-spark-bundle/target/hudi-spark3.5-bundle_2.12-1.1.0-SNAPSHOT.jar"
+ exit 1
+ fi
+
+ if [ ! -f "$HUDI_BUNDLE_PATH" ]; then
+ echo "ERROR: Hudi bundle not found at: $HUDI_BUNDLE_PATH"
+ exit 1
+ fi
+
+ echo "Using local Hudi bundle: $HUDI_BUNDLE_PATH"
+fi
+
+# Function to ensure Spark binary is available locally
+ensure_spark_binary() {
+ local spark_version=$1
+
+ # Determine exact Spark version and tarball name
+ case "$spark_version" in
+ "3.2")
+ local spark_full_version="3.2.4"
+ local spark_tarball="spark-3.2.4-bin-hadoop3.2.tgz"
+ local extracted_dirname="spark-3.2.4-bin-hadoop3.2"
+ ;;
+ "3.3")
+ local spark_full_version="3.3.4"
+ local spark_tarball="spark-3.3.4-bin-hadoop3.tgz"
+ local extracted_dirname="spark-3.3.4-bin-hadoop3"
+ ;;
+ "3.4")
+ local spark_full_version="3.4.3"
+ local spark_tarball="spark-3.4.3-bin-hadoop3.tgz"
+ local extracted_dirname="spark-3.4.3-bin-hadoop3"
+ ;;
+ "3.5")
+ local spark_full_version="3.5.1"
+ local spark_tarball="spark-3.5.1-bin-hadoop3.tgz"
+ local extracted_dirname="spark-3.5.1-bin-hadoop3"
+ ;;
+ *)
+ echo "ERROR: Unsupported Spark version: $spark_version"
+ exit 1
+ ;;
+ esac
+
+ local spark_dir="$SCRIPT_DIR/spark-versions/spark-${spark_full_version}"
+ local spark_bin="$spark_dir/bin/spark-shell"
+
+ # Check if Spark binary already exists
+ if [ -f "$spark_bin" ]; then
+ echo "Spark $spark_full_version already available at $spark_dir" >&2
+ echo "$spark_dir"
+ return 0
+ fi
+
+ echo "Downloading Spark $spark_full_version..." >&2
+
+ local download_url="https://archive.apache.org/dist/spark/spark-${spark_full_version}/${spark_tarball}"
+ local temp_tarball="/tmp/${spark_tarball}"
+
+ # Download Spark binary
+ if ! curl -L -o "$temp_tarball" "$download_url"; then
+ echo "ERROR: Failed to download Spark $spark_full_version" >&2
+ exit 1
+ fi
+
+ # Extract to spark-versions directory
+ echo "Extracting Spark $spark_full_version..." >&2
+ mkdir -p "$SCRIPT_DIR/spark-versions"
+
+ if ! tar -xzf "$temp_tarball" -C "$SCRIPT_DIR/spark-versions/"; then
+ echo "ERROR: Failed to extract Spark $spark_full_version" >&2
+ rm -f "$temp_tarball"
+ exit 1
+ fi
+
+ # Rename extracted directory to our expected name
+ local extracted_dir="$SCRIPT_DIR/spark-versions/$extracted_dirname"
+ if [ -d "$extracted_dir" ]; then
+ mv "$extracted_dir" "$spark_dir"
+ fi
+
+ # Clean up tarball
+ rm -f "$temp_tarball"
+
+ # Add a small delay to ensure filesystem sync
+ echo "Waiting for filesystem sync..." >&2
+ sleep 1
+
+ echo "Spark $spark_full_version ready at $spark_dir" >&2
+ echo "$spark_dir"
+}
+
+# Function to generate a fixture table for a specific Hudi version
+generate_fixture() {
+ local hudi_version=$1
+ local table_version=$2
+ local fixture_name=$3
+ local spark_version=$4
+ local scala_version=$5
+
+ echo "📊 Generating fixture: $fixture_name (Hudi $hudi_version, Table Version $table_version)"
+ echo " Using Spark $spark_version with Scala $scala_version"
+
+ local fixture_path="$FIXTURES_DIR/$fixture_name"
+
+ # Clean existing fixture directory to prevent table type conflicts
+ if [ -d "$fixture_path" ]; then
+ echo "Cleaning existing fixture directory: $fixture_path"
+ rm -rf "$fixture_path"
+ fi
+
+ mkdir -p "$fixture_path"
+
+ # Ensure Spark binary is available
+ local spark_home=$(ensure_spark_binary "$spark_version")
+ echo "DEBUG: spark_home=[$spark_home]"
+
+ # Validate Spark installation
+ if [ ! -f "$spark_home/bin/spark-shell" ]; then
+ echo "ERROR: spark-shell not found at $spark_home/bin/spark-shell"
+ echo " Directory contents:"
+ ls -la "$spark_home/bin/" || echo " Directory does not exist"
+ exit 1
+ fi
+ echo "Validated spark-shell exists at: $spark_home/bin/spark-shell"
+
+ # Prepare Scala script from template
+ local table_name="${fixture_name}_table"
+ local temp_script="/tmp/generate_${fixture_name}.scala"
+
+ # Copy template and substitute variables
+ cp "$SCRIPT_DIR/scala-templates/generate-fixture.scala" "$temp_script"
+ sed -i.bak \
+ -e "s/\${FIXTURE_NAME}/$fixture_name/g" \
+ -e "s/\${TABLE_NAME}/$table_name/g" \
+ -e "s|\${BASE_PATH}|$fixture_path|g" \
+ "$temp_script"
+ rm -f "${temp_script}.bak"
+
+ # Run Spark shell directly to generate the fixture
+ echo "Running Spark shell directly from: $spark_home"
+
+ # Create temporary directory for Ivy cache to avoid permission issues
+ local ivy_cache_dir="/tmp/ivy-cache-${fixture_name}"
+ mkdir -p "$ivy_cache_dir"
+
+ # Handle version 9 specially (use local JAR instead of Maven)
+ if [ "$table_version" = "9" ]; then
+ echo "Using local Hudi bundle: $HUDI_BUNDLE_PATH"
+ "$spark_home/bin/spark-shell" \
+ --conf 'spark.serializer=org.apache.spark.serializer.KryoSerializer' \
+ --conf 'spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog' \
+ --conf 'spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension' \
+ --conf "spark.jars.ivy=$ivy_cache_dir" \
+ --conf 'spark.sql.warehouse.dir=/tmp/spark-warehouse' \
+ --jars "$HUDI_BUNDLE_PATH" -i "$temp_script"
+ else
+ # Use Maven packages for official releases
+ local hudi_bundle="org.apache.hudi:hudi-spark${spark_version}-bundle_${scala_version}:${hudi_version}"
+ echo "Using Hudi bundle: $hudi_bundle"
+ "$spark_home/bin/spark-shell" \
+ --conf 'spark.serializer=org.apache.spark.serializer.KryoSerializer' \
+ --conf 'spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog' \
+ --conf 'spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension' \
+ --conf "spark.jars.ivy=$ivy_cache_dir" \
+ --conf 'spark.sql.warehouse.dir=/tmp/spark-warehouse' \
+ --packages "$hudi_bundle" -i "$temp_script"
+ fi
+
+ # Clean up ivy cache directory
+ rm -rf "$ivy_cache_dir"
+
+ # Clean up temp script
+ rm "/tmp/generate_${fixture_name}.scala"
+
+ echo "Fixture $fixture_name generated successfully"
+}
+
+# Generate fixtures for each version using appropriate Spark versions
+echo "Generating fixtures for all supported versions..."
+
+# Based on Hudi-Spark compatibility matrix:
+# 1.0.x -> 3.5.x (default)
+# 0.15.x -> 3.5.x (default)
+# 0.14.x -> 3.4.x (default)
+# 0.13.x -> 3.3.x (default)
+# 0.12.x -> 3.3.x (default)
+# 0.11.x -> 3.2.x (default)
+
+echo "Hudi Version -> Spark Version -> Scala Version mapping:"
+
+# Hudi 0.11.1 (Table Version 4) -> Spark 3.2.x (default) -> Scala 2.12
+if should_generate_version "4"; then
+ echo " 0.11.1 -> Spark 3.2 -> Scala 2.12"
+ generate_fixture "0.11.1" "4" "hudi-v4-table" "3.2" "2.12"
+fi
+
+# Hudi 0.12.2 (Table Version 5) -> Spark 3.3.x (default) -> Scala 2.12
+if should_generate_version "5"; then
+ echo " 0.12.2 -> Spark 3.3 -> Scala 2.12"
+ generate_fixture "0.12.2" "5" "hudi-v5-table" "3.3" "2.12"
+fi
+
+# Hudi 0.14.0 (Table Version 6) -> Spark 3.4.x (default) -> Scala 2.12
+if should_generate_version "6"; then
+ echo " 0.14.0 -> Spark 3.4 -> Scala 2.12"
+ generate_fixture "0.14.0" "6" "hudi-v6-table" "3.4" "2.12"
+fi
+
+# Hudi 1.0.2 (Table Version 8) -> Spark 3.5.x (default) -> Scala 2.12
+if should_generate_version "8"; then
+ echo " 1.0.2 -> Spark 3.5 -> Scala 2.12"
+ generate_fixture "1.0.2" "8" "hudi-v8-table" "3.5" "2.12"
+fi
+
+# Hudi 1.1.0 (Table Version 9) -> Spark 3.5.x (default) -> Scala 2.12 (requires local bundle)
+if should_generate_version "9"; then
+ echo " 1.1.0 -> Spark 3.5 -> Scala 2.12 (using local bundle)"
+ generate_fixture "1.1.0" "9" "hudi-v9-table" "3.5" "2.12"
+fi
+
+
+echo ""
+echo "Fixture generation completed!"
+
+# Compress fixture tables to save space
+echo ""
+echo "Compressing fixture tables..."
+for fixture_dir in "$FIXTURES_DIR"/hudi-v*-table; do
+ if [ -d "$fixture_dir" ]; then
+ fixture_name=$(basename "$fixture_dir")
+ echo "Compressing $fixture_name..."
+ (cd "$FIXTURES_DIR" && zip -r -q -X "${fixture_name}.zip" "$fixture_name")
Review Comment:
See if the `zip` command can excluded unnecessary files as mentioned in the other review comment.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
Review Comment:
This looks redundant and can be removed.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
Review Comment:
`TestUpgradeDowngradeFixtures` -> `TestUpgradeDowngrade` (rename existing `TestUpgradeDowngrade` to `TestUpgradeDowngradeLegacy` so we can gradually rewrite tests from `TestUpgradeDowngradeLegacy` and remove `TestUpgradeDowngradeLegacy` eventually)?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
Review Comment:
Should the downgrade tests be separated into a new test? After upgrade, in certain cases the rollback is done so the upgraded table does not have inflight commit any more, thus the downgrade testing here does not cover the case with inflight commit and rollback.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
Review Comment:
```suggestion
private static Stream<Arguments> tableVersions() {
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249322638
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/mor-tables/hudi-v4-table.zip:
##########
Review Comment:
When I unzip the files I see `__MACOSX ` folder and `*.crc` files under base path, partition paths, and metadata folder (see https://gist.github.com/yihua/c78f6ab5f487e6c8715129bb646825f6). They can be deleted when creating the zip file as they are not needed for testing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249471425
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/generate-fixtures.sh:
##########
@@ -0,0 +1,341 @@
+#!/bin/bash
+
+# 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.
+
+# Script to generate Hudi MOR table fixtures for different versions
+# Used by TestUpgradeDowngradeFixtures for integration testing
+
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+FIXTURES_DIR="$SCRIPT_DIR/mor-tables"
+
+echo "Generating Hudi upgrade/downgrade test fixtures..."
+echo "Fixtures directory: $FIXTURES_DIR"
+
+# Parse command line arguments
+REQUESTED_VERSIONS=""
+HUDI_BUNDLE_PATH=""
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --version)
+ REQUESTED_VERSIONS="$2"
+ shift 2
+ ;;
+ --hudi-bundle-path)
+ HUDI_BUNDLE_PATH="$2"
+ shift 2
+ ;;
+ *)
+ echo "Unknown option: $1"
+ echo "Usage: $0 [--version <version_list>] [--hudi-bundle-path <path>]"
+ echo " --version <version_list> Comma-separated list of table versions to generate (e.g., 4,5,6)"
+ echo " --hudi-bundle-path <path> Path to locally built Hudi bundle JAR (required for version 9)"
+ echo ""
+ echo "Examples:"
+ echo " $0 # Generate all versions (except 9)"
+ echo " $0 --version 4,5 # Generate versions 4 and 5"
+ echo " $0 --version 9 --hudi-bundle-path /path/to/hudi-spark3.5-bundle_2.12-1.1.0-SNAPSHOT.jar"
+ echo ""
+ echo "Note: Version 9 requires a locally built Hudi bundle from master branch"
+ exit 1
+ ;;
+ esac
+done
+
+# Convert comma-separated versions to array
+if [ -n "$REQUESTED_VERSIONS" ]; then
+ IFS=',' read -ra VERSION_ARRAY <<< "$REQUESTED_VERSIONS"
+ echo "INFO: Generating specific versions: ${VERSION_ARRAY[@]}"
+else
+ echo "INFO: Generating all fixture versions"
+fi
+
+# Function to check if a version should be generated
+should_generate_version() {
+ local version=$1
+ # If no specific versions requested, generate all
+ if [ -z "$REQUESTED_VERSIONS" ]; then
+ return 0
+ fi
+ # Check if version is in the requested array
+ for requested in "${VERSION_ARRAY[@]}"; do
+ if [ "$requested" = "$version" ]; then
+ return 0
+ fi
+ done
+ return 1
+}
+
+# Validate version 9 requirements
+if should_generate_version "9"; then
+ if [ -z "$HUDI_BUNDLE_PATH" ]; then
+ echo "ERROR: Version 9 requires --hudi-bundle-path argument"
+ echo ""
+ echo "To generate table version 9, you need to:"
+ echo "1. Build Hudi from master branch:"
+ echo " cd <hudi-repo>"
+ echo " mvn clean install -DskipTests -Dspark3.5 -Dscala-2.12 -pl packaging/hudi-spark-bundle -am"
+ echo ""
+ echo "2. Provide the path to the built bundle:"
+ echo " $0 --version 9 --hudi-bundle-path <hudi-repo>/packaging/hudi-spark-bundle/target/hudi-spark3.5-bundle_2.12-1.1.0-SNAPSHOT.jar"
+ exit 1
+ fi
+
+ if [ ! -f "$HUDI_BUNDLE_PATH" ]; then
+ echo "ERROR: Hudi bundle not found at: $HUDI_BUNDLE_PATH"
+ exit 1
+ fi
+
+ echo "Using local Hudi bundle: $HUDI_BUNDLE_PATH"
+fi
+
+# Function to ensure Spark binary is available locally
+ensure_spark_binary() {
+ local spark_version=$1
+
+ # Determine exact Spark version and tarball name
+ case "$spark_version" in
+ "3.2")
+ local spark_full_version="3.2.4"
+ local spark_tarball="spark-3.2.4-bin-hadoop3.2.tgz"
+ local extracted_dirname="spark-3.2.4-bin-hadoop3.2"
+ ;;
+ "3.3")
+ local spark_full_version="3.3.4"
+ local spark_tarball="spark-3.3.4-bin-hadoop3.tgz"
+ local extracted_dirname="spark-3.3.4-bin-hadoop3"
+ ;;
+ "3.4")
+ local spark_full_version="3.4.3"
+ local spark_tarball="spark-3.4.3-bin-hadoop3.tgz"
+ local extracted_dirname="spark-3.4.3-bin-hadoop3"
+ ;;
+ "3.5")
+ local spark_full_version="3.5.1"
+ local spark_tarball="spark-3.5.1-bin-hadoop3.tgz"
+ local extracted_dirname="spark-3.5.1-bin-hadoop3"
+ ;;
+ *)
+ echo "ERROR: Unsupported Spark version: $spark_version"
+ exit 1
+ ;;
+ esac
+
+ local spark_dir="$SCRIPT_DIR/spark-versions/spark-${spark_full_version}"
+ local spark_bin="$spark_dir/bin/spark-shell"
+
+ # Check if Spark binary already exists
+ if [ -f "$spark_bin" ]; then
+ echo "Spark $spark_full_version already available at $spark_dir" >&2
+ echo "$spark_dir"
+ return 0
+ fi
+
+ echo "Downloading Spark $spark_full_version..." >&2
+
+ local download_url="https://archive.apache.org/dist/spark/spark-${spark_full_version}/${spark_tarball}"
+ local temp_tarball="/tmp/${spark_tarball}"
+
+ # Download Spark binary
+ if ! curl -L -o "$temp_tarball" "$download_url"; then
+ echo "ERROR: Failed to download Spark $spark_full_version" >&2
+ exit 1
+ fi
+
+ # Extract to spark-versions directory
+ echo "Extracting Spark $spark_full_version..." >&2
+ mkdir -p "$SCRIPT_DIR/spark-versions"
+
+ if ! tar -xzf "$temp_tarball" -C "$SCRIPT_DIR/spark-versions/"; then
+ echo "ERROR: Failed to extract Spark $spark_full_version" >&2
+ rm -f "$temp_tarball"
+ exit 1
+ fi
+
+ # Rename extracted directory to our expected name
+ local extracted_dir="$SCRIPT_DIR/spark-versions/$extracted_dirname"
+ if [ -d "$extracted_dir" ]; then
+ mv "$extracted_dir" "$spark_dir"
+ fi
+
+ # Clean up tarball
+ rm -f "$temp_tarball"
+
+ # Add a small delay to ensure filesystem sync
+ echo "Waiting for filesystem sync..." >&2
+ sleep 1
+
+ echo "Spark $spark_full_version ready at $spark_dir" >&2
+ echo "$spark_dir"
+}
+
+# Function to generate a fixture table for a specific Hudi version
+generate_fixture() {
+ local hudi_version=$1
+ local table_version=$2
+ local fixture_name=$3
+ local spark_version=$4
+ local scala_version=$5
+
+ echo "📊 Generating fixture: $fixture_name (Hudi $hudi_version, Table Version $table_version)"
+ echo " Using Spark $spark_version with Scala $scala_version"
+
+ local fixture_path="$FIXTURES_DIR/$fixture_name"
+
+ # Clean existing fixture directory to prevent table type conflicts
+ if [ -d "$fixture_path" ]; then
+ echo "Cleaning existing fixture directory: $fixture_path"
+ rm -rf "$fixture_path"
+ fi
+
+ mkdir -p "$fixture_path"
+
+ # Ensure Spark binary is available
+ local spark_home=$(ensure_spark_binary "$spark_version")
+ echo "DEBUG: spark_home=[$spark_home]"
+
+ # Validate Spark installation
+ if [ ! -f "$spark_home/bin/spark-shell" ]; then
+ echo "ERROR: spark-shell not found at $spark_home/bin/spark-shell"
+ echo " Directory contents:"
+ ls -la "$spark_home/bin/" || echo " Directory does not exist"
+ exit 1
+ fi
+ echo "Validated spark-shell exists at: $spark_home/bin/spark-shell"
+
+ # Prepare Scala script from template
+ local table_name="${fixture_name}_table"
+ local temp_script="/tmp/generate_${fixture_name}.scala"
+
+ # Copy template and substitute variables
+ cp "$SCRIPT_DIR/scala-templates/generate-fixture.scala" "$temp_script"
+ sed -i.bak \
+ -e "s/\${FIXTURE_NAME}/$fixture_name/g" \
+ -e "s/\${TABLE_NAME}/$table_name/g" \
+ -e "s|\${BASE_PATH}|$fixture_path|g" \
+ "$temp_script"
+ rm -f "${temp_script}.bak"
+
+ # Run Spark shell directly to generate the fixture
+ echo "Running Spark shell directly from: $spark_home"
+
+ # Create temporary directory for Ivy cache to avoid permission issues
+ local ivy_cache_dir="/tmp/ivy-cache-${fixture_name}"
+ mkdir -p "$ivy_cache_dir"
+
+ # Handle version 9 specially (use local JAR instead of Maven)
+ if [ "$table_version" = "9" ]; then
+ echo "Using local Hudi bundle: $HUDI_BUNDLE_PATH"
+ "$spark_home/bin/spark-shell" \
+ --conf 'spark.serializer=org.apache.spark.serializer.KryoSerializer' \
+ --conf 'spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog' \
+ --conf 'spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension' \
+ --conf "spark.jars.ivy=$ivy_cache_dir" \
+ --conf 'spark.sql.warehouse.dir=/tmp/spark-warehouse' \
+ --jars "$HUDI_BUNDLE_PATH" -i "$temp_script"
+ else
+ # Use Maven packages for official releases
+ local hudi_bundle="org.apache.hudi:hudi-spark${spark_version}-bundle_${scala_version}:${hudi_version}"
+ echo "Using Hudi bundle: $hudi_bundle"
+ "$spark_home/bin/spark-shell" \
+ --conf 'spark.serializer=org.apache.spark.serializer.KryoSerializer' \
+ --conf 'spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog' \
+ --conf 'spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension' \
+ --conf "spark.jars.ivy=$ivy_cache_dir" \
+ --conf 'spark.sql.warehouse.dir=/tmp/spark-warehouse' \
+ --packages "$hudi_bundle" -i "$temp_script"
+ fi
+
+ # Clean up ivy cache directory
+ rm -rf "$ivy_cache_dir"
+
+ # Clean up temp script
+ rm "/tmp/generate_${fixture_name}.scala"
+
+ echo "Fixture $fixture_name generated successfully"
+}
+
+# Generate fixtures for each version using appropriate Spark versions
+echo "Generating fixtures for all supported versions..."
+
+# Based on Hudi-Spark compatibility matrix:
+# 1.0.x -> 3.5.x (default)
+# 0.15.x -> 3.5.x (default)
+# 0.14.x -> 3.4.x (default)
+# 0.13.x -> 3.3.x (default)
+# 0.12.x -> 3.3.x (default)
+# 0.11.x -> 3.2.x (default)
+
+echo "Hudi Version -> Spark Version -> Scala Version mapping:"
+
+# Hudi 0.11.1 (Table Version 4) -> Spark 3.2.x (default) -> Scala 2.12
+if should_generate_version "4"; then
+ echo " 0.11.1 -> Spark 3.2 -> Scala 2.12"
+ generate_fixture "0.11.1" "4" "hudi-v4-table" "3.2" "2.12"
+fi
+
+# Hudi 0.12.2 (Table Version 5) -> Spark 3.3.x (default) -> Scala 2.12
+if should_generate_version "5"; then
+ echo " 0.12.2 -> Spark 3.3 -> Scala 2.12"
+ generate_fixture "0.12.2" "5" "hudi-v5-table" "3.3" "2.12"
+fi
+
+# Hudi 0.14.0 (Table Version 6) -> Spark 3.4.x (default) -> Scala 2.12
+if should_generate_version "6"; then
+ echo " 0.14.0 -> Spark 3.4 -> Scala 2.12"
+ generate_fixture "0.14.0" "6" "hudi-v6-table" "3.4" "2.12"
+fi
+
+# Hudi 1.0.2 (Table Version 8) -> Spark 3.5.x (default) -> Scala 2.12
+if should_generate_version "8"; then
+ echo " 1.0.2 -> Spark 3.5 -> Scala 2.12"
+ generate_fixture "1.0.2" "8" "hudi-v8-table" "3.5" "2.12"
+fi
+
+# Hudi 1.1.0 (Table Version 9) -> Spark 3.5.x (default) -> Scala 2.12 (requires local bundle)
+if should_generate_version "9"; then
+ echo " 1.1.0 -> Spark 3.5 -> Scala 2.12 (using local bundle)"
+ generate_fixture "1.1.0" "9" "hudi-v9-table" "3.5" "2.12"
+fi
+
+
+echo ""
+echo "Fixture generation completed!"
+
+# Compress fixture tables to save space
+echo ""
+echo "Compressing fixture tables..."
+for fixture_dir in "$FIXTURES_DIR"/hudi-v*-table; do
+ if [ -d "$fixture_dir" ]; then
+ fixture_name=$(basename "$fixture_dir")
+ echo "Compressing $fixture_name..."
+ (cd "$FIXTURES_DIR" && zip -r -q -X "${fixture_name}.zip" "$fixture_name")
Review Comment:
Will do so
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249490260
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
Review Comment:
good point
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250042112
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
Review Comment:
Have added a util to be used between both classes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250092144
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
Review Comment:
Will remove these
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250104913
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
Review Comment:
Will do so
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250103999
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
Review Comment:
I think you are correct, will consolidate this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250103946
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
Review Comment:
ack
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252233034
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
Review Comment:
Should the rows be collected into a `List` to trigger the execution and then converted back to `Dataset<Row>`, to make sure the data fetching is actually executed before the upgrade?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
Review Comment:
I see most logic is shared between `testUpgradeOnly` and `testDowngradeOnly`. Should they be consolidated into `testUpgradeOrDowngrade(HoodieTableVersion fromVersion, HoodieTableVersion toVersion)`?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
Review Comment:
For certain version upgrade, assert `finalPendingCommit` is 0 since rollback should happen?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
Review Comment:
Similar here
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252647428
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
Review Comment:
I think you are right, will use `collectAsList` to trigger execution.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149320817
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 974231b204d4d7ccaff6ddf9f9c1a434983f585c Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500)
* 4682338fa47785195286281dec5303c00eaa86c7 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252191119
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
Review Comment:
will do
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252533941
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
Review Comment:
First will try your idea of consolidating into one method.
However I think it might be good to have these separate, and instead try to refactor similar setup between the two methods.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3152553643
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
}, {
"hash" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "b3b60b6069bbd0d32f33a901387facd6894dcbe8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 53f3c89aee5184a06c82890b5a082266e542da88 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511)
* b3b60b6069bbd0d32f33a901387facd6894dcbe8 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149739382
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 53f3c89aee5184a06c82890b5a082266e542da88 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7511)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252288187
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
+ "TABLE_CHECKSUM should be set for V4");
+ String actualChecksum = tableConfig.getString(HoodieTableConfig.TABLE_CHECKSUM);
+ assertNotNull(actualChecksum, "TABLE_CHECKSUM should not be null");
+
+ // Validate that the checksum is valid by comparing with computed checksum
+ String expectedChecksum = String.valueOf(HoodieTableConfig.generateChecksum(tableConfig.getProps()));
+ assertEquals(expectedChecksum, actualChecksum,
+ "TABLE_CHECKSUM should match computed checksum");
+
+ // TABLE_METADATA_PARTITIONS should be properly set if present
+ // Note: This is optional based on whether metadata table was enabled during upgrade
+ if (tableConfig.contains(HoodieTableConfig.TABLE_METADATA_PARTITIONS)) {
+ String metadataPartitions = tableConfig.getString(HoodieTableConfig.TABLE_METADATA_PARTITIONS);
+ assertTrue(metadataPartitions.contains("files"),
+ "TABLE_METADATA_PARTITIONS should contain 'files' partition when set");
+ }
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path migration).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ // Version 5 upgrade validates that no deprecated default partition paths exist
Review Comment:
Still call `validateVersion4Properties` as part of `validateVersion5Properties` like before? Similarly for other version-specific validation if that applies.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
+ "TABLE_CHECKSUM should be set for V4");
+ String actualChecksum = tableConfig.getString(HoodieTableConfig.TABLE_CHECKSUM);
+ assertNotNull(actualChecksum, "TABLE_CHECKSUM should not be null");
+
+ // Validate that the checksum is valid by comparing with computed checksum
+ String expectedChecksum = String.valueOf(HoodieTableConfig.generateChecksum(tableConfig.getProps()));
+ assertEquals(expectedChecksum, actualChecksum,
+ "TABLE_CHECKSUM should match computed checksum");
+
+ // TABLE_METADATA_PARTITIONS should be properly set if present
+ // Note: This is optional based on whether metadata table was enabled during upgrade
+ if (tableConfig.contains(HoodieTableConfig.TABLE_METADATA_PARTITIONS)) {
+ String metadataPartitions = tableConfig.getString(HoodieTableConfig.TABLE_METADATA_PARTITIONS);
+ assertTrue(metadataPartitions.contains("files"),
+ "TABLE_METADATA_PARTITIONS should contain 'files' partition when set");
+ }
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path migration).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ // Version 5 upgrade validates that no deprecated default partition paths exist
+ // The upgrade handler checks for DEPRECATED_DEFAULT_PARTITION_PATH ("default")
+ // and requires migration to DEFAULT_PARTITION_PATH ("__HIVE_DEFAULT_PARTITION__")
+
+ // If table is partitioned, validate partition path migration
+ if (tableConfig.isTablePartitioned()) {
+ LOG.info("Validating V5 partition path migration for partitioned table");
+
+ // Check hive-style partitioning configuration
+ boolean hiveStylePartitioningEnable = Boolean.parseBoolean(tableConfig.getHiveStylePartitioningEnable());
+ LOG.info("Hive-style partitioning enabled: {}", hiveStylePartitioningEnable);
+
+ // Validate partition field configuration exists
+ assertTrue(tableConfig.getPartitionFields().isPresent(),
+ "Partition fields should be present for partitioned table in V5");
+ } else {
+ LOG.info("Non-partitioned table - skipping partition path validation for V5");
+ }
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ * Based on FiveToSixUpgradeHandler - validates that compaction REQUESTED files were properly cleaned up.
+ */
+ private void validateVersion6Properties(HoodieTableMetaClient metaClient) throws IOException {
+ // Version 6 upgrade deletes compaction requested files from .aux folder (HUDI-6040)
+ // Validate that no REQUESTED compaction files remain in auxiliary folder
+
+ StoragePath auxPath = new StoragePath(metaClient.getMetaAuxiliaryPath());
+
+ if (!metaClient.getStorage().exists(auxPath)) {
+ // Auxiliary folder doesn't exist - this is valid, nothing to clean up
+ LOG.info("V6 validation passed: Auxiliary folder does not exist");
+ return;
+ }
+
+ // Auxiliary folder exists - validate that REQUESTED compaction files were cleaned up
+ LOG.info("V6 validation: Checking auxiliary folder cleanup at: {}", auxPath);
+
+ // Get pending compaction timeline with REQUESTED state (same as upgrade handler)
+ HoodieTimeline compactionTimeline = metaClient.getActiveTimeline().filterPendingCompactionTimeline()
+ .filter(instant -> instant.getState() == HoodieInstant.State.REQUESTED);
+
+ InstantFileNameGenerator factory = metaClient.getInstantFileNameGenerator();
+
+ // Validate that none of the REQUESTED compaction files exist in auxiliary folder
+ compactionTimeline.getInstantsAsStream().forEach(instant -> {
+ StoragePath compactionFile = new StoragePath(metaClient.getMetaAuxiliaryPath(), factory.getFileName(instant));
+ try {
+ if (metaClient.getStorage().exists(compactionFile)) {
+ throw new AssertionError("V6 validation failed: REQUESTED compaction file should have been cleaned up but still exists: " + compactionFile);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to check existence of compaction file: " + compactionFile, e);
+ }
+ });
+
+ LOG.info("V6 validation passed: {} REQUESTED compaction instants verified to be cleaned up from auxiliary folder",
+ compactionTimeline.countInstants());
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ // Timeline layout should be upgraded to V2 for V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present for V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be V2 for V8+");
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Read table data for validation purposes.
+ */
+ private Dataset<Row> readTableData(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Reading table data {}", stage);
+
+ try {
+ String basePath = metaClient.getBasePath().toString();
+ Dataset<Row> tableData = sqlContext().read()
+ .format("hudi")
+ .load(basePath);
+
+ assertNotNull(tableData, "Table read should not return null " + stage);
+ long rowCount = tableData.count();
+ assertTrue(rowCount >= 0, "Row count should be non-negative " + stage);
+
+ LOG.info("Successfully read table data {} ({} rows)", stage, rowCount);
+ return tableData;
+ } catch (Exception e) {
+ LOG.error("Failed to read table data {} from: {} (version: {})",
+ stage, metaClient.getBasePath(), metaClient.getTableConfig().getTableVersion(), e);
+ throw new RuntimeException("Failed to read table data " + stage, e);
+ }
+ }
+
+ /**
+ * Validate data consistency between original data and data after upgrade/downgrade.
+ * This ensures that upgrade/downgrade operations preserve data integrity.
+ */
+ private void validateDataConsistency(Dataset<Row> originalData, HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Validating data consistency {}", stage);
+
+ try {
+ Dataset<Row> currentData = readTableData(metaClient, stage);
+
+ // Exclude Hudi metadata columns
+ Set<String> hoodieMetadataColumns = new HashSet<>(Arrays.asList(
+ "_hoodie_commit_time", "_hoodie_commit_seqno", "_hoodie_record_key",
+ "_hoodie_partition_path", "_hoodie_file_name"));
+
+ Set<String> columnsToValidate = Arrays.stream(originalData.columns())
+ .filter(col -> !hoodieMetadataColumns.contains(col))
+ .collect(Collectors.toSet());
+
+ if (columnsToValidate.isEmpty()) {
+ LOG.info("Skipping data consistency validation {} (no business columns to validate)", stage);
+ return;
+ }
+
+ LOG.info("Validating data columns: {}", columnsToValidate);
+ boolean dataConsistent = areDataframesEqual(originalData, currentData, columnsToValidate);
+ assertTrue(dataConsistent, " data should be consistent between original and " + stage + " states");
+
+ LOG.info("Data consistency validation passed {}", stage);
+ } catch (Exception e) {
+ throw new RuntimeException("Data consistency validation failed " + stage, e);
+ }
+ }
+
+ /**
+ * Simple data validation for testAutoUpgradeDisabled.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing simple data validation on table {}", stage);
+
+ try {
+ Dataset<Row> tableData = readTableData(metaClient, stage);
+ LOG.info("Simple data validation passed {} (table accessible, {} rows)", stage, tableData.count());
+ } catch (Exception e) {
+ throw new RuntimeException("Simple data validation failed " + stage, e);
+ }
+ }
+
Review Comment:
nit: remove empty line
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
+ "TABLE_CHECKSUM should be set for V4");
+ String actualChecksum = tableConfig.getString(HoodieTableConfig.TABLE_CHECKSUM);
+ assertNotNull(actualChecksum, "TABLE_CHECKSUM should not be null");
+
+ // Validate that the checksum is valid by comparing with computed checksum
+ String expectedChecksum = String.valueOf(HoodieTableConfig.generateChecksum(tableConfig.getProps()));
+ assertEquals(expectedChecksum, actualChecksum,
+ "TABLE_CHECKSUM should match computed checksum");
+
+ // TABLE_METADATA_PARTITIONS should be properly set if present
+ // Note: This is optional based on whether metadata table was enabled during upgrade
+ if (tableConfig.contains(HoodieTableConfig.TABLE_METADATA_PARTITIONS)) {
+ String metadataPartitions = tableConfig.getString(HoodieTableConfig.TABLE_METADATA_PARTITIONS);
+ assertTrue(metadataPartitions.contains("files"),
+ "TABLE_METADATA_PARTITIONS should contain 'files' partition when set");
+ }
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path migration).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ // Version 5 upgrade validates that no deprecated default partition paths exist
+ // The upgrade handler checks for DEPRECATED_DEFAULT_PARTITION_PATH ("default")
+ // and requires migration to DEFAULT_PARTITION_PATH ("__HIVE_DEFAULT_PARTITION__")
+
+ // If table is partitioned, validate partition path migration
+ if (tableConfig.isTablePartitioned()) {
+ LOG.info("Validating V5 partition path migration for partitioned table");
+
+ // Check hive-style partitioning configuration
+ boolean hiveStylePartitioningEnable = Boolean.parseBoolean(tableConfig.getHiveStylePartitioningEnable());
+ LOG.info("Hive-style partitioning enabled: {}", hiveStylePartitioningEnable);
+
+ // Validate partition field configuration exists
+ assertTrue(tableConfig.getPartitionFields().isPresent(),
+ "Partition fields should be present for partitioned table in V5");
+ } else {
+ LOG.info("Non-partitioned table - skipping partition path validation for V5");
+ }
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ * Based on FiveToSixUpgradeHandler - validates that compaction REQUESTED files were properly cleaned up.
+ */
+ private void validateVersion6Properties(HoodieTableMetaClient metaClient) throws IOException {
+ // Version 6 upgrade deletes compaction requested files from .aux folder (HUDI-6040)
+ // Validate that no REQUESTED compaction files remain in auxiliary folder
+
+ StoragePath auxPath = new StoragePath(metaClient.getMetaAuxiliaryPath());
+
+ if (!metaClient.getStorage().exists(auxPath)) {
+ // Auxiliary folder doesn't exist - this is valid, nothing to clean up
+ LOG.info("V6 validation passed: Auxiliary folder does not exist");
+ return;
+ }
+
+ // Auxiliary folder exists - validate that REQUESTED compaction files were cleaned up
+ LOG.info("V6 validation: Checking auxiliary folder cleanup at: {}", auxPath);
+
+ // Get pending compaction timeline with REQUESTED state (same as upgrade handler)
+ HoodieTimeline compactionTimeline = metaClient.getActiveTimeline().filterPendingCompactionTimeline()
+ .filter(instant -> instant.getState() == HoodieInstant.State.REQUESTED);
+
+ InstantFileNameGenerator factory = metaClient.getInstantFileNameGenerator();
+
+ // Validate that none of the REQUESTED compaction files exist in auxiliary folder
+ compactionTimeline.getInstantsAsStream().forEach(instant -> {
+ StoragePath compactionFile = new StoragePath(metaClient.getMetaAuxiliaryPath(), factory.getFileName(instant));
+ try {
+ if (metaClient.getStorage().exists(compactionFile)) {
+ throw new AssertionError("V6 validation failed: REQUESTED compaction file should have been cleaned up but still exists: " + compactionFile);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to check existence of compaction file: " + compactionFile, e);
+ }
+ });
+
+ LOG.info("V6 validation passed: {} REQUESTED compaction instants verified to be cleaned up from auxiliary folder",
+ compactionTimeline.countInstants());
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ // Timeline layout should be upgraded to V2 for V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present for V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be V2 for V8+");
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Read table data for validation purposes.
+ */
+ private Dataset<Row> readTableData(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Reading table data {}", stage);
+
+ try {
+ String basePath = metaClient.getBasePath().toString();
+ Dataset<Row> tableData = sqlContext().read()
+ .format("hudi")
+ .load(basePath);
+
+ assertNotNull(tableData, "Table read should not return null " + stage);
+ long rowCount = tableData.count();
+ assertTrue(rowCount >= 0, "Row count should be non-negative " + stage);
+
+ LOG.info("Successfully read table data {} ({} rows)", stage, rowCount);
+ return tableData;
+ } catch (Exception e) {
+ LOG.error("Failed to read table data {} from: {} (version: {})",
+ stage, metaClient.getBasePath(), metaClient.getTableConfig().getTableVersion(), e);
+ throw new RuntimeException("Failed to read table data " + stage, e);
+ }
+ }
+
+ /**
+ * Validate data consistency between original data and data after upgrade/downgrade.
+ * This ensures that upgrade/downgrade operations preserve data integrity.
+ */
+ private void validateDataConsistency(Dataset<Row> originalData, HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Validating data consistency {}", stage);
+
+ try {
+ Dataset<Row> currentData = readTableData(metaClient, stage);
+
+ // Exclude Hudi metadata columns
+ Set<String> hoodieMetadataColumns = new HashSet<>(Arrays.asList(
+ "_hoodie_commit_time", "_hoodie_commit_seqno", "_hoodie_record_key",
+ "_hoodie_partition_path", "_hoodie_file_name"));
+
+ Set<String> columnsToValidate = Arrays.stream(originalData.columns())
+ .filter(col -> !hoodieMetadataColumns.contains(col))
+ .collect(Collectors.toSet());
+
+ if (columnsToValidate.isEmpty()) {
+ LOG.info("Skipping data consistency validation {} (no business columns to validate)", stage);
+ return;
+ }
+
+ LOG.info("Validating data columns: {}", columnsToValidate);
+ boolean dataConsistent = areDataframesEqual(originalData, currentData, columnsToValidate);
+ assertTrue(dataConsistent, " data should be consistent between original and " + stage + " states");
+
+ LOG.info("Data consistency validation passed {}", stage);
+ } catch (Exception e) {
+ throw new RuntimeException("Data consistency validation failed " + stage, e);
+ }
+ }
+
+ /**
+ * Simple data validation for testAutoUpgradeDisabled.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
Review Comment:
Could this be removed since `validateDataConsistency` has stronger validation?
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
Review Comment:
Add timeline layout version
`assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get());`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3148835776
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469)
* e69e5e414dced40fe6c6aeb3f4e01ca78acca502 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149465214
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
}, {
"hash" : "53f3c89aee5184a06c82890b5a082266e542da88",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "53f3c89aee5184a06c82890b5a082266e542da88",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 4682338fa47785195286281dec5303c00eaa86c7 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509)
* 53f3c89aee5184a06c82890b5a082266e542da88 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145856955
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* a95f25079f6dd0d1199d5d66a7340bfdddce6325 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146048884
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 72c416095c9078a3d7b9e28f7a72c55ceaf0b14e Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455)
* fe58d1cccda2993538fbc1fbd7e6cc8197a160d8 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457)
* bf1cd628b1f12ec551cede386e12ea4ac8f602ff UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146050331
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* fe58d1cccda2993538fbc1fbd7e6cc8197a160d8 Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457)
* bf1cd628b1f12ec551cede386e12ea4ac8f602ff UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250177728
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
+ LOG.debug("Read {} rows from table {}", rowCount, stage);
+
+ // Verify table metadata is accessible
+ assertNotNull(metaClient.getTableConfig(), "Table config should be accessible " + stage);
+ assertNotNull(metaClient.getTableConfig().getTableName(), "Table name should be accessible " + stage);
+
+ LOG.info("✓ Data validation passed {} (table accessible, {} rows)", stage, rowCount);
+ } catch (Exception e) {
+ throw new RuntimeException("Data validation failed " + stage, e);
+ }
+ }
+
+ /**
+ * Perform simple read validation and return the total row count.
+ */
+ private long performSimpleReadValidation(HoodieTableMetaClient metaClient) {
+ LOG.debug("Performing read validation on table at: {}", metaClient.getBasePath());
+ try {
+ // Log table information for debugging
+ String basePath = metaClient.getBasePath().toString();
+ LOG.debug("Table base path: {}", basePath);
+ LOG.debug("Table version: {}", metaClient.getTableConfig().getTableVersion());
+ LOG.debug("Table type: {}", metaClient.getTableConfig().getTableType());
+
+ // Read entire table using Spark's built-in Hudi support
+ LOG.debug("Attempting to read table using Spark SQL...");
+ Dataset<Row> tableData = sqlContext.read()
+ .format("hudi")
+ .load(basePath);
+
+ // Validate read operation succeeded
+ assertNotNull(tableData, "Table read should not return null");
+ LOG.debug("Table read operation succeeded");
+
+ // Count rows
+ LOG.debug("Counting rows...");
+ long rowCount = tableData.count();
+ assertTrue(rowCount >= 0, "Row count should be non-negative");
+
+ LOG.debug("Successfully read {} rows from table", rowCount);
Review Comment:
will remove
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3148986150
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* e69e5e414dced40fe6c6aeb3f4e01ca78acca502 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493)
* 974231b204d4d7ccaff6ddf9f9c1a434983f585c UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252621003
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
Review Comment:
Yes for specific handlers we need to verify this, i will add more stricter logic for this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249496001
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
Review Comment:
So you are saying to make some zip extract utils that both test classes can leverage?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145967964
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "CANCELED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 72c416095c9078a3d7b9e28f7a72c55ceaf0b14e Azure: [CANCELED](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455)
* fe58d1cccda2993538fbc1fbd7e6cc8197a160d8 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145854475
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* a95f25079f6dd0d1199d5d66a7340bfdddce6325 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3146140511
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* bf1cd628b1f12ec551cede386e12ea4ac8f602ff Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250085320
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
Review Comment:
Will fix this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250100780
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
Review Comment:
will do
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250121670
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
+ LOG.debug("Read {} rows from table {}", rowCount, stage);
+
+ // Verify table metadata is accessible
+ assertNotNull(metaClient.getTableConfig(), "Table config should be accessible " + stage);
+ assertNotNull(metaClient.getTableConfig().getTableName(), "Table name should be accessible " + stage);
Review Comment:
will remove these
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250121776
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
Review Comment:
Ack, will look into doing this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252306133
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // TABLE_CHECKSUM should exist and be valid
+ assertTrue(tableConfig.contains(HoodieTableConfig.TABLE_CHECKSUM),
+ "TABLE_CHECKSUM should be set for V4");
+ String actualChecksum = tableConfig.getString(HoodieTableConfig.TABLE_CHECKSUM);
+ assertNotNull(actualChecksum, "TABLE_CHECKSUM should not be null");
+
+ // Validate that the checksum is valid by comparing with computed checksum
+ String expectedChecksum = String.valueOf(HoodieTableConfig.generateChecksum(tableConfig.getProps()));
+ assertEquals(expectedChecksum, actualChecksum,
+ "TABLE_CHECKSUM should match computed checksum");
+
+ // TABLE_METADATA_PARTITIONS should be properly set if present
+ // Note: This is optional based on whether metadata table was enabled during upgrade
+ if (tableConfig.contains(HoodieTableConfig.TABLE_METADATA_PARTITIONS)) {
+ String metadataPartitions = tableConfig.getString(HoodieTableConfig.TABLE_METADATA_PARTITIONS);
+ assertTrue(metadataPartitions.contains("files"),
+ "TABLE_METADATA_PARTITIONS should contain 'files' partition when set");
+ }
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path migration).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ // Version 5 upgrade validates that no deprecated default partition paths exist
+ // The upgrade handler checks for DEPRECATED_DEFAULT_PARTITION_PATH ("default")
+ // and requires migration to DEFAULT_PARTITION_PATH ("__HIVE_DEFAULT_PARTITION__")
+
+ // If table is partitioned, validate partition path migration
+ if (tableConfig.isTablePartitioned()) {
+ LOG.info("Validating V5 partition path migration for partitioned table");
+
+ // Check hive-style partitioning configuration
+ boolean hiveStylePartitioningEnable = Boolean.parseBoolean(tableConfig.getHiveStylePartitioningEnable());
+ LOG.info("Hive-style partitioning enabled: {}", hiveStylePartitioningEnable);
+
+ // Validate partition field configuration exists
+ assertTrue(tableConfig.getPartitionFields().isPresent(),
+ "Partition fields should be present for partitioned table in V5");
+ } else {
+ LOG.info("Non-partitioned table - skipping partition path validation for V5");
+ }
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ * Based on FiveToSixUpgradeHandler - validates that compaction REQUESTED files were properly cleaned up.
+ */
+ private void validateVersion6Properties(HoodieTableMetaClient metaClient) throws IOException {
+ // Version 6 upgrade deletes compaction requested files from .aux folder (HUDI-6040)
+ // Validate that no REQUESTED compaction files remain in auxiliary folder
+
+ StoragePath auxPath = new StoragePath(metaClient.getMetaAuxiliaryPath());
+
+ if (!metaClient.getStorage().exists(auxPath)) {
+ // Auxiliary folder doesn't exist - this is valid, nothing to clean up
+ LOG.info("V6 validation passed: Auxiliary folder does not exist");
+ return;
+ }
+
+ // Auxiliary folder exists - validate that REQUESTED compaction files were cleaned up
+ LOG.info("V6 validation: Checking auxiliary folder cleanup at: {}", auxPath);
+
+ // Get pending compaction timeline with REQUESTED state (same as upgrade handler)
+ HoodieTimeline compactionTimeline = metaClient.getActiveTimeline().filterPendingCompactionTimeline()
+ .filter(instant -> instant.getState() == HoodieInstant.State.REQUESTED);
+
+ InstantFileNameGenerator factory = metaClient.getInstantFileNameGenerator();
+
+ // Validate that none of the REQUESTED compaction files exist in auxiliary folder
+ compactionTimeline.getInstantsAsStream().forEach(instant -> {
+ StoragePath compactionFile = new StoragePath(metaClient.getMetaAuxiliaryPath(), factory.getFileName(instant));
+ try {
+ if (metaClient.getStorage().exists(compactionFile)) {
+ throw new AssertionError("V6 validation failed: REQUESTED compaction file should have been cleaned up but still exists: " + compactionFile);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to check existence of compaction file: " + compactionFile, e);
+ }
+ });
+
+ LOG.info("V6 validation passed: {} REQUESTED compaction instants verified to be cleaned up from auxiliary folder",
+ compactionTimeline.countInstants());
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ // Timeline layout should be upgraded to V2 for V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present for V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be V2 for V8+");
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Read table data for validation purposes.
+ */
+ private Dataset<Row> readTableData(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Reading table data {}", stage);
+
+ try {
+ String basePath = metaClient.getBasePath().toString();
+ Dataset<Row> tableData = sqlContext().read()
+ .format("hudi")
+ .load(basePath);
+
+ assertNotNull(tableData, "Table read should not return null " + stage);
+ long rowCount = tableData.count();
+ assertTrue(rowCount >= 0, "Row count should be non-negative " + stage);
+
+ LOG.info("Successfully read table data {} ({} rows)", stage, rowCount);
+ return tableData;
+ } catch (Exception e) {
+ LOG.error("Failed to read table data {} from: {} (version: {})",
+ stage, metaClient.getBasePath(), metaClient.getTableConfig().getTableVersion(), e);
+ throw new RuntimeException("Failed to read table data " + stage, e);
+ }
+ }
+
+ /**
+ * Validate data consistency between original data and data after upgrade/downgrade.
+ * This ensures that upgrade/downgrade operations preserve data integrity.
+ */
+ private void validateDataConsistency(Dataset<Row> originalData, HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Validating data consistency {}", stage);
+
+ try {
+ Dataset<Row> currentData = readTableData(metaClient, stage);
+
+ // Exclude Hudi metadata columns
+ Set<String> hoodieMetadataColumns = new HashSet<>(Arrays.asList(
+ "_hoodie_commit_time", "_hoodie_commit_seqno", "_hoodie_record_key",
+ "_hoodie_partition_path", "_hoodie_file_name"));
+
+ Set<String> columnsToValidate = Arrays.stream(originalData.columns())
+ .filter(col -> !hoodieMetadataColumns.contains(col))
+ .collect(Collectors.toSet());
+
+ if (columnsToValidate.isEmpty()) {
+ LOG.info("Skipping data consistency validation {} (no business columns to validate)", stage);
+ return;
+ }
+
+ LOG.info("Validating data columns: {}", columnsToValidate);
+ boolean dataConsistent = areDataframesEqual(originalData, currentData, columnsToValidate);
+ assertTrue(dataConsistent, " data should be consistent between original and " + stage + " states");
+
+ LOG.info("Data consistency validation passed {}", stage);
+ } catch (Exception e) {
+ throw new RuntimeException("Data consistency validation failed " + stage, e);
+ }
+ }
+
+ /**
+ * Simple data validation for testAutoUpgradeDisabled.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
Review Comment:
yes will remove this older comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3148833766
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469)
* e69e5e414dced40fe6c6aeb3f4e01ca78acca502 UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252014445
##########
hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeLegacy.java:
##########
@@ -111,7 +111,7 @@
/**
* Unit tests {@link UpgradeDowngrade}.
*/
-public class TestUpgradeDowngrade extends HoodieClientTestBase {
+public class TestUpgradeDowngradeLegacy extends HoodieClientTestBase {
Review Comment:
nit: add a line in the Javadocs to say that new tests on upgrade and downgrade should be added to `TestUpgradeDowngrade` using the test fixtures.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ }
+
+ /**
+ * Validate specific properties for a given table version.
+ */
+ private void validateSpecificPropertiesForVersion(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig, HoodieTableVersion version) throws IOException {
+ switch (version) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(metaClient);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", version);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
Review Comment:
Check all `validateVersionNProperties` methods. There are still spurious comments.
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
+ LOG.info("Testing downgrade for version {}", targetVersion);
+
+ HoodieTableMetaClient targetMetaClient = loadFixtureTable(targetVersion);
+ assertEquals(targetVersion, targetMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> sourceVersionOpt = getPreviousVersion(targetVersion);
+ if (!sourceVersionOpt.isPresent()) {
+ LOG.info("Skipping downgrade test for version {} (no lower version available)", targetVersion);
+ return;
+ }
+ HoodieTableVersion sourceVersion = sourceVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(targetMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = targetMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = targetMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before downgrade for validation
+ Dataset<Row> originalData = readTableData(targetMetaClient, "before downgrade");
+
+ LOG.info("Downgrading from {} to {}", targetVersion, sourceVersion);
+ new UpgradeDowngrade(targetMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(sourceVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient downgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(targetMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(downgradedMetaClient, sourceVersion);
+ validateVersionSpecificProperties(downgradedMetaClient, targetVersion, sourceVersion);
+ validateDataConsistency(originalData, downgradedMetaClient, "after downgrade");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = downgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after downgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = downgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after downgrade");
+
+ LOG.info("Successfully completed downgrade test for version {} -> {}", targetVersion, sourceVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("tableVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ validateSpecificPropertiesForVersion(unchangedMetaClient, unchangedMetaClient.getTableConfig(), originalVersion);
+ validateVersionSpecificProperties(unchangedMetaClient, originalVersion, originalVersion);
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+ HoodieTestUtils.extractZipToDirectory(resourcePath, tempDir, getClass());
+
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private Option<HoodieTableVersion> getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.NINE);
+ case NINE:
+ return Option.empty(); // No higher version available
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get the previous version down from the current version.
+ */
+ private Option<HoodieTableVersion> getPreviousVersion(HoodieTableVersion current) {
+ switch (current) {
+ case NINE:
+ return Option.of(HoodieTableVersion.EIGHT);
+ case EIGHT:
+ return Option.of(HoodieTableVersion.SIX);
+ case SIX:
+ return Option.of(HoodieTableVersion.FIVE);
+ case FIVE:
+ return Option.of(HoodieTableVersion.FOUR);
+ case FOUR:
+ return Option.empty(); // for now we are focusing on V4-V9
+ default:
+ return Option.empty();
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for all table versions.
+ */
+ private static Stream<Arguments> tableVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Provide test parameters for upgrade versions (V4-V8).
+ */
+ private static Stream<Arguments> upgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // V4 -> V5
+ Arguments.of(HoodieTableVersion.FIVE), // V5 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT) // V8 -> V9
+ );
+ }
+
+ /**
+ * Provide test parameters for downgrade versions (V9 down to V5).
+ */
+ private static Stream<Arguments> downgradeVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.NINE), // V9 -> V8
+ Arguments.of(HoodieTableVersion.EIGHT), // V8 -> V6
+ Arguments.of(HoodieTableVersion.SIX), // V6 -> V5
+ Arguments.of(HoodieTableVersion.FIVE) // V5 -> V4
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+ if (expectedVersion.greaterThanOrEquals(HoodieTableVersion.FOUR)) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) {
+ assertEquals(expectedVersion,
+ metaClient.getTableConfig().getTableVersion());
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
Review Comment:
`fromVersion` is not used in the validation. Can `validateVersionSpecificProperties` and `validateSpecificPropertiesForVersion` be merged into one (`validateVersionSpecificProperties`) by taking `version` only?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [HUDI-9684] Add Upgrade/Downgrade Test Fixtures Framework [hudi]
Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua merged PR #13669:
URL: https://github.com/apache/hudi/pull/13669
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2252533941
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngrade.java:
##########
@@ -0,0 +1,653 @@
+/*
+ * 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.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+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.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.table.timeline.InstantFileNameGenerator;
+import org.apache.hudi.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.testutils.HoodieTestUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.SparkClientFunctionalTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases.
+ */
+public class TestUpgradeDowngrade extends SparkClientFunctionalTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngrade.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @ParameterizedTest
+ @MethodSource("upgradeVersions")
+ public void testUpgradeOnly(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing upgrade for version {}", originalVersion);
+
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ Option<HoodieTableVersion> targetVersionOpt = getNextVersion(originalVersion);
+ if (!targetVersionOpt.isPresent()) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+ HoodieTableVersion targetVersion = targetVersionOpt.get();
+
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Read original data before upgrade for validation
+ Dataset<Row> originalData = readTableData(originalMetaClient, "before upgrade");
+
+ LOG.info("Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context(), SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf().newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ validateDataConsistency(originalData, upgradedMetaClient, "after upgrade");
+
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Successfully completed upgrade test for version {} -> {}", originalVersion, targetVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("downgradeVersions")
+ public void testDowngradeOnly(HoodieTableVersion targetVersion) throws Exception {
Review Comment:
I think it might be good to have these seperate, but I can try to refactor similar setup between the two methods.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3148989368
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* e69e5e414dced40fe6c6aeb3f4e01ca78acca502 Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493)
* 974231b204d4d7ccaff6ddf9f9c1a434983f585c Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149102558
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 974231b204d4d7ccaff6ddf9f9c1a434983f585c Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250483667
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
Review Comment:
Tracking JIRA Here: https://issues.apache.org/jira/browse/HUDI-9684
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
Review Comment:
Tracking JIRA Here: https://issues.apache.org/jira/browse/HUDI-9684
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249472545
##########
hudi-spark-datasource/hudi-spark/src/test/resources/upgrade-downgrade-fixtures/scala-templates/generate-fixture.scala:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+import org.apache.spark.sql.SaveMode
+import org.apache.hudi.DataSourceWriteOptions._
+import spark.implicits._
+
+val tableName = "${TABLE_NAME}"
+val basePath = "${BASE_PATH}"
+
+// Create simple test data with consistent schema
+val testData = Seq(
+ ("id1", "Alice", 1000L, "2023-01-01"),
+ ("id2", "Bob", 2000L, "2023-01-01"),
+ ("id3", "Charlie", 3000L, "2023-01-02"),
+ ("id4", "David", 4000L, "2023-01-02"),
+ ("id5", "Eve", 5000L, "2023-01-03")
+)
+
+val df = testData.toDF("id", "name", "ts", "partition")
+
+// Write initial batch (creates base files)
+df.write.format("hudi").
+ option(PRECOMBINE_FIELD.key, "ts").
+ option(RECORDKEY_FIELD.key, "id").
+ option(PARTITIONPATH_FIELD.key, "partition").
+ option("hoodie.table.name", tableName).
+ option("hoodie.datasource.write.table.type", "MERGE_ON_READ").
+ option("hoodie.datasource.write.operation", "insert").
+ mode(SaveMode.Overwrite).
+ save(basePath)
+
+println("Initial batch written")
+
+// Write update batch (creates log files)
+val updateData = Seq(
+ ("id1", "Alice_Updated", 1001L, "2023-01-01"),
+ ("id2", "Bob_Updated", 2001L, "2023-01-01"),
+ ("id6", "Frank", 6000L, "2023-01-03")
+)
+
+val updateDf = updateData.toDF("id", "name", "ts", "partition")
+
+updateDf.write.format("hudi").
+ option(PRECOMBINE_FIELD.key, "ts").
+ option(RECORDKEY_FIELD.key, "id").
+ option(PARTITIONPATH_FIELD.key, "partition").
+ option("hoodie.table.name", tableName).
+ option("hoodie.datasource.write.table.type", "MERGE_ON_READ").
+ option("hoodie.datasource.write.operation", "upsert").
+ mode(SaveMode.Append).
+ save(basePath)
+
+println("Update batch written")
+
+// Create one more insert to have multiple commits
+val insertData = Seq(
+ ("id7", "Grace", 7000L, "2023-01-04"),
+ ("id8", "Henry", 8000L, "2023-01-04")
+)
+
+val insertDf = insertData.toDF("id", "name", "ts", "partition")
+
+insertDf.write.format("hudi").
+ option(PRECOMBINE_FIELD.key, "ts").
+ option(RECORDKEY_FIELD.key, "id").
+ option(PARTITIONPATH_FIELD.key, "partition").
+ option("hoodie.table.name", tableName).
+ option("hoodie.datasource.write.table.type", "MERGE_ON_READ").
+ option("hoodie.datasource.write.operation", "insert").
+ mode(SaveMode.Append).
+ save(basePath)
+
+println("Additional insert written")
+println(s"Fixture ${FIXTURE_NAME} generated successfully!")
+
+System.exit(0)
Review Comment:
will do so
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250092617
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
Review Comment:
will remove
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2250177728
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing rollback and compaction behavior for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping rollback/compaction test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Count initial timeline state
+ int initialPendingCommits = originalMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ int initialCompletedCommits = originalMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+
+ // Perform upgrade
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate timeline state after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+
+ // Perform data validation after upgrade
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade in rollback/compaction test");
+
+ // Verify rollback behavior - pending commits should be cleaned up or reduced
+ int finalPendingCommits = upgradedMetaClient.getCommitsTimeline().filterPendingExcludingCompaction().countInstants();
+ assertTrue(finalPendingCommits <= initialPendingCommits,
+ "Pending commits should be cleaned up or reduced after upgrade");
+
+ // Verify we still have completed commits
+ int finalCompletedCommits = upgradedMetaClient.getCommitsTimeline().filterCompletedInstants().countInstants();
+ assertTrue(finalCompletedCommits >= initialCompletedCommits,
+ "Completed commits should be preserved or increased after upgrade");
+
+ LOG.info("Rollback and compaction behavior validated for version {}", originalVersion);
+ }
+
+ /**
+ * Load a fixture table from resources and copy it to a temporary location for testing.
+ */
+ private HoodieTableMetaClient loadFixtureTable(HoodieTableVersion version) throws IOException {
+ String fixtureName = getFixtureName(version);
+ String resourcePath = FIXTURES_BASE_PATH + fixtureName;
+
+ // Extract fixture zip from resources to temp directory
+ extractFixtureToTempDir(resourcePath, tempDir.toString());
+
+ // Get the table name from fixture (remove .zip extension)
+ String tableName = fixtureName.replace(".zip", "");
+ String tablePath = tempDir.resolve(tableName).toString();
+
+ // Initialize meta client for the copied fixture
+ metaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(tablePath)
+ .build();
+
+ LOG.info("Loaded fixture table {} at version {}", fixtureName, metaClient.getTableConfig().getTableVersion());
+ return metaClient;
+ }
+
+ /**
+ * Extract fixture zip file from resources to temporary directory.
+ */
+ private void extractFixtureToTempDir(String resourcePath, String tempPath) throws IOException {
+ LOG.info("Loading fixture from resource path: {}", resourcePath);
+
+ try (ZipInputStream zip = new ZipInputStream(getClass().getResourceAsStream(resourcePath))) {
+ if (zip == null) {
+ throw new IOException("Fixture not found at: " + resourcePath);
+ }
+
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ File file = Paths.get(tempPath, entry.getName()).toFile();
+ if (entry.isDirectory()) {
+ file.mkdirs();
+ continue;
+ }
+
+ // Create parent directories if they don't exist
+ file.getParentFile().mkdirs();
+
+ // Extract file content
+ byte[] buffer = new byte[10000];
+ try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
+ int count;
+ while ((count = zip.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Create write config for test operations (upgrade/downgrade/validation).
+ */
+ private HoodieWriteConfig createWriteConfig(HoodieTableMetaClient metaClient, boolean autoUpgrade) {
+ Properties props = new Properties();
+ props.putAll(metaClient.getTableConfig().getProps());
+
+ HoodieWriteConfig.Builder builder = HoodieWriteConfig.newBuilder()
+ .withPath(metaClient.getBasePath().toString())
+ .withAutoUpgradeVersion(autoUpgrade)
+ .withProps(props);
+
+ // Add timeline layout version only if available (needed for upgrade operations)
+ if (metaClient.getTableConfig().getTimelineLayoutVersion().isPresent()) {
+ builder.withTimelineLayoutVersion(metaClient.getTableConfig().getTimelineLayoutVersion().get().getVersion());
+ }
+
+ // For validation operations, keep timeline server disabled for simplicity
+ if (!autoUpgrade) {
+ builder.withEmbeddedTimelineServerEnabled(false);
+ }
+
+ return builder.build();
+ }
+
+ /**
+ * Get the next version up from the current version.
+ */
+ private HoodieTableVersion getNextVersion(HoodieTableVersion current) {
+ switch (current) {
+ case FOUR:
+ return HoodieTableVersion.FIVE;
+ case FIVE:
+ return HoodieTableVersion.SIX;
+ case SIX:
+ // even though there is a table version 7, this is not an official release and serves as a bridge
+ // so the next version should be 8
+ return HoodieTableVersion.EIGHT;
+ case EIGHT:
+ return HoodieTableVersion.NINE;
+ case NINE:
+ return null; // No higher version available
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Get fixture zip file name for a given table version.
+ */
+ private String getFixtureName(HoodieTableVersion version) {
+ switch (version) {
+ case FOUR:
+ return "hudi-v4-table.zip";
+ case FIVE:
+ return "hudi-v5-table.zip";
+ case SIX:
+ return "hudi-v6-table.zip";
+ case EIGHT:
+ return "hudi-v8-table.zip";
+ case NINE:
+ return "hudi-v9-table.zip";
+ default:
+ throw new IllegalArgumentException("Unsupported fixture version: " + version);
+ }
+ }
+
+ /**
+ * Provide test parameters for fixture versions.
+ */
+ private static Stream<Arguments> fixtureVersions() {
+ return Stream.of(
+ Arguments.of(HoodieTableVersion.FOUR), // Hudi 0.11.1
+ Arguments.of(HoodieTableVersion.FIVE), // Hudi 0.12.2
+ Arguments.of(HoodieTableVersion.SIX), // Hudi 0.14
+ Arguments.of(HoodieTableVersion.EIGHT), // Hudi 1.0.2
+ Arguments.of(HoodieTableVersion.NINE) // Hudi 1.1
+ );
+ }
+
+ /**
+ * Assert table version on both data table and metadata table (if exists).
+ * Adapted from TestUpgradeDowngrade.assertTableVersionOnDataAndMetadataTable().
+ */
+ private void assertTableVersionOnDataAndMetadataTable(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertTableVersion(metaClient, expectedVersion);
+
+ if (expectedVersion.versionCode() >= HoodieTableVersion.FOUR.versionCode()) {
+ StoragePath metadataTablePath = HoodieTableMetadata.getMetadataTableBasePath(metaClient.getBasePath());
+ if (metaClient.getStorage().exists(metadataTablePath)) {
+ LOG.info("Verifying metadata table version at: {}", metadataTablePath);
+ HoodieTableMetaClient mdtMetaClient = HoodieTableMetaClient.builder()
+ .setConf(metaClient.getStorageConf().newInstance()).setBasePath(metadataTablePath).build();
+ assertTableVersion(mdtMetaClient, expectedVersion);
+ } else {
+ LOG.info("Metadata table does not exist at: {}", metadataTablePath);
+ }
+ }
+ }
+
+ /**
+ * Assert table version by checking both in-memory config and persisted properties file.
+ * Adapted from TestUpgradeDowngrade.assertTableVersion().
+ */
+ private void assertTableVersion(
+ HoodieTableMetaClient metaClient, HoodieTableVersion expectedVersion) throws IOException {
+ assertEquals(expectedVersion.versionCode(),
+ metaClient.getTableConfig().getTableVersion().versionCode());
+ StoragePath propertyFile = new StoragePath(
+ metaClient.getMetaPath(), HoodieTableConfig.HOODIE_PROPERTIES_FILE);
+ // Load the properties and verify
+ InputStream inputStream = metaClient.getStorage().open(propertyFile);
+ HoodieConfig config = new HoodieConfig();
+ config.getProps().load(inputStream);
+ inputStream.close();
+ assertEquals(Integer.toString(expectedVersion.versionCode()),
+ config.getString(HoodieTableConfig.VERSION));
+ }
+
+ /**
+ * Validate version-specific properties after upgrade/downgrade operations.
+ */
+ private void validateVersionSpecificProperties(
+ HoodieTableMetaClient metaClient, HoodieTableVersion fromVersion, HoodieTableVersion toVersion) throws IOException {
+ LOG.info("Validating version-specific properties: {} -> {}", fromVersion, toVersion);
+
+ HoodieTableConfig tableConfig = metaClient.getTableConfig();
+
+ // Validate properties for target version
+ switch (toVersion) {
+ case FOUR:
+ validateVersion4Properties(tableConfig);
+ break;
+ case FIVE:
+ validateVersion5Properties(tableConfig);
+ break;
+ case SIX:
+ validateVersion6Properties(tableConfig);
+ break;
+ case EIGHT:
+ validateVersion8Properties(tableConfig);
+ break;
+ case NINE:
+ validateVersion9Properties(metaClient, tableConfig);
+ break;
+ default:
+ LOG.warn("No specific property validation for version {}", toVersion);
+ }
+
+ // Validate upgrade/downgrade specific changes
+ if (fromVersion.versionCode() < toVersion.versionCode()) {
+ validateUpgradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ } else if (fromVersion.versionCode() > toVersion.versionCode()) {
+ validateDowngradeProperties(fromVersion, toVersion, metaClient, tableConfig);
+ }
+ }
+
+ /**
+ * Validate basic properties for version 4.
+ */
+ private void validateVersion4Properties(HoodieTableConfig tableConfig) {
+ // Basic table properties should exist
+ assertNotNull(tableConfig.getTableName(), "Table name should be set");
+ assertEquals(HoodieTableType.MERGE_ON_READ, tableConfig.getTableType(), "Table should be MOR type");
+ assertTrue(tableConfig.getRecordKeyFieldProp() != null && !tableConfig.getRecordKeyFieldProp().isEmpty(),
+ "Record key field should be set");
+ assertTrue(tableConfig.getPartitionFieldProp() != null && !tableConfig.getPartitionFieldProp().isEmpty(),
+ "Partition field should be set");
+ }
+
+ /**
+ * Validate properties for version 5 (default partition path changes).
+ */
+ private void validateVersion5Properties(HoodieTableConfig tableConfig) {
+ validateVersion4Properties(tableConfig);
+ // Version 5 mainly focuses on default partition path validation
+ // The upgrade handler validates this during upgrade, so we just ensure basic properties
+ }
+
+ /**
+ * Validate properties for version 6 (auxiliary folder cleanup).
+ */
+ private void validateVersion6Properties(HoodieTableConfig tableConfig) {
+ validateVersion5Properties(tableConfig);
+ // Version 6 focuses on auxiliary folder cleanup
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+ }
+
+ /**
+ * Validate properties for version 8 (major upgrade with record merge mode, new configuration properties).
+ */
+ private void validateVersion8Properties(HoodieTableConfig tableConfig) {
+ validateVersion6Properties(tableConfig);
+
+ // Note: Timeline layout validation moved to transition methods since it changes during upgrades
+
+ // Timeline path should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be set for V8");
+ assertEquals(HoodieTableConfig.TIMELINE_PATH.defaultValue(),
+ tableConfig.getString(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should have default value");
+
+ // Record merge mode should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be set for V8");
+ RecordMergeMode mergeMode = tableConfig.getRecordMergeMode();
+ assertNotNull(mergeMode, "Merge mode should not be null");
+
+ // Record merge strategy ID should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be set for V8");
+
+ // Payload class should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.PAYLOAD_CLASS_NAME),
+ "Payload class should be set for V8");
+
+ // Initial version should be set
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be set for V8");
+
+ // Key generator type should be set if key generator class is present
+ if (tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_CLASS_NAME)) {
+ assertTrue(tableConfig.contains(HoodieTableConfig.KEY_GENERATOR_TYPE),
+ "Key generator type should be set when key generator class is present");
+ }
+ }
+
+ /**
+ * Validate properties for version 9 (index version population).
+ */
+ private void validateVersion9Properties(HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ validateVersion8Properties(tableConfig);
+
+ // Check if index metadata exists and has proper version information
+ Option<HoodieIndexMetadata> indexMetadata = metaClient.getIndexMetadata();
+ if (indexMetadata.isPresent()) {
+ indexMetadata.get().getIndexDefinitions().forEach((indexName, indexDef) -> {
+ assertNotNull(indexDef.getVersion(),
+ "Index " + indexName + " should have version information in V9");
+ });
+ }
+ }
+
+ /**
+ * Validate properties added during upgrade operations.
+ */
+ private void validateUpgradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating upgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Validate timeline layout changes during upgrades
+ if (fromVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()) {
+ // Timeline layout should change from V1 to V2 during upgrade to V8+
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ assertTrue(layoutVersion.isPresent(), "Timeline layout version should be present after upgrade to V8+");
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_2, layoutVersion.get(),
+ "Timeline layout should be upgraded to V2 during upgrade to V8+");
+
+ // These properties should be added during upgrade to V8+
+ assertTrue(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH),
+ "Timeline path should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_MODE),
+ "Record merge mode should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
+ "Record merge strategy ID should be added during upgrade to V8+");
+ assertTrue(tableConfig.contains(HoodieTableConfig.INITIAL_VERSION),
+ "Initial version should be added during upgrade to V8+");
+ }
+ }
+
+ /**
+ * Validate properties removed/changed during downgrade operations.
+ */
+ private void validateDowngradeProperties(HoodieTableVersion fromVersion, HoodieTableVersion toVersion,
+ HoodieTableMetaClient metaClient, HoodieTableConfig tableConfig) {
+ LOG.debug("Validating downgrade properties: {} -> {}", fromVersion, toVersion);
+
+ // Downgrading from V8+ to pre-V8 should remove certain properties
+ if (fromVersion.versionCode() >= HoodieTableVersion.EIGHT.versionCode()
+ && toVersion.versionCode() < HoodieTableVersion.EIGHT.versionCode()) {
+ // These V8+ properties should be removed or modified during downgrade
+ assertFalse(tableConfig.contains(HoodieTableConfig.TIMELINE_PATH)
+ && !HoodieTableConfig.TIMELINE_PATH.defaultValue().equals(tableConfig.getString(HoodieTableConfig.TIMELINE_PATH)),
+ "Timeline path should be reset during downgrade from V8+");
+
+ // Timeline layout should be downgraded to V1
+ Option<TimelineLayoutVersion> layoutVersion = tableConfig.getTimelineLayoutVersion();
+ if (layoutVersion.isPresent()) {
+ assertEquals(TimelineLayoutVersion.LAYOUT_VERSION_1, layoutVersion.get(),
+ "Timeline layout should be downgraded to V1");
+ }
+ }
+ }
+
+ /**
+ * Perform data validation on the table to ensure it remains operational.
+ * This performs a simple read-only validation to verify table accessibility.
+ */
+ private void performDataValidationOnTable(HoodieTableMetaClient metaClient, String stage) {
+ LOG.info("Performing data validation on table {}", stage);
+
+ try {
+ // Simple read validation to ensure table is accessible
+ long rowCount = performSimpleReadValidation(metaClient);
+ LOG.debug("Read {} rows from table {}", rowCount, stage);
+
+ // Verify table metadata is accessible
+ assertNotNull(metaClient.getTableConfig(), "Table config should be accessible " + stage);
+ assertNotNull(metaClient.getTableConfig().getTableName(), "Table name should be accessible " + stage);
+
+ LOG.info("✓ Data validation passed {} (table accessible, {} rows)", stage, rowCount);
+ } catch (Exception e) {
+ throw new RuntimeException("Data validation failed " + stage, e);
+ }
+ }
+
+ /**
+ * Perform simple read validation and return the total row count.
+ */
+ private long performSimpleReadValidation(HoodieTableMetaClient metaClient) {
+ LOG.debug("Performing read validation on table at: {}", metaClient.getBasePath());
+ try {
+ // Log table information for debugging
+ String basePath = metaClient.getBasePath().toString();
+ LOG.debug("Table base path: {}", basePath);
+ LOG.debug("Table version: {}", metaClient.getTableConfig().getTableVersion());
+ LOG.debug("Table type: {}", metaClient.getTableConfig().getTableType());
+
+ // Read entire table using Spark's built-in Hudi support
+ LOG.debug("Attempting to read table using Spark SQL...");
+ Dataset<Row> tableData = sqlContext.read()
+ .format("hudi")
+ .load(basePath);
+
+ // Validate read operation succeeded
+ assertNotNull(tableData, "Table read should not return null");
+ LOG.debug("Table read operation succeeded");
+
+ // Count rows
+ LOG.debug("Counting rows...");
+ long rowCount = tableData.count();
+ assertTrue(rowCount >= 0, "Row count should be non-negative");
+
+ LOG.debug("Successfully read {} rows from table", rowCount);
Review Comment:
will remove
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3149325567
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7455",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
}, {
"hash" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7457",
"triggerID" : "fe58d1cccda2993538fbc1fbd7e6cc8197a160d8",
"triggerType" : "PUSH"
}, {
"hash" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7459",
"triggerID" : "bf1cd628b1f12ec551cede386e12ea4ac8f602ff",
"triggerType" : "PUSH"
}, {
"hash" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7469",
"triggerID" : "e80123ac7fc2dfb3b5773fceb0b8d2919ba3dbd8",
"triggerType" : "PUSH"
}, {
"hash" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"status" : "DELETED",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7493",
"triggerID" : "e69e5e414dced40fe6c6aeb3f4e01ca78acca502",
"triggerType" : "PUSH"
}, {
"hash" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500",
"triggerID" : "974231b204d4d7ccaff6ddf9f9c1a434983f585c",
"triggerType" : "PUSH"
}, {
"hash" : "4682338fa47785195286281dec5303c00eaa86c7",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509",
"triggerID" : "4682338fa47785195286281dec5303c00eaa86c7",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 974231b204d4d7ccaff6ddf9f9c1a434983f585c Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7500)
* 4682338fa47785195286281dec5303c00eaa86c7 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7509)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #13669:
URL: https://github.com/apache/hudi/pull/13669#issuecomment-3145950956
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454",
"triggerID" : "a95f25079f6dd0d1199d5d66a7340bfdddce6325",
"triggerType" : "PUSH"
}, {
"hash" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "72c416095c9078a3d7b9e28f7a72c55ceaf0b14e",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* a95f25079f6dd0d1199d5d66a7340bfdddce6325 Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=7454)
* 72c416095c9078a3d7b9e28f7a72c55ceaf0b14e UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot run azure` re-run the last Azure build
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Initial Test Fixture Framework For Upgrade/Downgrade [hudi]
Posted by "rahil-c (via GitHub)" <gi...@apache.org>.
rahil-c commented on code in PR #13669:
URL: https://github.com/apache/hudi/pull/13669#discussion_r2249495720
##########
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/upgrade/TestUpgradeDowngradeFixtures.java:
##########
@@ -0,0 +1,633 @@
+/*
+ * 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.config.HoodieConfig;
+import org.apache.hudi.common.config.RecordMergeMode;
+import org.apache.hudi.common.model.HoodieIndexMetadata;
+import org.apache.hudi.common.model.HoodieTableType;
+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.common.table.timeline.versioning.TimelineLayoutVersion;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.storage.StoragePath;
+import org.apache.hudi.testutils.HoodieSparkClientTestHarness;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Properties;
+import java.util.stream.Stream;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+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.assertTrue;
+
+/**
+ * Test class for upgrade/downgrade operations using pre-created fixture tables
+ * from different Hudi releases. Tests round-trip operations: upgrade one version up,
+ * then downgrade back to original version.
+ */
+public class TestUpgradeDowngradeFixtures extends HoodieSparkClientTestHarness {
+
+ private static final Logger LOG = LoggerFactory.getLogger(TestUpgradeDowngradeFixtures.class);
+ private static final String FIXTURES_BASE_PATH = "/upgrade-downgrade-fixtures/mor-tables/";
+
+ @TempDir
+ java.nio.file.Path tempDir;
+
+ private HoodieTableMetaClient metaClient;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ initSparkContexts();
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ cleanupSparkContexts();
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRoundTripUpgradeDowngrade(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing round-trip upgrade/downgrade for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+ assertEquals(originalVersion, originalMetaClient.getTableConfig().getTableVersion(),
+ "Fixture table should be at expected version");
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config for upgrade operations
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, true);
+
+ // Step 1: Upgrade to next version
+ LOG.info("Step 1: Upgrading from {} to {}", originalVersion, targetVersion);
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to read updated table configuration after upgrade
+ HoodieTableMetaClient upgradedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(upgradedMetaClient, targetVersion);
+ validateVersionSpecificProperties(upgradedMetaClient, originalVersion, targetVersion);
+ performDataValidationOnTable(upgradedMetaClient, "after upgrade");
+
+ // Step 2: Downgrade back to original version
+ LOG.info("Step 2: Downgrading from {} back to {}", targetVersion, originalVersion);
+ new UpgradeDowngrade(upgradedMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(originalVersion, null);
+
+ // Create fresh meta client to read updated table configuration after downgrade
+ HoodieTableMetaClient finalMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(upgradedMetaClient.getBasePath())
+ .build();
+ assertTableVersionOnDataAndMetadataTable(finalMetaClient, originalVersion);
+ validateVersionSpecificProperties(finalMetaClient, targetVersion, originalVersion);
+ performDataValidationOnTable(finalMetaClient, "after round-trip");
+
+ LOG.info("Successfully completed round-trip test for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testAutoUpgradeDisabled(HoodieTableVersion originalVersion) throws Exception {
+ LOG.info("Testing auto-upgrade disabled for version {}", originalVersion);
+
+ // Load fixture table
+ HoodieTableMetaClient originalMetaClient = loadFixtureTable(originalVersion);
+
+ // Calculate target version (next version up)
+ HoodieTableVersion targetVersion = getNextVersion(originalVersion);
+ if (targetVersion == null) {
+ LOG.info("Skipping auto-upgrade test for version {} (no higher version available)", originalVersion);
+ return;
+ }
+
+ // Create write config with auto-upgrade disabled
+ HoodieWriteConfig config = createWriteConfig(originalMetaClient, false);
+
+ // Attempt upgrade with auto-upgrade disabled
+ new UpgradeDowngrade(originalMetaClient, config, context, SparkUpgradeDowngradeHelper.getInstance())
+ .run(targetVersion, null);
+
+ // Create fresh meta client to validate that version remained unchanged
+ HoodieTableMetaClient unchangedMetaClient = HoodieTableMetaClient.builder()
+ .setConf(storageConf.newInstance())
+ .setBasePath(originalMetaClient.getBasePath())
+ .build();
+ assertEquals(originalVersion, unchangedMetaClient.getTableConfig().getTableVersion(),
+ "Table version should remain unchanged when auto-upgrade is disabled");
+ performDataValidationOnTable(unchangedMetaClient, "after auto-upgrade disabled test");
+
+ LOG.info("Auto-upgrade disabled test passed for version {}", originalVersion);
+ }
+
+ @ParameterizedTest
+ @MethodSource("fixtureVersions")
+ public void testRollbackAndCompactionBehavior(HoodieTableVersion originalVersion) throws Exception {
Review Comment:
I think you are right that we probably need to have the rollbackAndCompact logic be verified within the upgrade or downgrade tests, rather than having this be a separate test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org