Copilot commented on code in PR #6585:
URL: https://github.com/apache/hive/pull/6585#discussion_r3540939971


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/ObjectStore.java:
##########
@@ -412,31 +410,26 @@ public boolean openTransaction() {
     return result;
   }
 
-  @SuppressWarnings("unchecked")
+  @SuppressWarnings("unchecked, rawtypes")
   @Override
   public <T> T unwrap(Class<T> iface) {
     MetaDescriptor descriptor = iface.getAnnotation(MetaDescriptor.class);
     if (descriptor == null) {
       throw new IllegalArgumentException("Unable to unwrap the store as " + 
iface);
     }
-    String implClassName = conf.get("metastore." + descriptor.alias() + 
".store.impl", "");
-    T simpl;
-    T impl = (T) cachedImpls.get(iface);
-    if (impl != null &&
-        (StringUtils.isEmpty(implClassName) || 
impl.getClass().getName().equals(implClassName))) {
-      simpl = impl;
-    } else {
-      Class<?> ifaceImpl = descriptor.defaultImpl();
-      if (StringUtils.isNotEmpty(implClassName)) {
-        ifaceImpl = conf.getClass(implClassName, ifaceImpl);
-      }
-      simpl = (T) JavaUtils.newInstance(ifaceImpl);
-      cachedImpls.put(iface, simpl);
+    String implClassName =
+        conf.get("metastore." + descriptor.alias() + ".store.impl", "");
+    Class<?> ifaceImpl = descriptor.defaultImpl();
+    if (StringUtils.isNotEmpty(implClassName)) {
+      ifaceImpl = conf.getClass(implClassName, ifaceImpl);
     }
+    T simpl = (T) JavaUtils.newInstance(ifaceImpl);
     List<Query> openQueries = new LinkedList<>();
     if (simpl instanceof RawStoreBundle rsb) {
       rsb.setBaseStore(this);
-      rsb.setPersistentManager(PersistenceManagerProxy.getProxy(pm, 
openQueries));
+      if (pm != null) {
+        rsb.setPersistentManager(PersistenceManagerProxy.getProxy(pm, 
openQueries));
+      }

Review Comment:
   `unwrap()` can return a RawStoreBundle without a PersistenceManager when 
`pm` is null (e.g., after `shutdown()`), but the returned proxy will still 
attempt to open transactions and will NPE later. It’s safer to fail fast (or 
always set the PM proxy) so callers get an actionable error instead of a 
delayed null dereference.



##########
standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/metastore/TestObjectStoreUnwrap.java:
##########
@@ -0,0 +1,325 @@
+/*
+ * 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.hadoop.hive.metastore.metastore;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.metastore.Deadline;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.MetaStoreTestUtils;
+import org.apache.hadoop.hive.metastore.ObjectStore;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.annotation.MetastoreUnitTest;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.client.builder.DatabaseBuilder;
+import org.apache.hadoop.hive.metastore.client.builder.GetPartitionsArgs;
+import org.apache.hadoop.hive.metastore.client.builder.PartitionBuilder;
+import org.apache.hadoop.hive.metastore.client.builder.TableBuilder;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
+import org.apache.hadoop.hive.metastore.metastore.iface.TableStore;
+import org.apache.hadoop.hive.metastore.utils.DirectSqlConfigurator;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.lang.reflect.Proxy;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+
+import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_CATALOG_NAME;
+
+@Category(MetastoreUnitTest.class)
+public class TestObjectStoreUnwrap {
+  private static final String DB = "unwrap_proxy_db";
+  private static final String TABLE = "unwrap_proxy_tbl";
+
+  private ObjectStore objectStore;
+  private Configuration conf;
+  private TableName tableName;
+
+  @Before
+  public void setUp() throws Exception {
+    conf = MetastoreConf.newMetastoreConf();
+    MetastoreConf.setBoolVar(conf, ConfVars.HIVE_IN_TEST, true);
+    MetaStoreTestUtils.setConfForStandloneMode(conf);
+
+    String currentUrl = MetastoreConf.getVar(conf, ConfVars.CONNECT_URL_KEY);
+    currentUrl = currentUrl.replace(MetaStoreServerUtils.JUNIT_DATABASE_PREFIX,
+        String.format("%s_%s", MetaStoreServerUtils.JUNIT_DATABASE_PREFIX, 
UUID.randomUUID()));
+    MetastoreConf.setVar(conf, ConfVars.CONNECT_URL_KEY, currentUrl);
+
+    objectStore = new ObjectStore();
+    objectStore.setConf(conf);
+    HMSHandler.createDefaultCatalog(objectStore, new Warehouse(conf));
+    tableName = new TableName(DEFAULT_CATALOG_NAME, DB, TABLE);
+    createPartitionedTable();
+  }
+
+  @Test
+  public void testQueryClosedAfterRead() throws Exception {
+    TableStore tableStore = objectStore.unwrap(TableStore.class);
+    TransactionHandler<?> handler = getHandler(tableStore);
+    GetPartitionsArgs args = new 
GetPartitionsArgs.GetPartitionsArgsBuilder().max(10).build();
+
+    try (AutoCloseable ignored = deadline();
+         DirectSqlConfigurator directSql = new DirectSqlConfigurator(conf, 
false)) {
+      List<Partition> partitions = tableStore.getPartitions(tableName, args);
+      Assert.assertEquals(3, partitions.size());
+    }
+
+    Assert.assertEquals(0, handler.getOpenQueryCount());
+    Assert.assertFalse(objectStore.isActiveTransaction());
+  }
+
+  @Test
+  public void testQueryClosedAfterDelete() throws Exception {
+    TableStore tableStore = objectStore.unwrap(TableStore.class);
+    TransactionHandler<?> handler = getHandler(tableStore);
+
+    try (AutoCloseable ignored = deadline();
+         DirectSqlConfigurator directSql = new DirectSqlConfigurator(conf, 
false)) {
+      tableStore.dropPartitions(tableName, Arrays.asList("test_part_col=a0", 
"test_part_col=a1"));
+    }
+
+    Assert.assertEquals(0, handler.getOpenQueryCount());
+    Assert.assertFalse(objectStore.isActiveTransaction());
+
+    try (AutoCloseable ignored = deadline();
+         DirectSqlConfigurator directSql = new DirectSqlConfigurator(conf, 
false)) {
+      Assert.assertEquals(1, tableStore.getPartitions(tableName,
+          new 
GetPartitionsArgs.GetPartitionsArgsBuilder().max(10).build()).size());
+    }
+    Assert.assertEquals(0, handler.getOpenQueryCount());
+  }
+
+  @Test
+  public void testRepeatedUnwrapNoLeaks() throws Exception {
+    GetPartitionsArgs args = new 
GetPartitionsArgs.GetPartitionsArgsBuilder().max(10).build();
+    try (AutoCloseable ignored = deadline();
+         DirectSqlConfigurator directSql = new DirectSqlConfigurator(conf, 
false)) {
+      for (int i = 0; i < 5; i++) {
+        TableStore tableStore = objectStore.unwrap(TableStore.class);
+        TransactionHandler<?> handler = getHandler(tableStore);
+        Assert.assertEquals(3, tableStore.getPartitions(tableName, 
args).size());
+        Assert.assertEquals("queries leaked on iteration " + i, 0, 
handler.getOpenQueryCount());
+      }
+    }
+    Assert.assertFalse(objectStore.isActiveTransaction());
+  }
+
+  @Test
+  public void testProxiesReadThenDelete() throws Exception {
+    TableStore readProxy = objectStore.unwrap(TableStore.class);
+    TableStore deleteProxy = objectStore.unwrap(TableStore.class);
+    Assert.assertNotSame(readProxy, deleteProxy);
+
+    TransactionHandler<?> readHandler = getHandler(readProxy);
+    TransactionHandler<?> deleteHandler = getHandler(deleteProxy);
+    GetPartitionsArgs args = new 
GetPartitionsArgs.GetPartitionsArgsBuilder().max(10).build();
+
+    try (AutoCloseable ignored = deadline();
+         DirectSqlConfigurator directSql = new DirectSqlConfigurator(conf, 
false)) {
+      Assert.assertEquals(3, readProxy.getPartitions(tableName, args).size());
+      Assert.assertEquals(0, readHandler.getOpenQueryCount());
+
+      Assert.assertEquals(3, deleteProxy.getPartitions(tableName, 
args).size());
+      Assert.assertEquals(0, deleteHandler.getOpenQueryCount());
+

Review Comment:
   The proxy-leak regression this test targets happens when one proxy’s calls 
start registering queries in the *other* proxy’s `openQueries` list (due to 
shared underlying impl state). To actually detect that, assert that the *other* 
handler’s query list stays empty immediately after each proxy call (before the 
other proxy has a chance to clear it).



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metastore/impl/TableStoreImpl.java:
##########
@@ -2213,8 +2215,8 @@ public List<Partition> listPartitionsPsWithAuth(TableName 
tableName, GetPartitio
       for (Partition part : partitions) {
         String partName = Warehouse.makePartName(convertToFieldSchemas(mtbl
             .getPartitionKeys()), part.getValues());
-        PrincipalPrivilegeSet partAuth = 
baseStore.getPartitionPrivilegeSet(catName, dbName,
-            tblName, partName, userName, groupNames);
+        PrincipalPrivilegeSet partAuth = siblingStore(PrivilegeStore.class)
+            .getPartitionPrivilegeSet(new TableName(catName, dbName, tblName), 
partName, userName, groupNames);

Review Comment:
   `siblingStore(PrivilegeStore.class)` is called once per partition, which 
will repeatedly create new proxies/handlers now that `unwrap()` no longer 
caches implementations. Hoist the sibling store outside the loop and reuse it 
to avoid unnecessary proxy construction.



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metastore/impl/ColStatsStoreImpl.java:
##########
@@ -942,12 +943,12 @@ protected Integer getSqlResult() throws MetaException {
       @Override
       protected Integer getJdoResult() throws MetaException, 
NoSuchObjectException {
         try {
-          List<Partition> parts = baseStore.unwrap(TableStore.class)
+          List<Partition> parts = siblingStore(TableStore.class)
               .getPartitions(tn, GetPartitionsArgs.getAllPartitions());
           for (Partition part : parts) {
             Partition newPart = new Partition(part);
             StatsSetupConst.clearColumnStatsState(newPart.getParameters());

Review Comment:
   Inside the loop, `siblingStore(TableStore.class)` is called for every 
partition, which now constructs a fresh proxy each time. Reuse a single 
`TableStore` instance for the duration of this method to reduce allocations and 
reflective proxy overhead.



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metastore/impl/PrivilegeStoreImpl.java:
##########
@@ -891,14 +891,15 @@ public boolean grantPrivileges(PrivilegeBag privileges) 
throws InvalidObjectExce
             }
           }
         } else if (hiveObject.getObjectType() == HiveObjectType.COLUMN) {
-          MTable tblObj = baseStore.ensureGetMTable(catName, 
hiveObject.getDbName(), hiveObject
-              .getObjectName());
+          MTable tblObj = siblingStore(TableStore.class)
+              .ensureGetMTable(new TableName(catName, hiveObject.getDbName(), 
hiveObject.getObjectName()));
           if (tblObj != null) {
             if (hiveObject.getPartValues() != null) {
               MPartition partObj = null;

Review Comment:
   `siblingStore(TableStore.class)` is invoked multiple times in this branch, 
which repeatedly builds new proxies/handlers now that `ObjectStore.unwrap()` no 
longer caches implementations. Hoisting the sibling store into a local variable 
avoids repeated proxy construction while keeping the per-invocation isolation 
that prevents query leaks.



-- 
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