spark-test commented on code in PR #58984:
URL: https://github.com/apache/spark/pull/58984#discussion_r4507582544


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2297,6 +2297,16 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val HIVE_METASTORE_PARTITION_PROJECTION_ENABLED =
+    buildConf("spark.sql.hive.metastorePartitionProjection.enabled")
+      .doc("When true and the Hive Metastore version is 4.0 or higher, Spark 
uses partition " +

Review Comment:
   **Non-blocking (P2):** This doc only describes payload savings, but on Hive 
4.0-4.2 clients the default also changes metastore-side enforcement. 
`get_partitions_with_specs` runs only the table lookup, the projection query 
and the SD grouping. The regular path fetches each batch through 
`get_partitions_ps_with_auth_req`, which fires the pre-read event, authorizes 
partition metadata, applies the server-side filter hook, and checks 
`hive.metastore.limit.partition.request` against the table's total partition 
count. `HiveMetaStoreClient` also applies its client-side filter hook only on 
the regular call. On a metastore with a partition limit, INSERT, TRUNCATE, MSCK 
REPAIR, metadata-only queries and non-lazy conversion used to fail fast on 
tables with more partitions than the limit, and now they run in full. Filter 
hooks also no longer hide partitions from those commands. The 'Metastore-side 
checks' caveat lives only in the PR description, so operators reading the SQL 
config reference wo
 n't know to set this to `false`. Could the doc name 
`spark.sql.hive.metastore.version` as the gate, list the affected commands and 
the skipped checks, and say that `false` restores the full-fetch path?
   
   **Verification:**
   - **Inspection:** The config's doc text states the client-version condition, 
the affected commands, the metastore checks skipped against Hive 4.0-4.2 
metastores, and that false restores the full-fetch path.



##########
sql/hive/src/main/scala/org/apache/spark/sql/hive/client/HiveShim.scala:
##########
@@ -993,6 +1000,26 @@ private[client] class Shim_v2_0 extends Shim with Logging 
{
     hive.getPartitions(table, partSpec).asScala.toSeq
   }
 
+  override def getPartitionLocations(
+      hive: Hive,
+      table: Table,
+      partSpec: JMap[String, String]): Seq[CatalogTablePartitionLocation] = {
+    if (!table.isPartitioned) {
+      Seq.empty
+    } else {
+      recordHiveCall()

Review Comment:
   **Nit (P3):** `getPartitions` (line 999) already calls `recordHiveCall()` 
before its single `hive.getPartitions` call, so this extra call counts it 
twice. On the built-in 2.3.10 client, every switched command now adds a phantom 
call to the published `hiveClientCalls` metric: catalog-tracked INSERT, 
TRUNCATE, MSCK REPAIR, metadata-only queries and non-lazy conversion. The count 
also differs from the projection path, which records once. Dropping this line 
restores one record per call.
   
   **Verification:**
   - **Regression:** On a Hive client below 4.0, a listPartitionLocations call 
raises the Hive client call metric by the same amount as the equivalent 
listPartitions call.



##########
sql/hive/src/test/scala/org/apache/spark/sql/hive/client/HiveClientImplSuite.scala:
##########
@@ -103,4 +112,156 @@ class HiveClientImplSuite extends SparkFunSuite {
         "fieldType" -> "\"STRUCT<A:UNIONTYPE<INT,STRING>>\"",
         "fieldName" -> "`c`"))
   }
+
+  test("Shim_v4_0 getPartitionLocations returns empty on unpartitioned table") 
{
+    // The unpartitioned guard must return before any session config or HMS 
call is needed.
+    val shim = new Shim_v4_0()
+    val table = new org.apache.hadoop.hive.ql.metadata.Table("default", "t")
+    assert(shim.getPartitionLocations(null, table, new 
java.util.HashMap()).isEmpty)
+  }
+
+  test("Shim_v4_0 normalizeLocation constructs expected URI across root and 
relPath shapes") {
+    val shim = new Shim_v4_0()
+    val root = "file:/data/warehouse/tbl"
+
+    // Normal nested partition: the metastore computes relativePath as
+    // location.substring(tablePath.length()), so a true child partition's 
relativePath always
+    // carries the leading separator. normalizeLocation must not insert a 
second one.
+    assert(shim.normalizeLocation(root, "/p1=1/p2=2") ===
+      Some(new URI("file:/data/warehouse/tbl/p1=1/p2=2")))
+
+    // Sibling directory sharing the table path as a string prefix (e.g. 
"<tablePath>_external/"):
+    // the metastore's substring-based relativePath computation is not 
path-boundary aware, so it
+    // has no leading separator here. normalizeLocation must reproduce the 
location verbatim via
+    // concatenation, not insert a separator that was never there.
+    assert(shim.normalizeLocation(root, "_external/p=1") ===
+      Some(new URI("file:/data/warehouse/tbl_external/p=1")))
+
+    // Empty relative path means partition sits directly at the table location
+    assert(shim.normalizeLocation(root, "") === Some(new URI(root)))
+
+    // A null relative path means the metastore reported no location for this 
partition
+    // (either the storage descriptor or its location field was unset). No 
location is
+    // returned, mirroring what the full-fetch path reports for such 
partitions and
+    // avoiding any fabricated default partition path.
+    assert(shim.normalizeLocation(root, null) === None)
+
+    // Null root with non-empty relative path
+    assert(shim.normalizeLocation(null, "file:/custom/loc") ===
+      Some(new URI("file:/custom/loc")))
+
+    // Both root and relative path null
+    assert(shim.normalizeLocation(null, null) === None)
+  }
+
+  test("Shim_v4_0 buildPartitionSpec constructs partition spec") {
+    val shim = new Shim_v4_0()
+
+    // Values are matched to partition columns positionally.
+    val spec = shim.buildPartitionSpec(Array("p1", "p2", "p3"),
+      java.util.Arrays.asList("a", "b", "c"))
+    assert(spec === Map("p1" -> "a", "p2" -> "b", "p3" -> "c"))
+
+    // Defensive: a values list shorter or longer than the partition columns 
truncates
+    // instead of throwing or misaligning.
+    assert(shim.buildPartitionSpec(Array("p1", "p2"),
+      java.util.Arrays.asList("only")) === Map("p1" -> "only"))
+    assert(shim.buildPartitionSpec(Array("p1"),
+      java.util.Arrays.asList("a", "extra")) === Map("p1" -> "a"))
+  }
+
+  test("Shim_v4_0 buildPartitionLocations matches the full-fetch location 
derivation " +
+      "when the partition specs carry no location") {
+    val shim = new Shim_v4_0()
+
+    // How the full-fetch path (Shim_v2_0.getPartitionLocations, backed by the 
classic
+    // getPartitions RPC) derives a partition location: one is present only if 
the storage
+    // descriptor exists and carries one. The projection path must report 
exactly this.
+    def fullFetchLocation(sd: StorageDescriptor): Option[URI] =

Review Comment:
   **Non-blocking (P2):** This oracle models the full-fetch path as reading a 
raw storage descriptor, but the real full-fetch path never does. 
`Shim_v2_0.getPartitionLocations` and `listPartitions` read the SD of the 
`ql.metadata.Partition` objects that `Hive.getPartitions` builds with `new 
Partition(tbl, tpart)`. `Partition.initialize` replaces a null SD location with 
`new Path(table.getDataLocation(), Warehouse.makePartName(partCols, values))` 
whenever the table has a location (Apache Hive `rel/release-4.0.1`, 
`Partition.java` lines 169-177; the same logic is in `rel/release-2.3.10`). So 
for a table at `L` with partition `p1=1` whose SD has no location, the 
full-fetch path reports `L/p1=1` while projection reports `None`. This test 
expects `None`, the projection's own behavior, so it passes without checking 
parity. The `normalizeLocation` scaladoc ('matching what the full-fetch path 
reports for such partitions') and the comment in `buildPartitionLocations` make 
the same claim. The 
 versioned parity tests in `HiveClientSuite` only create partitions that have a 
location. The same premise was the reason given for keeping `None` in the reply 
to the reviewer's request to derive the default.
   
   **Recommended change:** When the projection response reports no location for 
a partition, derive the default the same way Hive's Partition.initialize does: 
the table's data location joined with Hive's partition name for the partition 
columns and values. Skip this only when the table itself has no location. 
Update the normalizeLocation and buildPartitionLocations comments to describe 
this. In the Hive client shim unit tests, replace the hand-written full-fetch 
oracle with expectations taken from Hive's own partition construction.
   
   **Why this works:** Hive's client layer fills in the table location plus the 
partition name before Spark sees a partition on the full-fetch path. Applying 
the same derivation in the projection conversion makes both paths report the 
same location for every row, so the flag no longer changes results. 
Expectations derived from Hive's real behavior then make the tests fail if the 
two paths drift apart.
   
   **Scope:** Missing-location handling in the Hive 4.x shim's projection 
conversion, and its tests
   
   **Compatibility:** Partitions that have a metastore location keep exactly 
the stored location, including sibling directories that share the table path as 
a string prefix.
   
   **Risks:** Rows with no storage descriptor at all also receive the derived 
default, because the grouped projection response reports them exactly like rows 
whose storage descriptor has no location. The base branch failed on such rows, 
and the flag-off path on 4.x clients reports no location for them, so the 
projection flag still changes this one case; setting the flag to false remains 
the rollback.
   
   **Constraints:** The derived path must use Hive's own partition-name 
escaping and lower-case column names, exactly like Partition.initialize, so 
that it equals what the full-fetch path reports.
   
   **Exclusions:**
   - Rewording the pull request description's statement about missing locations 
is left to the author.
   
   **Success:** For a partition whose metastore location is missing, in a table 
that has a location, listPartitionLocations on a Hive 4.x client reports the 
same location with projection enabled and disabled. The projection conversion's 
comments and the shim unit tests describe Hive's default derivation instead of 
claiming that 'no location' matches the full-fetch path.
   
   **Verification:**
   - **Regression:** Feeding a partition with a missing location through the 
projection conversion and through Hive's full-fetch partition construction 
yields the same location from both.
   - **Behavior:** The shim unit tests take their expected locations for 
missing-location response shapes from Hive's own partition construction, not 
from a raw storage descriptor.
   - **Compatibility:** Partitions that have locations, including custom 
locations and string-prefix sibling directories, keep identical specs and 
locations with projection on and off, on every Hive client version.



##########
sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveExternalCatalog.scala:
##########
@@ -1386,6 +1386,25 @@ private[spark] class HiveExternalCatalog(conf: 
SparkConf, hadoopConf: Configurat
     parts.map(restorePartitionMetadata(_, catalogTable))
   }
 
+  override def listPartitionLocations(
+      db: String,
+      table: String,
+      partialSpec: Option[TablePartitionSpec] = None): 
Seq[CatalogTablePartitionLocation] =
+    withClient {
+      val catalogTable = getTable(db, table)
+      val partColNameMap = buildLowerCasePartColNameMap(catalogTable)
+      val metaStoreSpec = partialSpec.map(toMetaStorePartitionSpec)
+      val res = client.getPartitionLocations(db, table, metaStoreSpec)
+        .map { part => part.copy(spec = restorePartitionSpec(part.spec, 
partColNameMap))
+      }
+
+      metaStoreSpec match {
+        case Some(spec) =>

Review Comment:
   **Nit (P3):** For a fully dynamic insert, 
`InsertIntoHadoopFsRelationCommand` passes `Some(Map.empty)`. This branch then 
runs `toMetaStorePartitionSpec`, a few small map allocations, for every 
partition of the table and copies the list. Yet an empty spec pushes no 
metastore filter, and `isPartialPartitionSpec(Map.empty, _)` is always true. 
The cost grows with partition count on exactly the path this PR speeds up. 
Guarding the case keeps the exact post-filter for non-empty specs:
   
   ```suggestion
           case Some(spec) if spec.nonEmpty =>
   ```
   
   **Verification:**
   - **Behavior:** listPartitionLocations returns the same partitions for an 
empty partial spec as for no spec, and a non-empty spec still drops partitions 
that the metastore over-matched.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/catalog/interface.scala:
##########
@@ -267,6 +267,44 @@ case class CatalogTablePartition(
   }
 }
 
+/**
+ * A partition's spec and optional location URI, avoiding the memory and RPC 
overhead of
+ * instantiating a full [[CatalogTablePartition]].
+ *
+ * @param spec partition spec values mapping partition column names to string 
values
+ * @param locationUri optional partition location URI
+ */
+case class CatalogTablePartitionLocation(
+    spec: CatalogTypes.TablePartitionSpec,
+    locationUri: Option[URI] = None) extends MetadataMapSupport {
+
+  def toJsonLinkedHashMap: mutable.LinkedHashMap[String, JValue] = {

Review Comment:
   **Nit (P3):** `toJsonLinkedHashMap` only emits `Partition Values`, and both 
`toString` and `simpleString` are built from it, so the location never appears. 
`toString` also prints `CatalogPartitionLocation(`, which is not the class 
name. For example, `CatalogTablePartitionLocation(Map("p1" -> "1"), Some(new 
URI("file:/a")))` and the same value with `file:/b` both render as 
`CatalogPartitionLocation(Partition Values: [p1=1])`. That makes logs and 
assertion failures from the new projection path useless for diagnosing a wrong 
location. Nothing calls `simpleString`, `toLinkedHashMap` or 
`toJsonLinkedHashMap` on this type. Dropping `MetadataMapSupport` and these 
overrides would restore the generated case-class `toString`, which prints both 
fields under the right name.
   
   **Verification:**
   - **Inspection:** CatalogTablePartitionLocation has no rendering override 
that omits the location, and its string form includes both fields.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/catalog/SessionCatalogSuite.scala:
##########
@@ -1601,6 +1601,24 @@ abstract class SessionCatalogSuite extends AnalysisTest 
with Eventually {
     }
   }
 
+  test("list partition locations") {

Review Comment:
   **Nit (P3):** This test only uses valid specs. `listPartitionLocations` 
duplicates `listPartitions`' `requirePartialMatchedPartitionSpec` and 
`requireNonEmptyValueInPartitionSpec`. `TRUNCATE TABLE ... PARTITION` now 
depends on that copy to reject an empty value, because `TruncateTableCommand` 
only normalizes column names before calling it. The existing invalid-spec tests 
call `listPartitions` only, and no TRUNCATE suite covers an empty value. If the 
copied block were dropped, `TRUNCATE TABLE t PARTITION (p = '')` would hit 
`HiveClientImpl`'s `assert` instead of `INVALID_PARTITION_SPEC`, and every test 
would still pass. Mirroring the `listPartitions` negative cases here (unknown 
column, empty value) would pin the behavior.
   
   **Verification:**
   - **Regression:** listPartitionLocations raises the same 
INVALID_PARTITION_SPEC errors as listPartitions, both for an unknown partition 
column and for an empty partition value.



##########
sql/hive/src/test/scala/org/apache/spark/sql/hive/client/HiveClientSuite.scala:
##########
@@ -731,6 +770,230 @@ class HiveClientSuite(version: String) extends 
HiveVersionSuite(version) {
     }
   }
 
+  test("INSERT OVERWRITE a partition with a custom location uses the location 
reported by " +
+      "getPartitionLocations") {
+    // Only Shim_v4_0 (and its 4.1/4.2 descendants) implement partition 
projection via
+    // getPartitionsWithSpecs; earlier shims fall back to the plain 
getPartitions-based
+    // implementation, which this test is not meant to exercise.
+    withTable("custom_loc_tbl") {
+      withTempDir { partDir =>
+        versionSpark.sql(
+          "CREATE TABLE custom_loc_tbl(c1 int, p1 int) USING PARQUET 
PARTITIONED BY (p1)")
+        versionSpark.sql("INSERT INTO custom_loc_tbl PARTITION (p1 = 1) VALUES 
(10)")
+        versionSpark.sql(
+          s"ALTER TABLE custom_loc_tbl PARTITION (p1 = 1) SET LOCATION 
'${partDir.toURI}'")
+
+        val parts = versionSpark.sessionState.catalog.listPartitionLocations(
+          TableIdentifier("custom_loc_tbl"))
+        assert(parts.length == 1)
+        assert(parts.head.locationUri.map(_.toString.stripSuffix("/")) ==
+          Some(partDir.toURI.toString.stripSuffix("/")))
+
+        // This overwrite must resolve the partition's custom location via
+        // getCustomPartitionLocations, which depends on 
Shim_v4_0.getPartitionLocations
+        // correctly reporting the post-ALTER location rather than the table's 
default path.
+        versionSpark.sql("INSERT OVERWRITE TABLE custom_loc_tbl PARTITION (p1 
= 1) VALUES (20)")
+        assert(versionSpark.table("custom_loc_tbl").collect().toSeq == 
Seq(Row(20, 1)))
+        assert(partDir.listFiles().exists(_.getName.startsWith("part-")))
+
+        // A second overwrite must delete-and-rewrite the same custom 
directory again, proving
+        // the custom location is resolved correctly on every call, not just 
the first one.
+        versionSpark.sql("INSERT OVERWRITE TABLE custom_loc_tbl PARTITION (p1 
= 1) VALUES (30)")
+        assert(versionSpark.table("custom_loc_tbl").collect().toSeq == 
Seq(Row(30, 1)))
+        assert(partDir.listFiles().count(_.getName.startsWith("part-")) == 1)
+      }
+    }
+  }
+
+  test("getPartitionLocations resolves a partition location that shares a 
string prefix " +
+      "with the table's own location") {
+    // Guards against a bug in Shim_v4_0.getPartitionLocations (and, 
previously, getPartitions):
+    // the metastore's 
MetaStoreServerUtils.getPartitionspecsGroupedByStorageDescriptor groups a
+    // partition into a PartitionSpecWithSharedSD whenever its location has 
the table's own
+    // location as a *string* prefix -- a plain String.startsWith check, not 
path-boundary aware.
+    // A sibling directory like "<tableLocation>_external" matches that check 
even though it is
+    // not actually nested under the table, so the metastore encodes it as a 
relativePath with no
+    // leading separator (e.g. "_external/p1=1"). Hive's own client-side 
reconstruction
+    // (PartitionSpecWithSharedSDProxy.Iterator.getCurrent) undoes this with 
plain string
+    // concatenation, not by joining root and relPath as filesystem path 
segments --
+    // normalizeLocation must match that exactly or it silently computes the 
wrong location.
+    withTempDir { baseDir =>
+      val tableDir = new File(baseDir, "prefix_collision_tbl")
+      val siblingDir = new File(baseDir, "prefix_collision_tbl_external")
+      withTable("prefix_collision_tbl") {
+        versionSpark.sql(
+          s"""
+             |CREATE TABLE prefix_collision_tbl(c1 int, p1 int)
+             |USING PARQUET PARTITIONED BY (p1)
+             |LOCATION '${tableDir.toURI}'
+           """.stripMargin)
+        versionSpark.sql("INSERT INTO prefix_collision_tbl PARTITION (p1 = 1) 
VALUES (10)")
+        versionSpark.sql(
+          s"ALTER TABLE prefix_collision_tbl PARTITION (p1 = 1) SET LOCATION " 
+
+            s"'${siblingDir.toURI}'")
+
+        val parts = versionSpark.sessionState.catalog.listPartitionLocations(
+          TableIdentifier("prefix_collision_tbl"))
+        assert(parts.length == 1)
+        assert(parts.head.locationUri.map(_.toString.stripSuffix("/")) ==
+          Some(siblingDir.toURI.toString.stripSuffix("/")))
+
+        // This overwrite must resolve the partition's custom location via
+        // getCustomPartitionLocations; if normalizeLocation miscomputed the 
location, this
+        // would either write to the wrong (likely non-existent) directory or 
throw.
+        versionSpark.sql(
+          "INSERT OVERWRITE TABLE prefix_collision_tbl PARTITION (p1 = 1) 
VALUES (20)")
+        assert(versionSpark.table("prefix_collision_tbl").collect().toSeq == 
Seq(Row(20, 1)))
+        assert(siblingDir.exists() && 
siblingDir.listFiles().exists(_.getName.startsWith("part-")))
+      }
+    }
+  }
+
+  test("listPartitionLocations and INSERT OVERWRITE with partition specs") {
+    assume(version.startsWith("4."))
+    withTable("spec_part_tbl") {
+      versionSpark.sql(
+        "CREATE TABLE spec_part_tbl(c1 int, p1 int, p2 int) " +
+        "USING PARQUET PARTITIONED BY (p1, p2)")
+      versionSpark.sql(
+        "INSERT INTO spec_part_tbl PARTITION (p1 = 1, p2 = 1) VALUES (10)")
+      versionSpark.sql(
+        "INSERT INTO spec_part_tbl PARTITION (p1 = 1, p2 = 2) VALUES (20)")
+      versionSpark.sql(
+        "INSERT INTO spec_part_tbl PARTITION (p1 = 2, p2 = 1) VALUES (30)")
+      versionSpark.sql(
+        "INSERT INTO spec_part_tbl PARTITION (p1 = 2, p2 = 2) VALUES (40)")
+      // Verify integer key p1=1 does not over-match p1=10 via trailing 
wildcard without slash

Review Comment:
   **Nit (P3):** These assertions go through 
`SessionCatalog.listPartitionLocations`, and 
`HiveExternalCatalog.listPartitionLocations` drops every result that doesn't 
exactly match the partial spec (`isPartialPartitionSpec`). If 
`byValuesFilterSpec` stopped padding and sent `['1']`, the metastore's matcher 
would also return `p1=10/p2=1`, the post-filter would remove it, and this test 
would still pass. Results stay correct, but the extra metastore payload the 
padding avoids would come back silently, and so would the inflated 
fetched-partition metric, which counts before the post-filter. The 
`HiveClient`-level tests use `src_part`, whose only partitions are 
`key1=1/key2=1` and `key1=1/key2=2`, so they can't catch it either. A 4.x 
assertion on `client.getPartitionLocations` for a table with `p1=1` and `p1=10` 
would.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58984#discussion_r4262017858).
   
   **Verification:**
   - **Regression:** A client-level listing for p1=1 on Hive 4.x returns only 
the p1=1 partitions, and it would return a p1=10 partition if the padding of 
unspecified columns were removed.



##########
sql/hive/src/test/scala/org/apache/spark/sql/hive/client/HiveClientSuite.scala:
##########
@@ -731,6 +770,230 @@ class HiveClientSuite(version: String) extends 
HiveVersionSuite(version) {
     }
   }
 
+  test("INSERT OVERWRITE a partition with a custom location uses the location 
reported by " +
+      "getPartitionLocations") {
+    // Only Shim_v4_0 (and its 4.1/4.2 descendants) implement partition 
projection via
+    // getPartitionsWithSpecs; earlier shims fall back to the plain 
getPartitions-based
+    // implementation, which this test is not meant to exercise.

Review Comment:
   **Nit (P3):** This test has no `assume(version.startsWith("4."))`, unlike 
the two projection tests further down. `HiveClientSuite` therefore runs it for 
every client from 2.0 to 4.2, including the `getPartitions`-based path this 
comment says it is not meant to exercise. Similarly, the comment on the 
string-prefix location test below says it guards a bug in '(and, previously, 
getPartitions)'. But no `getPartitions` implementation rebuilds locations from 
`get_partitions_with_specs`, on the base branch or here: every shim's 
`getPartitions` is still `Shim_v2_0`'s `hive.getPartitions` call. Both comments 
look left over from an earlier revision. Rewording them, or adding the guard if 
pre-4.0 coverage is not wanted, would keep readers from changing version guards 
for the wrong reason.
   
   **Verification:**
   - **Inspection:** Neither comment restricts its test to the Hive 4.x shims, 
and neither attributes a bug to getPartitions.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to