This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/master/pr-19927-9207ad3a2e80a43495be6c16b0efe95fc60b0e65 in repository https://gitbox.apache.org/repos/asf/hudi.git
commit 8dafd38a7d7f350aefada3e8f40ef32ffaf441a5 Author: voonhous <[email protected]> AuthorDate: Tue Nov 24 04:09:53 2026 +0000 test(spark): scope JVM state for concurrent SQL suites (#19927) * test(spark): scope JVM state for concurrent SQL suites Prepares HoodieSparkSqlTestBase suites for running concurrently in one JVM: - Literal table and database names in the SQL suites come from generateTableName, which is unique per suite; path assertions that embedded a literal build from the same value. - HoodieInMemoryHashIndex keeps one map per table (base path) and can clear a single table; the base clears globally only in per-suite mode and per table on drop in shared mode. - ExclusiveSuite marks suites that mutate JVM-wide state (shared Hadoop conf, persisted RDDs, metrics registry, Hudi's global properties). Every suite holds the read side of a fair read/write lock for its whole run; an exclusive suite holds the write side. No effect until suites run in parallel. - TestInsertTable4 scopes its stage listener to the jobs the test started, through a local property, and removes it in a finally. - TestRepairsProcedure no longer closes the JVM-cached FileSystem. Supersedes the proof of concept in #19923. * test(spark): scope TestDropTable show tables The eight catalog-wide `show tables` assertions saw the tables of suites running at the same time on the shared SparkContext. They now list `show tables like '<prefix>*'`, where the prefix is the one generateTableName uses for this suite, so the expected rows are unchanged and other suites' tables are ignored. * test(spark): keep derived table names with their suite and mark two more suites exclusive A name built from a generated one, such as `${tableName}_ro` or `${generateTableName}_timestamp_type`, did not fully match the generated pattern, so in shared mode every suite treated it as its own and dropped it. Match the pattern as a prefix instead. The metadata index lookup suites unpersist every RDD on the shared context and assert none are persisted, and TestHiveSyncProcedure sets hive.metastore.uris on the shared Hadoop conf. Make both exclusive. * test(spark): clear a single table's in-memory index entry by StoragePath * test(spark): key the in-memory index by scheme, authority and path tableKey kept only the path, so two tables at the same path in different buckets shared one location map. Keep scheme and authority, taking a scheme-less path as local so /tmp/t and file:/tmp/t still match, and have the catalog cleanup pass the location URI instead of its path. Also correct the TestInsertTable4 listener comment: Hudi overwrites the job description on its own jobs, not the job group id. --- .../apache/hudi/index/HoodieInMemoryHashIndex.java | 55 +++++++--- .../hudi/index/TestHoodieInMemoryHashIndex.java | 46 ++++++++ .../TestSparkSqlWithTimestampKeyGenerator.scala | 18 ++-- .../hudi/command/TestHoodieCommandMetrics.scala | 4 +- .../spark/sql/hudi/common/ExclusiveSuite.scala | 41 ++++++++ .../sql/hudi/common/HoodieSparkSqlTestBase.scala | 77 ++++++++++++-- .../apache/spark/sql/hudi/common/TestSqlConf.scala | 6 +- .../spark/sql/hudi/ddl/TestCreateTable.scala | 41 +++++--- .../apache/spark/sql/hudi/ddl/TestDropTable.scala | 20 ++-- .../apache/spark/sql/hudi/ddl/TestSpark3DDL.scala | 5 +- .../spark/sql/hudi/ddl/TestSparkCatalogSync.scala | 6 +- .../sql/hudi/dml/insert/TestInsertTable4.scala | 37 +++++-- .../sql/hudi/dml/schema/TestBlobDataType.scala | 117 ++++++++++++++------- .../sql/hudi/feature/TestCDCForSparkSQL.scala | 8 +- .../hudi/feature/index/TestExpressionIndex.scala | 4 +- .../TestHoodieBackedTableMetadataIndexLookup.scala | 4 +- .../hudi/feature/index/TestSecondaryIndex.scala | 4 +- .../TestClusteringBinaryCopyStrategy.scala | 3 +- .../sql/hudi/procedure/TestHiveSyncProcedure.scala | 3 +- .../sql/hudi/procedure/TestRepairsProcedure.scala | 1 - 20 files changed, 376 insertions(+), 124 deletions(-) diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieInMemoryHashIndex.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieInMemoryHashIndex.java index be2dca333e98..45b108131c9e 100644 --- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieInMemoryHashIndex.java +++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/index/HoodieInMemoryHashIndex.java @@ -30,8 +30,10 @@ import org.apache.hudi.common.table.timeline.HoodieTimeline; import org.apache.hudi.common.util.Option; import org.apache.hudi.common.util.VisibleForTesting; import org.apache.hudi.config.HoodieWriteConfig; +import org.apache.hudi.storage.StoragePath; import org.apache.hudi.table.HoodieTable; +import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; @@ -40,32 +42,51 @@ import java.util.concurrent.ConcurrentMap; /** * Hoodie Index implementation backed by an in-memory Hash map. * <p> + * Record locations are kept per table (keyed by base path) so that tables written in the same JVM + * do not see each other's keys. The commit-time check in tagLocation only rejects locations whose + * instant is missing from the current timeline; an entry left by an earlier table at the same base + * path is accepted, so a caller that re-creates a table at a path it used before must call + * clear(basePath) first. + * <p> * ONLY USE FOR LOCAL TESTING */ public class HoodieInMemoryHashIndex extends HoodieIndex<Object, Object> { - private static ConcurrentMap<HoodieKey, HoodieRecordLocation> recordLocationMap; + private static final ConcurrentMap<String, ConcurrentMap<HoodieKey, HoodieRecordLocation>> RECORD_LOCATIONS_PER_TABLE = + new ConcurrentHashMap<>(); public HoodieInMemoryHashIndex(HoodieWriteConfig config) { super(config); - synchronized (HoodieInMemoryHashIndex.class) { - if (recordLocationMap == null) { - recordLocationMap = new ConcurrentHashMap<>(); - } - } + } + + /** + * Keys a table by scheme, authority and path, with a scheme-less path taken as local, so {@code /tmp/t} and + * {@code file:/tmp/t} name one table while {@code s3a://bucket-a/t} and {@code s3a://bucket-b/t} do not. + */ + @VisibleForTesting + static String tableKey(StoragePath basePath) { + URI uri = basePath.toUri(); + String scheme = uri.getScheme() == null ? "file" : uri.getScheme(); + String authority = uri.getAuthority() == null ? "" : uri.getAuthority(); + return scheme + "://" + authority + uri.getPath(); + } + + private static ConcurrentMap<HoodieKey, HoodieRecordLocation> locationsOf(String tableKey) { + return RECORD_LOCATIONS_PER_TABLE.computeIfAbsent(tableKey, k -> new ConcurrentHashMap<>()); } @Override public <R> HoodieData<HoodieRecord<R>> tagLocation( HoodieData<HoodieRecord<R>> records, HoodieEngineContext context, HoodieTable hoodieTable) { + String key = tableKey(hoodieTable.getMetaClient().getBasePath()); return records.mapPartitions(hoodieRecordIterator -> { List<HoodieRecord<R>> taggedRecords = new ArrayList<>(); HoodieTimeline commitsTimeline = hoodieTable.getMetaClient().getCommitsTimeline().filterCompletedInstants(); while (hoodieRecordIterator.hasNext()) { HoodieRecord<R> record = hoodieRecordIterator.next(); - HoodieRecordLocation location = recordLocationMap.get(record.getKey()); + HoodieRecordLocation location = locationsOf(key).get(record.getKey()); if ((location != null) && HoodieIndexUtils.checkIfValidCommit(commitsTimeline, location.getInstantTime())) { record.unseal(); record.setCurrentLocation(location); @@ -81,15 +102,16 @@ public class HoodieInMemoryHashIndex public HoodieData<WriteStatus> updateLocation( HoodieData<WriteStatus> writeStatuses, HoodieEngineContext context, HoodieTable hoodieTable) { + String key = tableKey(hoodieTable.getMetaClient().getBasePath()); return writeStatuses.map(writeStatus -> { for (HoodieRecordDelegate recordDelegate : writeStatus.getIndexStats().getWrittenRecordDelegates()) { if (!writeStatus.isErrored(recordDelegate.getHoodieKey())) { Option<HoodieRecordLocation> newLocation = recordDelegate.getNewLocation(); if (newLocation.isPresent()) { - recordLocationMap.put(recordDelegate.getHoodieKey(), newLocation.get()); + locationsOf(key).put(recordDelegate.getHoodieKey(), newLocation.get()); } else { // Delete existing index for a deleted record - recordLocationMap.remove(recordDelegate.getHoodieKey()); + locationsOf(key).remove(recordDelegate.getHoodieKey()); } } } @@ -126,10 +148,19 @@ public class HoodieInMemoryHashIndex return false; } + /** + * Clears the locations of every table in this JVM. + */ @VisibleForTesting public static void clear() { - if (recordLocationMap != null) { - recordLocationMap.clear(); - } + RECORD_LOCATIONS_PER_TABLE.clear(); + } + + /** + * Clears the locations of a single table. + */ + @VisibleForTesting + public static void clear(StoragePath basePath) { + RECORD_LOCATIONS_PER_TABLE.remove(tableKey(basePath)); } } diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/index/TestHoodieInMemoryHashIndex.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/index/TestHoodieInMemoryHashIndex.java new file mode 100644 index 000000000000..7fc8c0f48208 --- /dev/null +++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/index/TestHoodieInMemoryHashIndex.java @@ -0,0 +1,46 @@ +/* + * 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.index; + +import org.apache.hudi.storage.StoragePath; + +import org.junit.jupiter.api.Test; + +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class TestHoodieInMemoryHashIndex { + + @Test + void testTableKeyTreatsSchemeLessPathAsLocal() { + String expected = HoodieInMemoryHashIndex.tableKey(new StoragePath("file:/tmp/t")); + assertEquals(expected, HoodieInMemoryHashIndex.tableKey(new StoragePath("/tmp/t"))); + assertEquals(expected, HoodieInMemoryHashIndex.tableKey(new StoragePath(URI.create("file:///tmp/t")))); + } + + @Test + void testTableKeyKeepsSchemeAndAuthority() { + assertNotEquals(HoodieInMemoryHashIndex.tableKey(new StoragePath("s3a://bucket-a/t")), + HoodieInMemoryHashIndex.tableKey(new StoragePath("s3a://bucket-b/t"))); + assertNotEquals(HoodieInMemoryHashIndex.tableKey(new StoragePath("s3a://bucket-a/t")), + HoodieInMemoryHashIndex.tableKey(new StoragePath("/t"))); + } +} diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithTimestampKeyGenerator.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithTimestampKeyGenerator.scala index 2ba74abbf8b4..255d19be1536 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithTimestampKeyGenerator.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithTimestampKeyGenerator.scala @@ -90,15 +90,16 @@ class TestSparkSqlWithTimestampKeyGenerator extends HoodieSparkSqlTestBase { withTempDir { tmp => val keyGeneratorSettings = timestampKeyGeneratorSettings(3) val tsType = if (keyGeneratorSettings.contains("DATE_STRING")) "string" else "long" + val tableName = generateTableName spark.sql( s""" - | CREATE TABLE test_default_path_ts ( + | CREATE TABLE $tableName ( | id int, | name string, | precomb long, | ts TIMESTAMP | ) USING HUDI - | LOCATION '${tmp.getCanonicalPath + "/test_default_path_ts"}' + | LOCATION '${tmp.getCanonicalPath + "/" + tableName}' | PARTITIONED BY (ts) | TBLPROPERTIES ( | type = 'COPY_ON_WRITE', @@ -111,11 +112,11 @@ class TestSparkSqlWithTimestampKeyGenerator extends HoodieSparkSqlTestBase { "(2, 'a3', 1, null)" ) val expectedQueryResult: String = "[1,a1,1,2025-01-15 01:02:03.0]; [2,a3,1,null]" - spark.sql(s"INSERT INTO test_default_path_ts VALUES ${dataBatches(0)}") + spark.sql(s"INSERT INTO $tableName VALUES ${dataBatches(0)}") // inserting value with partition_timestamp value as null - spark.sql(s"INSERT INTO test_default_path_ts VALUES ${dataBatches(1)}") + spark.sql(s"INSERT INTO $tableName VALUES ${dataBatches(1)}") - val queryResult = spark.sql(s"SELECT id, name, precomb, ts FROM test_default_path_ts ORDER BY id").collect().mkString("; ") + val queryResult = spark.sql(s"SELECT id, name, precomb, ts FROM $tableName ORDER BY id").collect().mkString("; ") LOG.warn(s"Query result: $queryResult") assertResult(expectedQueryResult)(queryResult) @@ -124,15 +125,16 @@ class TestSparkSqlWithTimestampKeyGenerator extends HoodieSparkSqlTestBase { test("Test mandatory partitioning for timestamp key generator") { withTempDir { tmp => + val tableName = generateTableName spark.sql( s""" - | CREATE TABLE should_fail ( + | CREATE TABLE $tableName ( | id int, | name string, | precomb long, | ts long | ) USING HUDI - | LOCATION '${tmp.getCanonicalPath + "/should_fail"}' + | LOCATION '${tmp.getCanonicalPath + "/" + tableName}' | TBLPROPERTIES ( | type = 'COPY_ON_WRITE', | primaryKey = 'id', @@ -143,7 +145,7 @@ class TestSparkSqlWithTimestampKeyGenerator extends HoodieSparkSqlTestBase { |""".stripMargin) // should fail due to absent partitioning assertThrows[HoodieException] { - spark.sql(s"INSERT INTO should_fail VALUES ${dataBatchesWithLongOfSeconds(0)}") + spark.sql(s"INSERT INTO $tableName VALUES ${dataBatchesWithLongOfSeconds(0)}") } } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/command/TestHoodieCommandMetrics.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/command/TestHoodieCommandMetrics.scala index 6e8144039fbe..57400550ae14 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/command/TestHoodieCommandMetrics.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/command/TestHoodieCommandMetrics.scala @@ -19,10 +19,10 @@ package org.apache.spark.sql.hudi.command import org.apache.hudi.common.model.HoodieCommitMetadata -import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase +import org.apache.spark.sql.hudi.common.{ExclusiveSuite, HoodieSparkSqlTestBase} import org.mockito.Mockito.{mock, when} -class TestHoodieCommandMetrics extends HoodieSparkSqlTestBase { +class TestHoodieCommandMetrics extends HoodieSparkSqlTestBase with ExclusiveSuite { override def beforeAll(): Unit = { spark.sparkContext diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/ExclusiveSuite.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/ExclusiveSuite.scala new file mode 100644 index 000000000000..821cdf32f4d2 --- /dev/null +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/ExclusiveSuite.scala @@ -0,0 +1,41 @@ +/* + * 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.spark.sql.hudi.common + +import org.scalatest.{Args, Status} + +/** + * Marks a suite that must not run at the same time as any other suite in the JVM because it + * mutates JVM-wide state (the shared Hadoop conf, persisted RDDs of the shared context, a + * static metrics registry). Takes the write side of [[HoodieSparkSqlTestBase.suiteLock]] for + * its whole run; every other suite holds the read side for its whole run. An exclusive suite + * therefore waits for the suites already running to finish, not just for their current test. No + * effect until suites run concurrently. + */ +trait ExclusiveSuite extends HoodieSparkSqlTestBase { + + abstract override def run(testName: Option[String], args: Args): Status = { + val lock = HoodieSparkSqlTestBase.suiteLock.writeLock() + lock.lock() + try { + super.run(testName, args) + } finally { + lock.unlock() + } + } +} diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/HoodieSparkSqlTestBase.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/HoodieSparkSqlTestBase.scala index 05b1a72a0e77..8b4b6eb3bfd8 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/HoodieSparkSqlTestBase.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/HoodieSparkSqlTestBase.scala @@ -49,15 +49,18 @@ import org.apache.spark.util.Utils import org.joda.time.DateTimeZone import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertTrue} import org.scalactic.source -import org.scalatest.{BeforeAndAfterAll, FunSuite, Tag} +import org.scalatest.{Args, BeforeAndAfterAll, FunSuite, Status, Tag} import org.scalatest.Assertions.assertResult import org.slf4j.LoggerFactory import java.io.File import java.util.{Collections, Optional, TimeZone} import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.locks.ReentrantReadWriteLock import java.util.regex.Pattern +import scala.util.Try + class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { org.apache.log4j.Logger.getRootLogger.setLevel(org.apache.log4j.Level.WARN) private val LOG = LoggerFactory.getLogger(getClass) @@ -167,8 +170,23 @@ class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { new File(sparkWareHouse, tableName).getCanonicalPath } + /** + * Holds the read side of [[HoodieSparkSqlTestBase.suiteLock]] for the whole suite, beforeAll and afterAll + * included, so an [[ExclusiveSuite]] never overlaps any part of another suite. ExclusiveSuite takes the + * write side around this method; ReentrantReadWriteLock lets a writer also acquire the read side. + */ + override def run(testName: Option[String], args: Args): Status = { + val readLock = HoodieSparkSqlTestBase.suiteLock.readLock() + readLock.lock() + try { + super.run(testName, args) + } finally { + readLock.unlock() + } + } + override protected def test(testName: String, testTags: Tag*)(testFun: => Any /* Assertion */)(implicit pos: source.Position): Unit = { - super.test(testName, testTags: _*)( + super.test(testName, testTags: _*)({ try { if (sharedSessionEnabled) { bindSuiteSession() @@ -179,11 +197,26 @@ class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { // stale keys from an earlier test cannot misroute writes in a later one. withRecordType // clears it between record-type iterations, but only on success and only for tests that use // it, so a throwing or non-withRecordType INMEMORY test would otherwise leak state here. - // Runs before the catalog cleanup so it holds even if a drop throws. - HoodieInMemoryHashIndex.clear() + // Runs before the catalog cleanup so it holds even if a drop throws. In shared mode this is + // a no-op, see clearInMemoryIndex. + clearInMemoryIndex() dropSuiteTables() } - ) + }) + } + + /** + * Per-suite mode: reset the JVM-static INMEMORY index between tests (see the note in test()). + * Shared mode: the index is keyed per table and dropSuiteTables clears each dropped table's + * entry, so a global clear would only wipe other suites' tables. A test that drops and re-creates + * a table at the same path inside one test must clear that path itself + * (HoodieInMemoryHashIndex.clear(basePath)); tagLocation's commit-time check accepts entries from + * an earlier table at the same path. + */ + protected def clearInMemoryIndex(): Unit = { + if (!sharedSessionEnabled) { + HoodieInMemoryHashIndex.clear() + } } /** @@ -213,7 +246,14 @@ class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { catalog.listDatabases().foreach { db => val tables = catalog.listTables(db) val toDrop = if (sharedSessionEnabled) tables.filter(table => ownsTable(table.table)) else tables - toDrop.foreach(table => catalog.dropTable(table, true, true)) + toDrop.foreach { table => + if (sharedSessionEnabled && !catalog.isTempView(table)) { + // Shared mode keeps one index map per table; drop this table's entry with the table. + Try(new StoragePath(catalog.getTableMetadata(table).location)) + .foreach(path => HoodieInMemoryHashIndex.clear(path)) + } + catalog.dropTable(table, true, true) + } } if (sharedSessionEnabled) { // Global temp views live in the shared state, outside listDatabases, and would otherwise outlive the suite. @@ -223,12 +263,16 @@ class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { } } - /** Shared mode: a table is this suite's if generateTableName produced it, or if no suite's generateTableName could have. */ + /** + * Shared mode: a table is this suite's if its name starts with this suite's prefix, or if it does not start with + * any suite's generated name. A prefix match, not a full one, so a name built from a generated one + * (`${tableName}_ro`, `${generateTableName}_timestamp_type`) stays with the suite that generated it. + */ private def ownsTable(name: String): Boolean = { - name.startsWith(tableNamePrefix) || !HoodieSparkSqlTestBase.GENERATED_TABLE_NAME.matcher(name).matches() + name.startsWith(tableNamePrefix) || !HoodieSparkSqlTestBase.GENERATED_TABLE_NAME.matcher(name).lookingAt() } - private lazy val tableNamePrefix: String = s"h${getClass.getSimpleName.toLowerCase}_" + protected lazy val tableNamePrefix: String = s"h${getClass.getSimpleName.toLowerCase}_" protected def generateTableName: String = { s"$tableNamePrefix${tableId.incrementAndGet()}" @@ -468,6 +512,14 @@ class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { try { f(tableName) } finally { + if (sharedSessionEnabled) { + val catalog = spark.sessionState.catalog + val ident = spark.sessionState.sqlParser.parseTableIdentifier(tableName) + if (catalog.tableExists(ident) && !catalog.isTempView(ident)) { + Try(new StoragePath(catalog.getTableMetadata(ident).location)) + .foreach(path => HoodieInMemoryHashIndex.clear(path)) + } + } spark.sql(s"drop table if exists $tableName purge") } } @@ -507,7 +559,7 @@ class HoodieSparkSqlTestBase extends FunSuite with BeforeAndAfterAll { withSQLConf(config.toList: _*) { f // We need to clear indexed location in memory after each test. - HoodieInMemoryHashIndex.clear() + clearInMemoryIndex() } } } @@ -543,7 +595,10 @@ object HoodieSparkSqlTestBase { val SHARED_SESSION_PROPERTY = "hudi.spark.test.sharedSession" val sharedSessionEnabled: Boolean = java.lang.Boolean.getBoolean(SHARED_SESSION_PROPERTY) - // Table names produced by generateTableName (without a database prefix). + // Read side held by every suite for its whole run, write side by an ExclusiveSuite for its whole run. + val suiteLock = new ReentrantReadWriteLock(true) + + // Table names produced by generateTableName (without a database prefix); names built from one start with it. private[common] val GENERATED_TABLE_NAME: Pattern = Pattern.compile("h[a-z0-9]+_[0-9]+") private[common] lazy val sharedWarehouse: File = { diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/TestSqlConf.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/TestSqlConf.scala index 8a17b4a83db9..82170ce6cbe1 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/TestSqlConf.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/common/TestSqlConf.scala @@ -31,7 +31,8 @@ import org.scalatest.BeforeAndAfter import java.io.File import java.nio.file.{Files, Paths} -class TestSqlConf extends HoodieSparkSqlTestBase with BeforeAndAfter { +// Exclusive: sets HUDI_CONF_DIR and Hudi's JVM-wide global properties, which a concurrent suite would read. +class TestSqlConf extends HoodieSparkSqlTestBase with BeforeAndAfter with ExclusiveSuite { // The backing mutable map field name inside java.util.Collections$unmodifiableMap, // used to modify JVM environment variables at runtime via reflection @@ -158,5 +159,8 @@ class TestSqlConf extends HoodieSparkSqlTestBase with BeforeAndAfter { after { unsetEnv(DFSPropertiesConfiguration.CONF_FILE_DIR_ENV_NAME) DFSPropertiesConfiguration.clearGlobalProps() + // Reload the globals with HUDI_CONF_DIR unset, so the JVM is back to its pre-suite state + // instead of an empty props set that would stop a later reader from loading the defaults. + DFSPropertiesConfiguration.refreshGlobalProps() } } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestCreateTable.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestCreateTable.scala index 67c89050c1f3..9d0b22abcf4b 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestCreateTable.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestCreateTable.scala @@ -52,7 +52,7 @@ import scala.collection.JavaConverters._ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelpers { test("Test Create Managed Hoodie Table") { - val databaseName = "hudi_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") @@ -311,8 +311,8 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp assertTrue(storage.exists(tableConfigPath)) val tableConfigModificationTime = storage.getPathInfo(tableConfigPath).getModificationTime validateExternalTableCreation(storage, basePath, tableConfigModificationTime, Option.empty) - validateExternalTableCreation(storage, basePath, tableConfigModificationTime, Option("new_database")) - validateExternalTableCreation(storage, basePath, tableConfigModificationTime, Option("another_database")) + validateExternalTableCreation(storage, basePath, tableConfigModificationTime, Option(generateTableName)) + validateExternalTableCreation(storage, basePath, tableConfigModificationTime, Option(generateTableName)) } } @@ -320,7 +320,7 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp basePath: String, tableConfigModificationTime: Long, databaseName: Option[String]): Unit = { - val tableName = "table" + val tableName = generateTableName if (databaseName.isDefined) { spark.sql( s""" @@ -1033,7 +1033,7 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp test("Test Create Table From Existing Hoodie Table") { withTempDir { tmp => - val databaseName = "hudi_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") @@ -1558,7 +1558,7 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp } test("Test Create Non-Hudi Table(Parquet Table)") { - val databaseName = "test_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") @@ -2696,8 +2696,9 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp // VECTOR type name. test("test create VECTOR table with CLUSTERED BY bucket spec parses (parser coverage)") { + val bucketTableName = generateTableName val plan = parseCreateTable( - "CREATE TABLE vec_bucket_tbl (id BIGINT, embedding VECTOR(4)) USING hudi " + + s"CREATE TABLE $bucketTableName (id BIGINT, embedding VECTOR(4)) USING hudi " + "CLUSTERED BY (id) INTO 4 BUCKETS") val bucket = transformByName(plan, "bucket") assertEquals("4", firstLiteralArg(bucket).value.toString) @@ -2705,14 +2706,16 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp // SORTED BY ... ASC is accepted by the bucket-spec visitor and yields a sorted_bucket // transform; a plain bucket transform here would mean the SORTED BY clause was dropped. + val sortedBucketTableName = generateTableName val sortedPlan = parseCreateTable( - "CREATE TABLE vec_sbucket_tbl (id BIGINT, ts BIGINT, embedding VECTOR(4)) USING hudi " + + s"CREATE TABLE $sortedBucketTableName (id BIGINT, ts BIGINT, embedding VECTOR(4)) USING hudi " + "CLUSTERED BY (id, ts) SORTED BY (id ASC) INTO 8 BUCKETS") assertEquals("sorted_bucket", sortedPlan.partitioning.head.name) // SORTED BY ... DESC is rejected by the bucket-spec visitor. + val badBucketTableName = generateTableName checkExceptionContain( - "CREATE TABLE vec_bad_bucket_tbl (id BIGINT, embedding VECTOR(4)) USING hudi " + + s"CREATE TABLE $badBucketTableName (id BIGINT, embedding VECTOR(4)) USING hudi " + "CLUSTERED BY (id) SORTED BY (id DESC) INTO 4 BUCKETS")( "Column ordering must be ASC") } @@ -2723,40 +2726,44 @@ class TestCreateTable extends HoodieSparkSqlTestBase with ExtendedParserTestHelp // tableSpec (location/comment/properties are stable across Spark 3.3 through 4.2; the parsed // options map is not exposed on the 3.5+ TableSpecBase, so OPTIONS is only asserted through // the path-folding case below). + val tableName = generateTableName val plan = parseCreateTable( s""" - |CREATE TABLE vec_clause_tbl ( + |CREATE TABLE $tableName ( | id BIGINT, | embedding VECTOR(4) |) USING hudi |COMMENT 'a vector table' - |LOCATION '/tmp/vec_clause_tbl' + |LOCATION '/tmp/$tableName' |OPTIONS ('opt_str' = 'v', 'opt_int' = 1, 'opt_bool' = true) |TBLPROPERTIES ('prop_str' = 'v', 'prop_int' = 2, 'prop_bool' = false) """.stripMargin) assertEquals(ArrayType(FloatType, containsNull = false), plan.tableSchema("embedding").dataType) assertEquals(Some("a vector table"), plan.tableSpec.comment) - assertEquals(Some("/tmp/vec_clause_tbl"), plan.tableSpec.location) + assertEquals(Some(s"/tmp/$tableName"), plan.tableSpec.location) assertEquals("v", plan.tableSpec.properties("prop_str")) assertEquals("2", plan.tableSpec.properties("prop_int")) assertEquals("false", plan.tableSpec.properties("prop_bool")) // A 'path' option with no LOCATION is folded into the table location by the option cleaner. + val pathTableName = generateTableName val pathPlan = parseCreateTable( - "CREATE TABLE vec_path_tbl (id BIGINT, embedding VECTOR(4)) USING hudi " + - "OPTIONS ('path' = '/tmp/vec_path_tbl')") - assertEquals(Some("/tmp/vec_path_tbl"), pathPlan.tableSpec.location) + s"CREATE TABLE $pathTableName (id BIGINT, embedding VECTOR(4)) USING hudi " + + s"OPTIONS ('path' = '/tmp/$pathTableName')") + assertEquals(Some(s"/tmp/$pathTableName"), pathPlan.tableSpec.location) // A 'path' option colliding with LOCATION is rejected by the option cleaner. + val dupPathTableName = generateTableName interceptParse( - "CREATE TABLE vec_dup_path_tbl (id BIGINT, embedding VECTOR(4)) USING hudi " + + s"CREATE TABLE $dupPathTableName (id BIGINT, embedding VECTOR(4)) USING hudi " + "OPTIONS ('path' = '/tmp/a') LOCATION '/tmp/b'")( "Duplicated table paths") // Each reserved table property (provider, location, owner) is rejected by the property cleaner. Seq("provider", "location", "owner").foreach { reserved => + val reservedTableName = generateTableName interceptParse( - s"CREATE TABLE vec_reserved_$reserved (id BIGINT, embedding VECTOR(4)) USING hudi " + + s"CREATE TABLE $reservedTableName (id BIGINT, embedding VECTOR(4)) USING hudi " + s"TBLPROPERTIES ('$reserved' = 'x')")( "reserved table property") } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestDropTable.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestDropTable.scala index dafe532ee8c4..7fbdc208dd5d 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestDropTable.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestDropTable.scala @@ -29,6 +29,10 @@ import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase class TestDropTable extends HoodieSparkSqlTestBase { + // The catalog is shared with suites running at the same time, so listings are scoped to + // this suite's tables. Spark's LIKE pattern: '*' matches any characters, '_' is literal. + private val showSuiteTables = s"show tables like '$tableNamePrefix*'" + test("Test Drop Table") { withTempDir { tmp => Seq("cow", "mor").foreach { tableType => @@ -138,7 +142,7 @@ class TestDropTable extends HoodieSparkSqlTestBase { Map("hoodie.query.as.ro.table" -> "false")) spark.sql(s"drop table ${tableName} purge") - checkAnswer("show tables")() + checkAnswer(showSuiteTables)() } } @@ -187,14 +191,14 @@ class TestDropTable extends HoodieSparkSqlTestBase { Map("hoodie.query.as.ro.table" -> "false")) spark.sql(s"drop table ${tableName}_ro") - checkAnswer("show tables")( + checkAnswer(showSuiteTables)( Seq("default", tableName, false), Seq("default", s"${tableName}_rt", false)) spark.sql(s"drop table ${tableName}_rt") - checkAnswer("show tables")(Seq("default", tableName, false)) + checkAnswer(showSuiteTables)(Seq("default", tableName, false)) spark.sql(s"drop table ${tableName}") - checkAnswer("show tables")() + checkAnswer(showSuiteTables)() } } @@ -243,7 +247,7 @@ class TestDropTable extends HoodieSparkSqlTestBase { Map("hoodie.query.as.ro.table" -> "false")) spark.sql(s"drop table ${tableName}_ro purge") - checkAnswer("show tables")() + checkAnswer(showSuiteTables)() } } @@ -270,7 +274,7 @@ class TestDropTable extends HoodieSparkSqlTestBase { filesystem.delete(new Path(tablePath), true) spark.sql(s"drop table ${tableName}") - checkAnswer("show tables")() + checkAnswer(showSuiteTables)() } } @@ -325,7 +329,7 @@ class TestDropTable extends HoodieSparkSqlTestBase { spark.sql(s"drop table ${tableName}") spark.sql(s"drop table ${tableName}_ro") spark.sql(s"drop table ${tableName}_rt") - checkAnswer("show tables")() + checkAnswer(showSuiteTables)() } } @@ -354,7 +358,7 @@ class TestDropTable extends HoodieSparkSqlTestBase { filesystem.delete(tablePath, true) spark.sql(s"drop table $tableName") - checkAnswer("show tables")() + checkAnswer(showSuiteTables)() } } } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSpark3DDL.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSpark3DDL.scala index d8c1d00849c6..d4b3dacf9559 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSpark3DDL.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSpark3DDL.scala @@ -25,7 +25,6 @@ import org.apache.hudi.common.table.{HoodieTableConfig, TableSchemaResolver} import org.apache.hudi.common.table.timeline.HoodieInstant import org.apache.hudi.common.testutils.HoodieTestDataGenerator import org.apache.hudi.config.HoodieWriteConfig -import org.apache.hudi.index.HoodieInMemoryHashIndex import org.apache.hudi.testutils.DataSourceTestUtils import org.apache.hudi.testutils.HoodieClientTestUtils.createMetaClient @@ -1070,7 +1069,7 @@ class TestSpark3DDL extends HoodieSparkSqlTestBase { spark.sql(s"select id, name, cast(price as string), ts from $tableName") // clear after using INMEMORY index - HoodieInMemoryHashIndex.clear() + clearInMemoryIndex() } } } @@ -1154,7 +1153,7 @@ class TestSpark3DDL extends HoodieSparkSqlTestBase { ) // clear after using INMEMORY index - HoodieInMemoryHashIndex.clear() + clearInMemoryIndex() } } } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSparkCatalogSync.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSparkCatalogSync.scala index 970adc4bde44..46654036b9b2 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSparkCatalogSync.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/ddl/TestSparkCatalogSync.scala @@ -39,7 +39,7 @@ class TestSparkCatalogSync extends HoodieSparkSqlTestBase { import spark.implicits._ val tableName = generateTableName - val databaseName = "testdb" + val databaseName = generateTableName val basePath = s"${tmp.getCanonicalPath}/$tableName" val syncProps = buildSyncProps(databaseName, tableName, basePath) @@ -81,7 +81,7 @@ class TestSparkCatalogSync extends HoodieSparkSqlTestBase { import spark.implicits._ val tableName = generateTableName - val databaseName = "testdb" + val databaseName = generateTableName val basePath = s"${tmp.getCanonicalPath}/$tableName" val syncProps = buildSyncProps(databaseName, tableName, basePath) @@ -119,7 +119,7 @@ class TestSparkCatalogSync extends HoodieSparkSqlTestBase { import spark.implicits._ val tableName = generateTableName - val databaseName = "testdb" + val databaseName = generateTableName val basePath = s"${tmp.getCanonicalPath}/$tableName" val syncProps = buildSyncProps(databaseName, tableName, basePath) diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable4.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable4.scala index eebc34fa9625..53023869ddfb 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable4.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/insert/TestInsertTable4.scala @@ -31,12 +31,12 @@ import org.apache.hudi.config.{HoodieClusteringConfig, HoodieIndexConfig, Hoodie import org.apache.hudi.exception.{HoodieDuplicateKeyException, HoodieException} import org.apache.hudi.index.HoodieIndex.IndexType -import org.apache.spark.scheduler.{SparkListener, SparkListenerStageSubmitted} +import org.apache.spark.scheduler.{SparkListener, SparkListenerJobStart, SparkListenerStageSubmitted} import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase.getLastCommitMetadata import java.io.File -import java.util.concurrent.{CountDownLatch, TimeUnit} +import java.util.concurrent.{ConcurrentHashMap, CountDownLatch, TimeUnit} class TestInsertTable4 extends HoodieSparkSqlTestBase { test("Test Bulk Insert Into Consistent Hashing Bucket Index Table") { @@ -290,10 +290,22 @@ class TestInsertTable4 extends HoodieSparkSqlTestBase { var listenerCallCount: Int = 0 var countDownLatch: CountDownLatch = _ - // add a listener for stages for parallelism checking with stage name - class StageParallelismListener(var stageName: String) extends SparkListener { + // add a listener for stages for parallelism checking with stage name, restricted to the stages of + // the jobs this test started. Hudi overwrites the job description on its own jobs, so the + // discriminator is a local property the test sets before the query. + class StageParallelismListener(var stageName: String, scope: String) extends SparkListener { + private val scopedStageIds = ConcurrentHashMap.newKeySet[Int]() + + override def onJobStart(jobStart: SparkListenerJobStart): Unit = { + if (jobStart.properties != null + && scope == jobStart.properties.getProperty(TestInsertTable4.SCOPE_PROPERTY)) { + jobStart.stageIds.foreach(stageId => scopedStageIds.add(stageId)) + } + } + override def onStageSubmitted(stageSubmitted: SparkListenerStageSubmitted): Unit = { - if (stageSubmitted.stageInfo.name.contains(stageName)) { + if (scopedStageIds.contains(stageSubmitted.stageInfo.stageId) + && stageSubmitted.stageInfo.name.contains(stageName)) { assertResult(1)(stageSubmitted.stageInfo.numTasks) listenerCallCount = listenerCallCount + 1 countDownLatch.countDown @@ -339,7 +351,9 @@ class TestInsertTable4 extends HoodieSparkSqlTestBase { |""".stripMargin) val stageClassName = classOf[HoodieSparkEngineContext].getSimpleName // The SparkContext outlives the suite in shared session mode, so the listener must not. - val listener = new StageParallelismListener(stageName = stageClassName) + val scope = java.util.UUID.randomUUID().toString + spark.sparkContext.setLocalProperty(TestInsertTable4.SCOPE_PROPERTY, scope) + val listener = new StageParallelismListener(stageName = stageClassName, scope = scope) spark.sparkContext.addSparkListener(listener) try { val df = spark.sql( @@ -356,6 +370,7 @@ class TestInsertTable4 extends HoodieSparkSqlTestBase { assert(listenerCallCount >= 1) } finally { spark.sparkContext.removeSparkListener(listener) + spark.sparkContext.setLocalProperty(TestInsertTable4.SCOPE_PROPERTY, null) } } } @@ -398,7 +413,9 @@ class TestInsertTable4 extends HoodieSparkSqlTestBase { |""".stripMargin) val stageClassName = classOf[HoodieSparkEngineContext].getSimpleName // The SparkContext outlives the suite in shared session mode, so the listener must not. - val listener = new StageParallelismListener(stageName = stageClassName) + val scope = java.util.UUID.randomUUID().toString + spark.sparkContext.setLocalProperty(TestInsertTable4.SCOPE_PROPERTY, scope) + val listener = new StageParallelismListener(stageName = stageClassName, scope = scope) spark.sparkContext.addSparkListener(listener) try { val df = spark.sql( @@ -415,6 +432,7 @@ class TestInsertTable4 extends HoodieSparkSqlTestBase { assert(listenerCallCount >= 1) } finally { spark.sparkContext.removeSparkListener(listener) + spark.sparkContext.setLocalProperty(TestInsertTable4.SCOPE_PROPERTY, null) } } } @@ -856,3 +874,8 @@ class TestInsertTable4 extends HoodieSparkSqlTestBase { } } } + +object TestInsertTable4 { + // Local property set by a test so its stage listener only sees the jobs that test started. + val SCOPE_PROPERTY = "hoodie.test.stage.listener.scope" +} diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/schema/TestBlobDataType.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/schema/TestBlobDataType.scala index 368506bfd076..99877c13d87d 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/schema/TestBlobDataType.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/dml/schema/TestBlobDataType.scala @@ -293,9 +293,10 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel test("Test parse CREATE TABLE with BLOB column and primitive data types") { // Exercises the primitive-data-type match arms plus NOT NULL and column COMMENT. + val tableName = generateTableName val plan = parseCreateTable( s""" - |CREATE TABLE blob_prim_tbl ( + |CREATE TABLE $tableName ( | c_bool BOOLEAN, | c_tiny TINYINT, | c_small SMALLINT, @@ -341,9 +342,10 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel test("Test parse CREATE TABLE with BLOB column and complex data types") { // Exercises the ARRAY / MAP / STRUCT arms. BLOB-in-struct metadata handling is already // covered by "test BLOB in nested struct". + val tableName = generateTableName val plan = parseCreateTable( s""" - |CREATE TABLE blob_complex_tbl ( + |CREATE TABLE $tableName ( | c_arr ARRAY<INT>, | c_map MAP<STRING, INT>, | c_struct STRUCT<a: INT, b: STRING>, @@ -360,9 +362,10 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel } test("Test parse CREATE TABLE with BLOB column and interval data types") { + val tableName = generateTableName val plan = parseCreateTable( s""" - |CREATE TABLE blob_ivl_tbl ( + |CREATE TABLE $tableName ( | i_year INTERVAL YEAR, | i_ym INTERVAL YEAR TO MONTH, | i_day INTERVAL DAY, @@ -382,18 +385,21 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // Endpoints where the end field does not follow the start are rejected by both interval // data-type visitors. The grammar only allows YEAR/MONTH -> MONTH and DAY/HOUR/MINUTE/SECOND // -> HOUR/MINUTE/SECOND, so these stay grammatical yet still hit the builder's end <= start guard. + val badYmTableName = generateTableName interceptParse( - "CREATE TABLE blob_bad_ym (id BIGINT, bad INTERVAL MONTH TO MONTH, data BLOB) USING hudi")( + s"CREATE TABLE $badYmTableName (id BIGINT, bad INTERVAL MONTH TO MONTH, data BLOB) USING hudi")( "are not supported") + val badDtTableName = generateTableName interceptParse( - "CREATE TABLE blob_bad_dt (id BIGINT, bad INTERVAL SECOND TO HOUR, data BLOB) USING hudi")( + s"CREATE TABLE $badDtTableName (id BIGINT, bad INTERVAL SECOND TO HOUR, data BLOB) USING hudi")( "are not supported") } test("Test parse CREATE TABLE with BLOB column and partition transforms") { + val tableName = generateTableName val plan = parseCreateTable( s""" - |CREATE TABLE blob_tf_tbl ( + |CREATE TABLE $tableName ( | id BIGINT, | ts DATE, | region STRING, @@ -413,8 +419,9 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // bucket(numBuckets, col) with int, long and short number-of-buckets literals exercises the // three numeric arms of the bucket handling. Seq("4", "4L", "4S").foreach { numLiteral => + val bucketTableName = generateTableName val bp = parseCreateTable( - s"CREATE TABLE blob_bkt_tbl (id BIGINT, data BLOB) USING hudi " + + s"CREATE TABLE $bucketTableName (id BIGINT, data BLOB) USING hudi " + s"PARTITIONED BY (bucket($numLiteral, id))") val bkt = transformByName(bp, "bucket") assertResult("4")(firstLiteralArg(bkt).value.toString) @@ -426,24 +433,28 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // The partition-COLUMN arm is the only partitioning branch that changes the emitted schema: // the parsed partition columns are appended to the table columns and each becomes an // identity transform. + val tableName = generateTableName val plan = parseCreateTable( - "CREATE TABLE blob_pcol_tbl (id BIGINT, data BLOB) USING hudi PARTITIONED BY (p STRING)") + s"CREATE TABLE $tableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (p STRING)") assertResult(StringType)(plan.tableSchema("p").dataType) assertResult(BlobType())(plan.tableSchema("data").dataType) assertResult(Seq(Seq("p")))(transformFieldRefs(transformByName(plan, "identity"))) // Mixing partition columns and transform expressions is rejected. + val mixTableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_mix_tbl (id BIGINT, data BLOB) USING hudi " + + s"CREATE TABLE $mixTableName (id BIGINT, data BLOB) USING hudi " + "PARTITIONED BY (p STRING, bucket(4, id))")( "Cannot mix partition expressions and partition columns") // SKEWED BY and CREATE TEMPORARY TABLE are rejected by the clause and header visitors. + val skewTableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_skew_tbl (id BIGINT, data BLOB) USING hudi SKEWED BY (id) ON (1, 2)")( + s"CREATE TABLE $skewTableName (id BIGINT, data BLOB) USING hudi SKEWED BY (id) ON (1, 2)")( "CREATE TABLE ... SKEWED BY") + val tmpTableName = generateTableName checkExceptionContain( - "CREATE TEMPORARY TABLE blob_tmp_tbl (id BIGINT, data BLOB) USING hudi")( + s"CREATE TEMPORARY TABLE $tmpTableName (id BIGINT, data BLOB) USING hudi")( "use CREATE TEMPORARY VIEW instead") } @@ -458,9 +469,10 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // dependent: only TRUE is ansiNonReserved, so a bare true always parses as a column // reference, while false and null are column references under the default non-ANSI keyword // mode but typed literals under ANSI mode (both cases are asserted below). + val tableName = generateTableName val plan = parseCreateTable( s""" - |CREATE TABLE blob_lit_tbl ( + |CREATE TABLE $tableName ( | id BIGINT, | data BLOB |) USING hudi @@ -489,8 +501,9 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // and visitNullLiteral as typed literals, while a bare true stays a column reference // (TRUE is ansiNonReserved; FALSE and NULL are not). withSQLConf("spark.sql.ansi.enabled" -> "true") { + val boolTableName = generateTableName val ansiPlan = parseCreateTable( - "CREATE TABLE blob_bool_tbl (id BIGINT, data BLOB) USING hudi " + + s"CREATE TABLE $boolTableName (id BIGINT, data BLOB) USING hudi " + "PARTITIONED BY (bool_t(false, id), true_t(true, id), null_t(null, id))") assertResult(BooleanType)(firstLiteralArg(transformByName(ansiPlan, "bool_t")).dataType) assertResult(false)(firstLiteralArg(transformByName(ansiPlan, "bool_t")).value) @@ -506,30 +519,37 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // clean ParseException on every Spark profile (#19450). Assertions stay substring-based // because the Spark 4.x builders add an "Operation not allowed: " prefix. // Non-numeric number of buckets. - interceptParse("CREATE TABLE blob_e1 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (bucket('x', id))")( + val e1TableName = generateTableName + interceptParse(s"CREATE TABLE $e1TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (bucket('x', id))")( "Invalid number of buckets") // A non-column-reference where a column is required. The buggy interpolation rendered the // literal text "5.describe" (a superstring of the expected message), so pin its absence too. - val e2 = interceptParse("CREATE TABLE blob_e2 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (bucket(4, 5))")( + val e2TableName = generateTableName + val e2 = interceptParse(s"CREATE TABLE $e2TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (bucket(4, 5))")( "Expected a column reference for transform bucket: 5") assert(!e2.getMessage.contains(".describe")) // A single-field transform given more than one argument. - interceptParse("CREATE TABLE blob_e3 (id BIGINT, ts DATE, data BLOB) USING hudi PARTITIONED BY (years(id, ts))")( + val e3TableName = generateTableName + interceptParse(s"CREATE TABLE $e3TableName (id BIGINT, ts DATE, data BLOB) USING hudi PARTITIONED BY (years(id, ts))")( "Too many arguments") // Typed literal that fails to parse (visitTypeConstructor arm). - interceptParse("CREATE TABLE blob_e4 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(DATE 'nope', id))")( + val e4TableName = generateTableName + interceptParse(s"CREATE TABLE $e4TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(DATE 'nope', id))")( "Cannot parse the DATE value: nope") // Invalid INTERVAL literal: the builders copy the triggering exception's stack trace onto the // ParseException (the construct-then-setStackTrace arm), so the thrower must be visible. - val e5 = interceptParse("CREATE TABLE blob_e5 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 'x', id))")( + val e5TableName = generateTableName + val e5 = interceptParse(s"CREATE TABLE $e5TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 'x', id))")( "Cannot parse the INTERVAL value: x") assert(e5.getStackTrace.exists(_.getClassName.contains("IntervalUtils"))) // Out-of-range fractional literal; pre-fix the message's interior dots broke Spark 3.4+ // error-class lookup and surfaced as a bare AssertionError. - interceptParse("CREATE TABLE blob_e6 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (bucket(1e40F, id))")( + val e6TableName = generateTableName + interceptParse(s"CREATE TABLE $e6TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (bucket(1e40F, id))")( "does not fit in range") // Mixed year-month and day-time interval fields. - interceptParse("CREATE TABLE blob_e7 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL '1 year 2 hours', id))")( + val e7TableName = generateTableName + interceptParse(s"CREATE TABLE $e7TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL '1 year 2 hours', id))")( "Cannot mix year-month and day-time fields") } @@ -537,25 +557,32 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // Remaining error arms of the literal and interval visitors, one SQL per throw site; all must // surface as a clean ParseException on every Spark profile (#19450). // A typed literal whose type keyword has no visitor arm. - interceptParse("CREATE TABLE blob_e8 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(FOO 'bar', id))")( + val e8TableName = generateTableName + interceptParse(s"CREATE TABLE $e8TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(FOO 'bar', id))")( "Literals of type 'FOO' are currently not supported") // A hex literal with a non-hex character (the IllegalArgumentException fallback arm). - interceptParse("CREATE TABLE blob_e9 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(X'zz', id))")( + val e9TableName = generateTableName + interceptParse(s"CREATE TABLE $e9TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(X'zz', id))")( "hexBinary") // Multi-unit interval combined with a from-to unit. - interceptParse("CREATE TABLE blob_e10 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 1 DAY 2 HOUR TO MINUTE, id))")( + val e10TableName = generateTableName + interceptParse(s"CREATE TABLE $e10TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 1 DAY 2 HOUR TO MINUTE, id))")( "Can only have a single from-to unit in the interval literal syntax") // From-to unit combined with a trailing multi-unit interval (the error-recovery arm). - interceptParse("CREATE TABLE blob_e11 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL '1' DAY TO HOUR '2' MINUTE, id))")( + val e11TableName = generateTableName + interceptParse(s"CREATE TABLE $e11TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL '1' DAY TO HOUR '2' MINUTE, id))")( "Can only have a single from-to unit in the interval literal syntax") // A non-numeric value in a unit-value pair. - interceptParse("CREATE TABLE blob_e12 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 'x' DAY, id))")( + val e12TableName = generateTableName + interceptParse(s"CREATE TABLE $e12TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 'x' DAY, id))")( "Can only use numbers in the interval value part") // A from-to interval whose value is not a string literal. - interceptParse("CREATE TABLE blob_e13 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 1 DAY TO HOUR, id))")( + val e13TableName = generateTableName + interceptParse(s"CREATE TABLE $e13TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL 1 DAY TO HOUR, id))")( "The value of from-to unit must be a string") // A from-to unit pair outside the supported YEAR TO MONTH / DAY TO SECOND family. - interceptParse("CREATE TABLE blob_e14 (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL '1' MONTH TO HOUR, id))")( + val e14TableName = generateTableName + interceptParse(s"CREATE TABLE $e14TableName (id BIGINT, data BLOB) USING hudi PARTITIONED BY (myfunc(INTERVAL '1' MONTH TO HOUR, id))")( "Intervals FROM month TO hour are not supported") } @@ -564,36 +591,43 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel // Spark 3.3 through 4.2 via tableSpec.serde); asserting only the BLOB column type would pass // even if the file/row-format visitors dropped their clause. // Generic STORED AS format. - val ff1 = parseCreateTable("CREATE TABLE blob_ff1 (id BIGINT, data BLOB) STORED AS PARQUET") + val ff1TableName = generateTableName + val ff1 = parseCreateTable(s"CREATE TABLE $ff1TableName (id BIGINT, data BLOB) STORED AS PARQUET") assertResult(BlobType())(ff1.tableSchema("data").dataType) assertResult(Some("PARQUET"))(ff1.tableSpec.serde.get.storedAs) // STORED AS INPUTFORMAT ... OUTPUTFORMAT ... (the table-file-format arm). - val ff2 = parseCreateTable("CREATE TABLE blob_ff2 (id BIGINT, data BLOB) " + + val ff2TableName = generateTableName + val ff2 = parseCreateTable(s"CREATE TABLE $ff2TableName (id BIGINT, data BLOB) " + "STORED AS INPUTFORMAT 'com.example.InFmt' OUTPUTFORMAT 'com.example.OutFmt'") assertResult(Some(FormatClasses("com.example.InFmt", "com.example.OutFmt")))( ff2.tableSpec.serde.get.formatClasses) // ROW FORMAT SERDE on its own. - val ff3 = parseCreateTable("CREATE TABLE blob_ff3 (id BIGINT, data BLOB) " + + val ff3TableName = generateTableName + val ff3 = parseCreateTable(s"CREATE TABLE $ff3TableName (id BIGINT, data BLOB) " + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'") assertResult(Some("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"))( ff3.tableSpec.serde.get.serde) // ROW FORMAT DELIMITED on its own. - val ff4 = parseCreateTable("CREATE TABLE blob_ff4 (id BIGINT, data BLOB) " + + val ff4TableName = generateTableName + val ff4 = parseCreateTable(s"CREATE TABLE $ff4TableName (id BIGINT, data BLOB) " + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ','") assertResult(",")(ff4.tableSpec.serde.get.serdeProperties("field.delim")) // Compatible ROW FORMAT SERDE + STORED AS SEQUENCEFILE merges both into one SerdeInfo. - val ff5 = parseCreateTable("CREATE TABLE blob_ff5 (id BIGINT, data BLOB) " + + val ff5TableName = generateTableName + val ff5 = parseCreateTable(s"CREATE TABLE $ff5TableName (id BIGINT, data BLOB) " + "ROW FORMAT SERDE 'com.example.Serde' STORED AS SEQUENCEFILE") assertResult(Some("SEQUENCEFILE"))(ff5.tableSpec.serde.get.storedAs) assertResult(Some("com.example.Serde"))(ff5.tableSpec.serde.get.serde) // Compatible ROW FORMAT DELIMITED + STORED AS TEXTFILE. - val ff6 = parseCreateTable("CREATE TABLE blob_ff6 (id BIGINT, data BLOB) " + + val ff6TableName = generateTableName + val ff6 = parseCreateTable(s"CREATE TABLE $ff6TableName (id BIGINT, data BLOB) " + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE") assertResult(Some("TEXTFILE"))(ff6.tableSpec.serde.get.storedAs) assertResult(",")(ff6.tableSpec.serde.get.serdeProperties("field.delim")) // Any ROW FORMAT combined with STORED AS INPUTFORMAT/OUTPUTFORMAT is accepted (the // table-file-format arm of validateRowFormatFileFormat). - val ff7 = parseCreateTable("CREATE TABLE blob_ff7 (id BIGINT, data BLOB) " + + val ff7TableName = generateTableName + val ff7 = parseCreateTable(s"CREATE TABLE $ff7TableName (id BIGINT, data BLOB) " + "ROW FORMAT SERDE 'com.example.Serde' " + "STORED AS INPUTFORMAT 'com.example.InFmt' OUTPUTFORMAT 'com.example.OutFmt'") assertResult(Some("com.example.Serde"))(ff7.tableSpec.serde.get.serde) @@ -601,31 +635,36 @@ class TestBlobDataType extends HoodieSparkSqlTestBase with ExtendedParserTestHel ff7.tableSpec.serde.get.formatClasses) // ROW FORMAT DELIMITED with a non-text file format is rejected. + val ferr1TableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_ferr1 (id BIGINT, data BLOB) " + + s"CREATE TABLE $ferr1TableName (id BIGINT, data BLOB) " + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS PARQUET")( "only compatible with 'textfile'") // ROW FORMAT SERDE with a format that also specifies a serde is rejected. + val ferr2TableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_ferr2 (id BIGINT, data BLOB) " + + s"CREATE TABLE $ferr2TableName (id BIGINT, data BLOB) " + "ROW FORMAT SERDE 'com.example.Serde' STORED AS PARQUET")( "incompatible with format") // STORED BY (a storage handler) is not allowed. The full "Operation not allowed" prefix is // asserted because ParseException.getMessage echoes the SQL text, so a bare "STORED BY" // expectation would match any failure of this statement. + val ferr3TableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_ferr3 (id BIGINT, data BLOB) STORED BY 'com.example.Handler'")( + s"CREATE TABLE $ferr3TableName (id BIGINT, data BLOB) STORED BY 'com.example.Handler'")( "Operation not allowed: STORED BY") // ROW FORMAT combined with STORED BY leaves no file format for the row format to pair with; // validateRowFormatFileFormat's catch-all arm rejects the combination before the STORED BY // error can fire. + val ferr5TableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_ferr5 (id BIGINT, data BLOB) " + + s"CREATE TABLE $ferr5TableName (id BIGINT, data BLOB) " + "ROW FORMAT SERDE 'com.example.Serde' STORED BY 'com.example.Handler'")( "Unexpected combination of") // A USING provider combined with a serde clause is not allowed. + val ferr4TableName = generateTableName checkExceptionContain( - "CREATE TABLE blob_ferr4 (id BIGINT, data BLOB) USING hudi STORED AS PARQUET")( + s"CREATE TABLE $ferr4TableName (id BIGINT, data BLOB) USING hudi STORED AS PARQUET")( "CREATE TABLE ... USING") } } diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/TestCDCForSparkSQL.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/TestCDCForSparkSQL.scala index d082e7b175f5..26c912b59719 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/TestCDCForSparkSQL.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/TestCDCForSparkSQL.scala @@ -55,7 +55,7 @@ class TestCDCForSparkSQL extends HoodieSparkSqlTestBase { test("Test delete all records in filegroup") { Seq("cow", "mor").foreach { tableType => withTempDir { tmp => - val databaseName = "hudi_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") val tableName = generateTableName @@ -100,7 +100,7 @@ class TestCDCForSparkSQL extends HoodieSparkSqlTestBase { * Test CDC in cases that it's a COW/MOR non--partitioned table and `cdcSupplementalLoggingMode` is true or not. */ test("Test Non-Partitioned Hoodie Table") { - val databaseName = "hudi_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") @@ -226,7 +226,7 @@ class TestCDCForSparkSQL extends HoodieSparkSqlTestBase { * Test CDC in cases that it's a COW/MOR partitioned table and `cdcSupplementalLoggingMode` is true or not. */ test("Test Partitioned Hoodie Table") { - val databaseName = "hudi_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") @@ -307,7 +307,7 @@ class TestCDCForSparkSQL extends HoodieSparkSqlTestBase { } test("Test Partial Updates With Spark CDC") { - val databaseName = "hudi_database" + val databaseName = generateTableName spark.sql(s"create database if not exists $databaseName") spark.sql(s"use $databaseName") withSQLConf(HoodieWriteConfig.MERGE_SMALL_FILE_GROUP_CANDIDATES_LIMIT.key -> "0", diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala index 902da89e58c6..60abe0266d5d 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestExpressionIndex.scala @@ -57,7 +57,7 @@ import org.apache.spark.sql.catalyst.parser.ParserInterface import org.apache.spark.sql.execution.FileSourceScanExec import org.apache.spark.sql.functions.lit import org.apache.spark.sql.hudi.command.{CreateIndexCommand, ShowIndexesCommand} -import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase +import org.apache.spark.sql.hudi.common.{ExclusiveSuite, HoodieSparkSqlTestBase} import org.apache.spark.sql.types._ import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertTrue} @@ -66,7 +66,7 @@ import java.util.stream.Collectors import scala.collection.JavaConverters -class TestExpressionIndex extends HoodieSparkSqlTestBase with SparkAdapterSupport { +class TestExpressionIndex extends HoodieSparkSqlTestBase with SparkAdapterSupport with ExclusiveSuite { override protected def beforeAll(): Unit = { spark.sql("set hoodie.metadata.index.column.stats.enable=false") diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestHoodieBackedTableMetadataIndexLookup.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestHoodieBackedTableMetadataIndexLookup.scala index c68ca0a9b601..adb13c10fa64 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestHoodieBackedTableMetadataIndexLookup.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestHoodieBackedTableMetadataIndexLookup.scala @@ -34,7 +34,7 @@ import org.apache.hudi.metadata.{HoodieBackedTableMetadata, MetadataPartitionTyp import org.apache.spark.api.java.JavaSparkContext import org.apache.spark.sql.SQLContext -import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase +import org.apache.spark.sql.hudi.common.{ExclusiveSuite, HoodieSparkSqlTestBase} import org.apache.spark.util.Utils import java.io.File @@ -45,7 +45,7 @@ import scala.collection.JavaConverters._ * Base class for testing HoodieBackedTableMetadata index lookup functionality. * Provides shared setup and common test utilities. */ -abstract class HoodieBackedTableMetadataIndexLookupTestBase extends HoodieSparkSqlTestBase { +abstract class HoodieBackedTableMetadataIndexLookupTestBase extends HoodieSparkSqlTestBase with ExclusiveSuite { // Shared test data for all tests protected var tableName: String = _ diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestSecondaryIndex.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestSecondaryIndex.scala index 9c1886ccb062..0926e8376057 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestSecondaryIndex.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/feature/index/TestSecondaryIndex.scala @@ -35,14 +35,14 @@ import org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY import org.apache.hudi.storage.StoragePath import org.apache.spark.sql.SaveMode -import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase +import org.apache.spark.sql.hudi.common.{ExclusiveSuite, HoodieSparkSqlTestBase} import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertNotNull, assertTrue} import java.util.concurrent.atomic.AtomicInteger import scala.collection.JavaConverters._ -class TestSecondaryIndex extends HoodieSparkSqlTestBase { +class TestSecondaryIndex extends HoodieSparkSqlTestBase with ExclusiveSuite { var instantTime: AtomicInteger = new AtomicInteger(1) val metadataOpts: Map[String, String] = Map( diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestClusteringBinaryCopyStrategy.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestClusteringBinaryCopyStrategy.scala index fec133b647f4..d886aa9cbc83 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestClusteringBinaryCopyStrategy.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestClusteringBinaryCopyStrategy.scala @@ -24,13 +24,14 @@ import org.apache.hudi.common.table.timeline.HoodieInstant import org.apache.hudi.common.util.{Option => HOption} import org.apache.spark.SparkConf +import org.apache.spark.sql.hudi.common.ExclusiveSuite import java.math.BigDecimal import java.sql.Date import java.sql.Timestamp import java.time.LocalDate -class TestClusteringBinaryCopyStrategy extends HoodieSparkProcedureTestBase { +class TestClusteringBinaryCopyStrategy extends HoodieSparkProcedureTestBase with ExclusiveSuite { override def sparkConf(): SparkConf = { super.sparkConf() diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestHiveSyncProcedure.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestHiveSyncProcedure.scala index 26719e78b141..5d92264b9ff7 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestHiveSyncProcedure.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestHiveSyncProcedure.scala @@ -23,9 +23,10 @@ import org.apache.hudi.hive.{HiveSyncConfig, HiveSyncConfigHolder} import org.apache.hudi.sync.common.HoodieSyncConfig import org.apache.hadoop.hive.conf.HiveConf +import org.apache.spark.sql.hudi.common.ExclusiveSuite import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue} -class TestHiveSyncProcedure extends HoodieSparkProcedureTestBase { +class TestHiveSyncProcedure extends HoodieSparkProcedureTestBase with ExclusiveSuite { // Session-conf keys the procedure writes from its optional arguments; reset after the call so // they do not leak into sibling tests sharing the session. diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala index 668ea2384a00..4126175f4e1c 100644 --- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala +++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestRepairsProcedure.scala @@ -126,7 +126,6 @@ class TestRepairsProcedure extends HoodieSparkProcedureTestBase { val out = fs.create(path) prevProps.store(out, "hudi properties") out.close() - fs.close() // create commit instant val newProps: URL = this.getClass.getClassLoader.getResource("table-config.properties")
