You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@hive.apache.org by "vikramahuja1001 (via GitHub)" <gi...@apache.org> on 2026/07/16 08:09:24 UTC

[PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

vikramahuja1001 opened a new pull request, #6610:
URL: https://github.com/apache/hive/pull/6610

   
   
   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://cwiki.apache.org/confluence/display/Hive/HowToContribute
     2. Ensure that you have created an issue on the Hive project JIRA: https://issues.apache.org/jira/projects/HIVE/summary
     3. Ensure you have added or run the appropriate tests for your PR: 
     4. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP]HIVE-XXXXX:  Your PR title ...'.
     5. Be sure to keep the PR description updated to reflect all changes.
     6. Please write your PR title to summarize what this PR proposes.
     7. If possible, provide a concise example to reproduce the issue for a faster review.
   
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description, screenshot and/or a reproducable example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Hive versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   -->
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "vikramahuja1001 (via GitHub)" <gi...@apache.org>.
vikramahuja1001 commented on PR #6610:
URL: https://github.com/apache/hive/pull/6610#issuecomment-4993710982

   @deniskuzZ / @ayushtkn / @zabetak/ @saihemanth-cloudera  Can you help to review this PR? Thanks.


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "vikramahuja1001 (via GitHub)" <gi...@apache.org>.
vikramahuja1001 commented on code in PR #6610:
URL: https://github.com/apache/hive/pull/6610#discussion_r3598302539


##########
ql/src/test/org/apache/hadoop/hive/ql/security/authorization/plugin/TestAuthorizationMetaStoreFilterHook.java:
##########
@@ -0,0 +1,333 @@
+/*
+ * 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.ql.security.authorization.plugin;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for {@link AuthorizationMetaStoreFilterHook#filterTables}.
+ *
+ * Validates correctness of the O(n) HashMap-based fix replacing the original
+ * O(n^2) nested-loop implementation, including catName null-handling logic.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class TestAuthorizationMetaStoreFilterHook {
+
+  private AuthorizationMetaStoreFilterHook hook;
+  private MockedStatic<SessionState> mockedSessionState;
+
+  @Mock private SessionState sessionState;
+  @Mock private HiveAuthorizer authorizer;
+
+  @Before
+  public void setUp() {
+    hook = new AuthorizationMetaStoreFilterHook(new Configuration());
+    when(sessionState.getUserIpAddress()).thenReturn("127.0.0.1");
+    when(sessionState.getForwardedAddresses()).thenReturn(Collections.emptyList());
+    when(sessionState.getAuthorizerV2()).thenReturn(authorizer);
+    mockedSessionState = mockStatic(SessionState.class);
+    mockedSessionState.when(SessionState::get).thenReturn(sessionState);
+  }
+
+  @After
+  public void tearDown() {
+    mockedSessionState.close();
+  }
+
+  // ── helpers ────────────────────────────────────────────────────────────────
+
+  /** Create a Table with catName. */
+  private Table createTable(String catName, String dbName, String tableName) {
+    Table table = new Table();
+    table.setCatName(catName);
+    table.setDbName(dbName);
+    table.setTableName(tableName);
+    table.setOwner("testowner");
+    table.setOwnerType(PrincipalType.USER);
+    return table;
+  }
+
+  /** Create a Table without catName (catName = null). */
+  private Table createTable(String dbName, String tableName) {
+    return createTable(null, dbName, tableName);
+  }
+
+  /**
+   * Stub authorizer to return HivePrivilegeObjects with the given catName
+   * for tables matching dbName + any of the allowedTableNames.
+   */
+  private void allowTablesWithCatName(String catName, String dbName, String... allowedTableNames)
+       throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+    List<HivePrivilegeObject> input = invocation.getArgument(0);
+    List<HivePrivilegeObject> result = new ArrayList<>();
+    Set<String> seen = new HashSet<>();
+      for (HivePrivilegeObject obj : input) {
+        for (String allowed : allowedTableNames) {
+          if (dbName.equals(obj.getDbname()) && allowed.equals(obj.getObjectName())) {
+            String key = (catName != null ? catName : "") + "\0" + dbName + "\0" + allowed;
+              if (seen.add(key)) {
+                result.add(new HivePrivilegeObject(
+                  HivePrivilegeObject.HivePrivilegeObjectType.TABLE_OR_VIEW, catName, dbName, allowed));
+              }
+            break;
+          }
+        }
+      }
+      return result;
+    });
+  }
+
+  /** Stub authorizer to return all objects unchanged (allow all, catName stays null). */
+  private void allowAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));
+  }
+
+  /** Stub authorizer to deny everything. */
+  private void denyAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenReturn(Collections.emptyList());
+  }
+
+  // ── existing tests (no catName) ────────────────────────────────────────────
+
+  @Test
+  public void testFilterTables_emptyInput() throws Exception {
+    denyAll();
+    List<Table> result = hook.filterTables(Collections.emptyList());
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_allAllowed() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+    allowAll();
+    List<Table> result = hook.filterTables(input);
+    assertEquals(3, result.size());
+  }
+
+  @Test
+  public void testFilterTables_allFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"));
+    denyAll();
+    List<Table> result = hook.filterTables(input);
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_someFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+      // authorize returns tbl1 and tbl3 with null catName
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+      List<HivePrivilegeObject> objs = invocation.getArgument(0);
+      return objs.stream()
+                    .filter(o -> "tbl1".equals(o.getObjectName()) || "tbl3".equals(o.getObjectName()))
+                    .collect(Collectors.toList());
+    });
+    List<Table> result = hook.filterTables(input);
+    assertEquals(2, result.size());
+    List<String> names = result.stream().map(Table::getTableName).collect(Collectors.toList());
+    assertTrue(names.contains("tbl1"));
+    assertTrue(names.contains("tbl3"));
+  }
+
+  // ── catName-specific tests ─────────────────────────────────────────────────
+
+  /**
+   * Case 1: obj.catName == null → must match a table that also has null catName.
+   * Note: HivePrivilegeObject normalizes null catName to the default catalog ("hive"),
+   * so the null-catName-obj path in production code is unreachable in practice.
+   * The live equivalent is tested via testFilterTables_tableCatNameNull_matchesObjWithNonNullCatName.
+   */
+  @Test
+  public void testFilterTables_objCatNameNull_matchesTableWithNullCatName() throws Exception {
+    List<Table> input = List.of(createTable(null, "db1", "tbl1"));
+    allowTablesWithCatName(null, "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertEquals("obj with null catName should match table with null catName", 1, result.size());
+  }
+
+  /**
+   * Case 2: obj.catName != null but table.catName == null → still matches.
+   * Original logic: condition `table.getCatName() != null` is false → skip the check.
+   */
+  @Test
+  public void testFilterTables_tableCatNameNull_matchesObjWithNonNullCatName() throws Exception {
+    List<Table> input = List.of(createTable(null, "db1", "tbl1")); // table has null catName
+    // authorizer returns obj with catName = "cat1"
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertEquals("table with null catName should match obj with any catName", 1, result.size());
+  }
+
+  /**
+   * Case 3: obj.catName != null, table.catName != null, and they match → matches.
+   */
+  @Test
+  public void testFilterTables_sameCatName_matches() throws Exception {
+    List<Table> input = List.of(createTable("cat1", "db1", "tbl1"));
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertEquals("same catName on obj and table should match", 1, result.size());
+    assertEquals("cat1", result.get(0).getCatName());
+  }
+
+  /**
+   * Both obj.catName and table.catName are non-null but DIFFERENT → no match.
+   * Original logic: condition is true → continue (skip).
+   */
+  @Test
+  public void testFilterTables_differentCatName_noMatch() throws Exception {
+    List<Table> input = List.of(createTable("cat2", "db1", "tbl1")); // table has cat2
+    // authorizer says tbl1 is allowed but with catName=cat1
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertTrue("obj.catName=cat1 vs table.catName=cat2 should not match", result.isEmpty());
+  }
+
+  /**
+   * Multiple catalogs, same db+table name.
+   * obj.catName=cat1 should return only the cat1 table, not cat2.
+   */
+  @Test
+  public void testFilterTables_multipleCatalogs_sameDbTable_exactCatNameMatch() throws Exception {
+    Table cat1Table = createTable("cat1", "db1", "tbl1");
+    Table cat2Table = createTable("cat2", "db1", "tbl1");
+    List<Table> input = List.of(cat1Table, cat2Table);
+
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+
+    List<Table> result = hook.filterTables(input);
+
+    assertEquals("Only cat1 table should be returned", 1, result.size());
+    assertEquals("cat1", result.get(0).getCatName());
+  }
+
+  /**
+   * obj.catName != null, no exact catName match exists, but a table with
+   * null catName exists → that null-catName table should be returned.
+   */
+  @Test
+  public void testFilterTables_noExactCatMatch_fallsBackToNullCatTable() throws Exception {
+    Table nullCatTable = createTable(null, "db1", "tbl1");  // catName = null
+    Table cat2Table    = createTable("cat2", "db1", "tbl1"); // catName = cat2
+    List<Table> input  = List.of(nullCatTable, cat2Table);
+
+    // obj requests catName=cat1 but no cat1 table exists; null-catName table should match
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+
+    List<Table> result = hook.filterTables(input);
+
+    assertEquals("null-catName table should match obj with non-null catName", 1, result.size());
+    assertEquals(null, result.get(0).getCatName());
+  }
+
+  /**
+   * Mixed: some tables have catName, some don't; some objs have catName, some don't.
+   */
+  @Test
+  public void testFilterTables_mixed_catNameCombinations() throws Exception {
+    List<Table> input = List.of(
+      createTable("cat1", "db1", "tbl1"),  // exact catName match
+      createTable(null,   "db1", "tbl2"),  // null catName — matches any obj catName
+      createTable("cat2", "db1", "tbl3"));   // catName=cat2, obj will request cat1 → no match
+
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+      // return 3 objs: tbl1(cat1), tbl2(cat1), tbl3(cat1)
+      List<HivePrivilegeObject> result = new ArrayList<>();
+      for (String tbl : List.of("tbl1", "tbl2", "tbl3")) {
+        HivePrivilegeObject obj = new HivePrivilegeObject(
+                      HivePrivilegeObject.HivePrivilegeObjectType.TABLE_OR_VIEW, "cat1", "db1", tbl);
+        result.add(obj);
+        }
+      return result;
+    });
+
+    List<Table> result = hook.filterTables(input);
+
+    List<String> names = result.stream().map(Table::getTableName).collect(Collectors.toList());
+    assertEquals("Should return tbl1 (exact) and tbl2 (null catName fallback)", 2, result.size());
+    assertTrue(names.contains("tbl1")); // cat1 == cat1 → match
+    assertTrue(names.contains("tbl2")); // null catName → match
+    assertTrue(!names.contains("tbl3")); // cat2 != cat1 → no match
+  }
+
+  // ── performance test ───────────────────────────────────────────────────────
+
+  /**
+   * 1 lakh tables must complete within 5 seconds.
+   * The original O(n^2) implementation would take 200-300 seconds.
+   * Note: uses inline time assertion instead of @Test(timeout) to avoid JUnit 4's
+   * separate-thread execution, which breaks Mockito's ThreadLocal-based MockedStatic.
+   */
+  @Test
+  public void testFilterTables_performance_100kTables() throws Exception {

Review Comment:
   Will handle it as a part of a follow up JIRA if that's okay since it is a reasonable scope for a separate JIRA itself?



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "vikramahuja1001 (via GitHub)" <gi...@apache.org>.
vikramahuja1001 commented on code in PR #6610:
URL: https://github.com/apache/hive/pull/6610#discussion_r3598291076


##########
ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/AuthorizationMetaStoreFilterHook.java:
##########
@@ -56,43 +59,88 @@ public List<String> filterTableNames(String catName, String dbName, List<String>
     return getFilteredObjectNames(getFilteredObjects(listObjs));
   }
 
+  /**
+   * Filters the given list of tables down to those the current user is authorized to see.
+   *
+   * <p>The method delegates authorization decisions to {@link HiveAuthorizer#filterListCmdObjects},

Review Comment:
   Have reused TablePrivilegeLookup and refactored the code.



##########
ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/AuthorizationMetaStoreFilterHook.java:
##########
@@ -56,43 +59,88 @@ public List<String> filterTableNames(String catName, String dbName, List<String>
     return getFilteredObjectNames(getFilteredObjects(listObjs));
   }
 
+  /**
+   * Filters the given list of tables down to those the current user is authorized to see.
+   *
+   * <p>The method delegates authorization decisions to {@link HiveAuthorizer#filterListCmdObjects},
+   * then maps the returned {@link HivePrivilegeObject}s back to the original {@link Table} objects.
+   * The mapping is O(n) using pre-built HashMaps, replacing an earlier O(n²) nested-loop
+   * implementation that was prohibitively slow for large table lists.
+   *
+   * <p>Catalog-name matching preserves the semantics of the original code across three cases:
+   * <ol>
+   *   <li><b>obj.catName == null</b> — the privilege object carries no catalog constraint;
+   *       the first table in the input list with the matching db+table name is returned,
+   *       regardless of that table's catName.</li>
+   *   <li><b>obj.catName != null, table.catName == null</b> — a table that was stored without
+   *       a catalog name is treated as a wildcard and matches any privilege object catName
+   *       when no exact-catName table is found.</li>
+   *   <li><b>obj.catName != null, table.catName != null</b> — both sides must match exactly;
+   *       if they differ the table is excluded.</li>
+   * </ol>
+   *
+   * @param tableList the full list of tables returned by the MetaStore before authorization
+   * @return the sub-list of tables the current user is permitted to list
+   * @throws MetaException if the authorizer throws an exception
+   */
   @Override
   public List<Table> filterTables(List<Table> tableList) throws MetaException {
     List<HivePrivilegeObject> listObjs = tablesToPrivilegeObjs(tableList);
-    return getFilteredTableList(getFilteredObjects(listObjs),tableList);
-  }
+    List<HivePrivilegeObject> filteredObjs = getFilteredObjects(listObjs);
 
-  private List<Table> getFilteredTableList(List<HivePrivilegeObject> hivePrivilegeObjects, List<Table> tableList) {
-    List<Table> ret = new ArrayList<>();
-    for(HivePrivilegeObject hivePrivilegeObject:hivePrivilegeObjects) {
-      String catName = hivePrivilegeObject.getCatName();
-      String dbName  = hivePrivilegeObject.getDbname();
-      String tblName = hivePrivilegeObject.getObjectName();
-      Table  table   = getFilteredTable(catName, dbName, tblName, tableList);
-      if (table != null) {
-        ret.add(table);
+    // Map 1: catName + dbName + tblName  →  exact catName match (case 3)
+    Map<String, Table> fullKeyMap = new HashMap<>(tableList.size() * 2);
+
+    // Map 2: dbName + tblName  →  first table regardless of catName (case 1: obj.catName == null)
+    Map<String, Table> anyMap = new HashMap<>(tableList.size() * 2);
+
+    // Map 3: dbName + tblName  →  first table where table.catName == null (case 2)
+    Map<String, Table> nullCatMap = new HashMap<>();
+
+    for (Table table : tableList) {
+      String partKey = dbTableKey(table.getDbName(), table.getTableName());
+      String fullKey = catDbTableKey(table.getCatName(), table.getDbName(), table.getTableName());
+
+      fullKeyMap.put(fullKey, table);
+      anyMap.putIfAbsent(partKey, table);           // first match wins
+      if (table.getCatName() == null) {
+        nullCatMap.putIfAbsent(partKey, table);   // only null-catName tables
       }
     }
-    return ret;
-  }
 
-  private Table getFilteredTable(String catName, String dbName, String tblName, List<Table> tableList) {
-    Table ret = null;
-    for (Table table: tableList) {
-      // do not check catalog name if catName is null
-      if (catName != null && table.getCatName() != null && !catName.equals(table.getCatName())) {
-        continue;
+    List<Table> ret = new ArrayList<>(filteredObjs.size());
+    for (HivePrivilegeObject obj : filteredObjs) {
+      Table table;
+      String partKey = dbTableKey(obj.getDbname(), obj.getObjectName());
+
+      if (obj.getCatName() == null) {

Review Comment:
   Have refactored the code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6610:
URL: https://github.com/apache/hive/pull/6610#issuecomment-4999199012

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6610) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [38 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6610&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6610&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6610&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6610&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6610&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6610)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "vikramahuja1001 (via GitHub)" <gi...@apache.org>.
vikramahuja1001 commented on PR #6610:
URL: https://github.com/apache/hive/pull/6610#issuecomment-5019795676

   Thanks for the reviews @dengzhhu653 , @saihemanth-cloudera . Could you also please merge this PR? Thanks


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6610:
URL: https://github.com/apache/hive/pull/6610#issuecomment-4992776055

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6610) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [175 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6610&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6610&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6610&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6610&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6610&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6610)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "saihemanth-cloudera (via GitHub)" <gi...@apache.org>.
saihemanth-cloudera commented on code in PR #6610:
URL: https://github.com/apache/hive/pull/6610#discussion_r3597764922


##########
ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/AuthorizationMetaStoreFilterHook.java:
##########
@@ -56,43 +59,88 @@ public List<String> filterTableNames(String catName, String dbName, List<String>
     return getFilteredObjectNames(getFilteredObjects(listObjs));
   }
 
+  /**
+   * Filters the given list of tables down to those the current user is authorized to see.
+   *
+   * <p>The method delegates authorization decisions to {@link HiveAuthorizer#filterListCmdObjects},
+   * then maps the returned {@link HivePrivilegeObject}s back to the original {@link Table} objects.
+   * The mapping is O(n) using pre-built HashMaps, replacing an earlier O(n²) nested-loop
+   * implementation that was prohibitively slow for large table lists.
+   *
+   * <p>Catalog-name matching preserves the semantics of the original code across three cases:
+   * <ol>
+   *   <li><b>obj.catName == null</b> — the privilege object carries no catalog constraint;
+   *       the first table in the input list with the matching db+table name is returned,
+   *       regardless of that table's catName.</li>
+   *   <li><b>obj.catName != null, table.catName == null</b> — a table that was stored without
+   *       a catalog name is treated as a wildcard and matches any privilege object catName
+   *       when no exact-catName table is found.</li>
+   *   <li><b>obj.catName != null, table.catName != null</b> — both sides must match exactly;
+   *       if they differ the table is excluded.</li>
+   * </ol>
+   *
+   * @param tableList the full list of tables returned by the MetaStore before authorization
+   * @return the sub-list of tables the current user is permitted to list
+   * @throws MetaException if the authorizer throws an exception
+   */
   @Override
   public List<Table> filterTables(List<Table> tableList) throws MetaException {
     List<HivePrivilegeObject> listObjs = tablesToPrivilegeObjs(tableList);
-    return getFilteredTableList(getFilteredObjects(listObjs),tableList);
-  }
+    List<HivePrivilegeObject> filteredObjs = getFilteredObjects(listObjs);
 
-  private List<Table> getFilteredTableList(List<HivePrivilegeObject> hivePrivilegeObjects, List<Table> tableList) {
-    List<Table> ret = new ArrayList<>();
-    for(HivePrivilegeObject hivePrivilegeObject:hivePrivilegeObjects) {
-      String catName = hivePrivilegeObject.getCatName();
-      String dbName  = hivePrivilegeObject.getDbname();
-      String tblName = hivePrivilegeObject.getObjectName();
-      Table  table   = getFilteredTable(catName, dbName, tblName, tableList);
-      if (table != null) {
-        ret.add(table);
+    // Map 1: catName + dbName + tblName  →  exact catName match (case 3)
+    Map<String, Table> fullKeyMap = new HashMap<>(tableList.size() * 2);
+
+    // Map 2: dbName + tblName  →  first table regardless of catName (case 1: obj.catName == null)
+    Map<String, Table> anyMap = new HashMap<>(tableList.size() * 2);
+
+    // Map 3: dbName + tblName  →  first table where table.catName == null (case 2)
+    Map<String, Table> nullCatMap = new HashMap<>();
+
+    for (Table table : tableList) {
+      String partKey = dbTableKey(table.getDbName(), table.getTableName());
+      String fullKey = catDbTableKey(table.getCatName(), table.getDbName(), table.getTableName());
+
+      fullKeyMap.put(fullKey, table);
+      anyMap.putIfAbsent(partKey, table);           // first match wins
+      if (table.getCatName() == null) {
+        nullCatMap.putIfAbsent(partKey, table);   // only null-catName tables
       }
     }
-    return ret;
-  }
 
-  private Table getFilteredTable(String catName, String dbName, String tblName, List<Table> tableList) {
-    Table ret = null;
-    for (Table table: tableList) {
-      // do not check catalog name if catName is null
-      if (catName != null && table.getCatName() != null && !catName.equals(table.getCatName())) {
-        continue;
+    List<Table> ret = new ArrayList<>(filteredObjs.size());
+    for (HivePrivilegeObject obj : filteredObjs) {
+      Table table;
+      String partKey = dbTableKey(obj.getDbname(), obj.getObjectName());
+
+      if (obj.getCatName() == null) {

Review Comment:
   nit: HivePrivilegeObject normalizes null to the default catalog in its constructor, so case 1 never runs in production.



##########
ql/src/test/org/apache/hadoop/hive/ql/security/authorization/plugin/TestAuthorizationMetaStoreFilterHook.java:
##########
@@ -0,0 +1,333 @@
+/*
+ * 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.ql.security.authorization.plugin;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for {@link AuthorizationMetaStoreFilterHook#filterTables}.
+ *
+ * Validates correctness of the O(n) HashMap-based fix replacing the original
+ * O(n^2) nested-loop implementation, including catName null-handling logic.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class TestAuthorizationMetaStoreFilterHook {
+
+  private AuthorizationMetaStoreFilterHook hook;
+  private MockedStatic<SessionState> mockedSessionState;
+
+  @Mock private SessionState sessionState;
+  @Mock private HiveAuthorizer authorizer;
+
+  @Before
+  public void setUp() {
+    hook = new AuthorizationMetaStoreFilterHook(new Configuration());
+    when(sessionState.getUserIpAddress()).thenReturn("127.0.0.1");
+    when(sessionState.getForwardedAddresses()).thenReturn(Collections.emptyList());
+    when(sessionState.getAuthorizerV2()).thenReturn(authorizer);
+    mockedSessionState = mockStatic(SessionState.class);
+    mockedSessionState.when(SessionState::get).thenReturn(sessionState);
+  }
+
+  @After
+  public void tearDown() {
+    mockedSessionState.close();
+  }
+
+  // ── helpers ────────────────────────────────────────────────────────────────
+
+  /** Create a Table with catName. */
+  private Table createTable(String catName, String dbName, String tableName) {
+    Table table = new Table();
+    table.setCatName(catName);
+    table.setDbName(dbName);
+    table.setTableName(tableName);
+    table.setOwner("testowner");
+    table.setOwnerType(PrincipalType.USER);
+    return table;
+  }
+
+  /** Create a Table without catName (catName = null). */
+  private Table createTable(String dbName, String tableName) {
+    return createTable(null, dbName, tableName);
+  }
+
+  /**
+   * Stub authorizer to return HivePrivilegeObjects with the given catName
+   * for tables matching dbName + any of the allowedTableNames.
+   */
+  private void allowTablesWithCatName(String catName, String dbName, String... allowedTableNames)
+       throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+    List<HivePrivilegeObject> input = invocation.getArgument(0);
+    List<HivePrivilegeObject> result = new ArrayList<>();
+    Set<String> seen = new HashSet<>();
+      for (HivePrivilegeObject obj : input) {
+        for (String allowed : allowedTableNames) {
+          if (dbName.equals(obj.getDbname()) && allowed.equals(obj.getObjectName())) {
+            String key = (catName != null ? catName : "") + "\0" + dbName + "\0" + allowed;
+              if (seen.add(key)) {
+                result.add(new HivePrivilegeObject(
+                  HivePrivilegeObject.HivePrivilegeObjectType.TABLE_OR_VIEW, catName, dbName, allowed));
+              }
+            break;
+          }
+        }
+      }
+      return result;
+    });
+  }
+
+  /** Stub authorizer to return all objects unchanged (allow all, catName stays null). */
+  private void allowAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));
+  }
+
+  /** Stub authorizer to deny everything. */
+  private void denyAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenReturn(Collections.emptyList());
+  }
+
+  // ── existing tests (no catName) ────────────────────────────────────────────
+
+  @Test
+  public void testFilterTables_emptyInput() throws Exception {
+    denyAll();
+    List<Table> result = hook.filterTables(Collections.emptyList());
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_allAllowed() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+    allowAll();
+    List<Table> result = hook.filterTables(input);
+    assertEquals(3, result.size());
+  }
+
+  @Test
+  public void testFilterTables_allFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"));
+    denyAll();
+    List<Table> result = hook.filterTables(input);
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_someFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+      // authorize returns tbl1 and tbl3 with null catName
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+      List<HivePrivilegeObject> objs = invocation.getArgument(0);
+      return objs.stream()
+                    .filter(o -> "tbl1".equals(o.getObjectName()) || "tbl3".equals(o.getObjectName()))
+                    .collect(Collectors.toList());
+    });
+    List<Table> result = hook.filterTables(input);
+    assertEquals(2, result.size());
+    List<String> names = result.stream().map(Table::getTableName).collect(Collectors.toList());
+    assertTrue(names.contains("tbl1"));
+    assertTrue(names.contains("tbl3"));
+  }
+
+  // ── catName-specific tests ─────────────────────────────────────────────────
+
+  /**
+   * Case 1: obj.catName == null → must match a table that also has null catName.
+   * Note: HivePrivilegeObject normalizes null catName to the default catalog ("hive"),
+   * so the null-catName-obj path in production code is unreachable in practice.
+   * The live equivalent is tested via testFilterTables_tableCatNameNull_matchesObjWithNonNullCatName.
+   */
+  @Test
+  public void testFilterTables_objCatNameNull_matchesTableWithNullCatName() throws Exception {
+    List<Table> input = List.of(createTable(null, "db1", "tbl1"));
+    allowTablesWithCatName(null, "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertEquals("obj with null catName should match table with null catName", 1, result.size());
+  }
+
+  /**
+   * Case 2: obj.catName != null but table.catName == null → still matches.
+   * Original logic: condition `table.getCatName() != null` is false → skip the check.
+   */
+  @Test
+  public void testFilterTables_tableCatNameNull_matchesObjWithNonNullCatName() throws Exception {
+    List<Table> input = List.of(createTable(null, "db1", "tbl1")); // table has null catName
+    // authorizer returns obj with catName = "cat1"
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertEquals("table with null catName should match obj with any catName", 1, result.size());
+  }
+
+  /**
+   * Case 3: obj.catName != null, table.catName != null, and they match → matches.
+   */
+  @Test
+  public void testFilterTables_sameCatName_matches() throws Exception {
+    List<Table> input = List.of(createTable("cat1", "db1", "tbl1"));
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertEquals("same catName on obj and table should match", 1, result.size());
+    assertEquals("cat1", result.get(0).getCatName());
+  }
+
+  /**
+   * Both obj.catName and table.catName are non-null but DIFFERENT → no match.
+   * Original logic: condition is true → continue (skip).
+   */
+  @Test
+  public void testFilterTables_differentCatName_noMatch() throws Exception {
+    List<Table> input = List.of(createTable("cat2", "db1", "tbl1")); // table has cat2
+    // authorizer says tbl1 is allowed but with catName=cat1
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+    List<Table> result = hook.filterTables(input);
+    assertTrue("obj.catName=cat1 vs table.catName=cat2 should not match", result.isEmpty());
+  }
+
+  /**
+   * Multiple catalogs, same db+table name.
+   * obj.catName=cat1 should return only the cat1 table, not cat2.
+   */
+  @Test
+  public void testFilterTables_multipleCatalogs_sameDbTable_exactCatNameMatch() throws Exception {
+    Table cat1Table = createTable("cat1", "db1", "tbl1");
+    Table cat2Table = createTable("cat2", "db1", "tbl1");
+    List<Table> input = List.of(cat1Table, cat2Table);
+
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+
+    List<Table> result = hook.filterTables(input);
+
+    assertEquals("Only cat1 table should be returned", 1, result.size());
+    assertEquals("cat1", result.get(0).getCatName());
+  }
+
+  /**
+   * obj.catName != null, no exact catName match exists, but a table with
+   * null catName exists → that null-catName table should be returned.
+   */
+  @Test
+  public void testFilterTables_noExactCatMatch_fallsBackToNullCatTable() throws Exception {
+    Table nullCatTable = createTable(null, "db1", "tbl1");  // catName = null
+    Table cat2Table    = createTable("cat2", "db1", "tbl1"); // catName = cat2
+    List<Table> input  = List.of(nullCatTable, cat2Table);
+
+    // obj requests catName=cat1 but no cat1 table exists; null-catName table should match
+    allowTablesWithCatName("cat1", "db1", "tbl1");
+
+    List<Table> result = hook.filterTables(input);
+
+    assertEquals("null-catName table should match obj with non-null catName", 1, result.size());
+    assertEquals(null, result.get(0).getCatName());
+  }
+
+  /**
+   * Mixed: some tables have catName, some don't; some objs have catName, some don't.
+   */
+  @Test
+  public void testFilterTables_mixed_catNameCombinations() throws Exception {
+    List<Table> input = List.of(
+      createTable("cat1", "db1", "tbl1"),  // exact catName match
+      createTable(null,   "db1", "tbl2"),  // null catName — matches any obj catName
+      createTable("cat2", "db1", "tbl3"));   // catName=cat2, obj will request cat1 → no match
+
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+      // return 3 objs: tbl1(cat1), tbl2(cat1), tbl3(cat1)
+      List<HivePrivilegeObject> result = new ArrayList<>();
+      for (String tbl : List.of("tbl1", "tbl2", "tbl3")) {
+        HivePrivilegeObject obj = new HivePrivilegeObject(
+                      HivePrivilegeObject.HivePrivilegeObjectType.TABLE_OR_VIEW, "cat1", "db1", tbl);
+        result.add(obj);
+        }
+      return result;
+    });
+
+    List<Table> result = hook.filterTables(input);
+
+    List<String> names = result.stream().map(Table::getTableName).collect(Collectors.toList());
+    assertEquals("Should return tbl1 (exact) and tbl2 (null catName fallback)", 2, result.size());
+    assertTrue(names.contains("tbl1")); // cat1 == cat1 → match
+    assertTrue(names.contains("tbl2")); // null catName → match
+    assertTrue(!names.contains("tbl3")); // cat2 != cat1 → no match
+  }
+
+  // ── performance test ───────────────────────────────────────────────────────
+
+  /**
+   * 1 lakh tables must complete within 5 seconds.
+   * The original O(n^2) implementation would take 200-300 seconds.
+   * Note: uses inline time assertion instead of @Test(timeout) to avoid JUnit 4's
+   * separate-thread execution, which breaks Mockito's ThreadLocal-based MockedStatic.
+   */
+  @Test
+  public void testFilterTables_performance_100kTables() throws Exception {

Review Comment:
   nit: a hard 5s wall-clock assert can be unstable on slow/shared runners. Consider adding `@Category(SlowTests.class)`



##########
ql/src/test/org/apache/hadoop/hive/ql/security/authorization/plugin/TestAuthorizationMetaStoreFilterHook.java:
##########
@@ -0,0 +1,333 @@
+/*
+ * 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.ql.security.authorization.plugin;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for {@link AuthorizationMetaStoreFilterHook#filterTables}.
+ *
+ * Validates correctness of the O(n) HashMap-based fix replacing the original
+ * O(n^2) nested-loop implementation, including catName null-handling logic.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class TestAuthorizationMetaStoreFilterHook {
+
+  private AuthorizationMetaStoreFilterHook hook;
+  private MockedStatic<SessionState> mockedSessionState;
+
+  @Mock private SessionState sessionState;
+  @Mock private HiveAuthorizer authorizer;
+
+  @Before
+  public void setUp() {
+    hook = new AuthorizationMetaStoreFilterHook(new Configuration());
+    when(sessionState.getUserIpAddress()).thenReturn("127.0.0.1");
+    when(sessionState.getForwardedAddresses()).thenReturn(Collections.emptyList());
+    when(sessionState.getAuthorizerV2()).thenReturn(authorizer);
+    mockedSessionState = mockStatic(SessionState.class);
+    mockedSessionState.when(SessionState::get).thenReturn(sessionState);
+  }
+
+  @After
+  public void tearDown() {
+    mockedSessionState.close();
+  }
+
+  // ── helpers ────────────────────────────────────────────────────────────────
+
+  /** Create a Table with catName. */
+  private Table createTable(String catName, String dbName, String tableName) {
+    Table table = new Table();
+    table.setCatName(catName);
+    table.setDbName(dbName);
+    table.setTableName(tableName);
+    table.setOwner("testowner");
+    table.setOwnerType(PrincipalType.USER);
+    return table;
+  }
+
+  /** Create a Table without catName (catName = null). */
+  private Table createTable(String dbName, String tableName) {
+    return createTable(null, dbName, tableName);
+  }
+
+  /**
+   * Stub authorizer to return HivePrivilegeObjects with the given catName
+   * for tables matching dbName + any of the allowedTableNames.
+   */
+  private void allowTablesWithCatName(String catName, String dbName, String... allowedTableNames)
+       throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+    List<HivePrivilegeObject> input = invocation.getArgument(0);
+    List<HivePrivilegeObject> result = new ArrayList<>();
+    Set<String> seen = new HashSet<>();
+      for (HivePrivilegeObject obj : input) {
+        for (String allowed : allowedTableNames) {
+          if (dbName.equals(obj.getDbname()) && allowed.equals(obj.getObjectName())) {
+            String key = (catName != null ? catName : "") + "\0" + dbName + "\0" + allowed;
+              if (seen.add(key)) {
+                result.add(new HivePrivilegeObject(
+                  HivePrivilegeObject.HivePrivilegeObjectType.TABLE_OR_VIEW, catName, dbName, allowed));
+              }
+            break;
+          }
+        }
+      }
+      return result;
+    });
+  }
+
+  /** Stub authorizer to return all objects unchanged (allow all, catName stays null). */
+  private void allowAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));
+  }
+
+  /** Stub authorizer to deny everything. */
+  private void denyAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenReturn(Collections.emptyList());
+  }
+
+  // ── existing tests (no catName) ────────────────────────────────────────────
+
+  @Test
+  public void testFilterTables_emptyInput() throws Exception {
+    denyAll();
+    List<Table> result = hook.filterTables(Collections.emptyList());
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_allAllowed() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+    allowAll();
+    List<Table> result = hook.filterTables(input);
+    assertEquals(3, result.size());
+  }
+
+  @Test
+  public void testFilterTables_allFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"));
+    denyAll();
+    List<Table> result = hook.filterTables(input);
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_someFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+      // authorize returns tbl1 and tbl3 with null catName
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+      List<HivePrivilegeObject> objs = invocation.getArgument(0);
+      return objs.stream()
+                    .filter(o -> "tbl1".equals(o.getObjectName()) || "tbl3".equals(o.getObjectName()))
+                    .collect(Collectors.toList());
+    });
+    List<Table> result = hook.filterTables(input);
+    assertEquals(2, result.size());
+    List<String> names = result.stream().map(Table::getTableName).collect(Collectors.toList());
+    assertTrue(names.contains("tbl1"));
+    assertTrue(names.contains("tbl3"));
+  }
+
+  // ── catName-specific tests ─────────────────────────────────────────────────
+
+  /**
+   * Case 1: obj.catName == null → must match a table that also has null catName.
+   * Note: HivePrivilegeObject normalizes null catName to the default catalog ("hive"),

Review Comment:
   nit: actually exercises case 2 (obj has normalized "hive", table has null catName), not case 1.



##########
ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/AuthorizationMetaStoreFilterHook.java:
##########


Review Comment:
   nit: duplicate imports. Can you clean this up?



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6610:
URL: https://github.com/apache/hive/pull/6610#issuecomment-5001581209

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6610) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [2 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6610&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6610&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6610&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6610&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6610&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6610)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "vikramahuja1001 (via GitHub)" <gi...@apache.org>.
vikramahuja1001 commented on code in PR #6610:
URL: https://github.com/apache/hive/pull/6610#discussion_r3598294643


##########
ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/AuthorizationMetaStoreFilterHook.java:
##########


Review Comment:
   done



##########
ql/src/test/org/apache/hadoop/hive/ql/security/authorization/plugin/TestAuthorizationMetaStoreFilterHook.java:
##########
@@ -0,0 +1,333 @@
+/*
+ * 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.ql.security.authorization.plugin;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.PrincipalType;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit tests for {@link AuthorizationMetaStoreFilterHook#filterTables}.
+ *
+ * Validates correctness of the O(n) HashMap-based fix replacing the original
+ * O(n^2) nested-loop implementation, including catName null-handling logic.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class TestAuthorizationMetaStoreFilterHook {
+
+  private AuthorizationMetaStoreFilterHook hook;
+  private MockedStatic<SessionState> mockedSessionState;
+
+  @Mock private SessionState sessionState;
+  @Mock private HiveAuthorizer authorizer;
+
+  @Before
+  public void setUp() {
+    hook = new AuthorizationMetaStoreFilterHook(new Configuration());
+    when(sessionState.getUserIpAddress()).thenReturn("127.0.0.1");
+    when(sessionState.getForwardedAddresses()).thenReturn(Collections.emptyList());
+    when(sessionState.getAuthorizerV2()).thenReturn(authorizer);
+    mockedSessionState = mockStatic(SessionState.class);
+    mockedSessionState.when(SessionState::get).thenReturn(sessionState);
+  }
+
+  @After
+  public void tearDown() {
+    mockedSessionState.close();
+  }
+
+  // ── helpers ────────────────────────────────────────────────────────────────
+
+  /** Create a Table with catName. */
+  private Table createTable(String catName, String dbName, String tableName) {
+    Table table = new Table();
+    table.setCatName(catName);
+    table.setDbName(dbName);
+    table.setTableName(tableName);
+    table.setOwner("testowner");
+    table.setOwnerType(PrincipalType.USER);
+    return table;
+  }
+
+  /** Create a Table without catName (catName = null). */
+  private Table createTable(String dbName, String tableName) {
+    return createTable(null, dbName, tableName);
+  }
+
+  /**
+   * Stub authorizer to return HivePrivilegeObjects with the given catName
+   * for tables matching dbName + any of the allowedTableNames.
+   */
+  private void allowTablesWithCatName(String catName, String dbName, String... allowedTableNames)
+       throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+    List<HivePrivilegeObject> input = invocation.getArgument(0);
+    List<HivePrivilegeObject> result = new ArrayList<>();
+    Set<String> seen = new HashSet<>();
+      for (HivePrivilegeObject obj : input) {
+        for (String allowed : allowedTableNames) {
+          if (dbName.equals(obj.getDbname()) && allowed.equals(obj.getObjectName())) {
+            String key = (catName != null ? catName : "") + "\0" + dbName + "\0" + allowed;
+              if (seen.add(key)) {
+                result.add(new HivePrivilegeObject(
+                  HivePrivilegeObject.HivePrivilegeObjectType.TABLE_OR_VIEW, catName, dbName, allowed));
+              }
+            break;
+          }
+        }
+      }
+      return result;
+    });
+  }
+
+  /** Stub authorizer to return all objects unchanged (allow all, catName stays null). */
+  private void allowAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> invocation.getArgument(0));
+  }
+
+  /** Stub authorizer to deny everything. */
+  private void denyAll() throws HiveAuthzPluginException, HiveAccessControlException {
+    when(authorizer.filterListCmdObjects(any(), any())).thenReturn(Collections.emptyList());
+  }
+
+  // ── existing tests (no catName) ────────────────────────────────────────────
+
+  @Test
+  public void testFilterTables_emptyInput() throws Exception {
+    denyAll();
+    List<Table> result = hook.filterTables(Collections.emptyList());
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_allAllowed() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+    allowAll();
+    List<Table> result = hook.filterTables(input);
+    assertEquals(3, result.size());
+  }
+
+  @Test
+  public void testFilterTables_allFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"));
+    denyAll();
+    List<Table> result = hook.filterTables(input);
+    assertTrue(result.isEmpty());
+  }
+
+  @Test
+  public void testFilterTables_someFiltered() throws Exception {
+    List<Table> input = List.of(
+      createTable("db1", "tbl1"),
+      createTable("db1", "tbl2"),
+      createTable("db1", "tbl3"));
+      // authorize returns tbl1 and tbl3 with null catName
+    when(authorizer.filterListCmdObjects(any(), any())).thenAnswer(invocation -> {
+      List<HivePrivilegeObject> objs = invocation.getArgument(0);
+      return objs.stream()
+                    .filter(o -> "tbl1".equals(o.getObjectName()) || "tbl3".equals(o.getObjectName()))
+                    .collect(Collectors.toList());
+    });
+    List<Table> result = hook.filterTables(input);
+    assertEquals(2, result.size());
+    List<String> names = result.stream().map(Table::getTableName).collect(Collectors.toList());
+    assertTrue(names.contains("tbl1"));
+    assertTrue(names.contains("tbl3"));
+  }
+
+  // ── catName-specific tests ─────────────────────────────────────────────────
+
+  /**
+   * Case 1: obj.catName == null → must match a table that also has null catName.
+   * Note: HivePrivilegeObject normalizes null catName to the default catalog ("hive"),

Review Comment:
   edited



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 merged PR #6610:
URL: https://github.com/apache/hive/pull/6610


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29740 : Fix SHOW TABLES operation taking 300 seconds+ on very large databases [hive]

Posted by "saihemanth-cloudera (via GitHub)" <gi...@apache.org>.
saihemanth-cloudera commented on code in PR #6610:
URL: https://github.com/apache/hive/pull/6610#discussion_r3597757400


##########
ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/AuthorizationMetaStoreFilterHook.java:
##########
@@ -56,43 +59,88 @@ public List<String> filterTableNames(String catName, String dbName, List<String>
     return getFilteredObjectNames(getFilteredObjects(listObjs));
   }
 
+  /**
+   * Filters the given list of tables down to those the current user is authorized to see.
+   *
+   * <p>The method delegates authorization decisions to {@link HiveAuthorizer#filterListCmdObjects},

Review Comment:
   filterTableMetas() and HiveMetaStoreAuthorizer already use TablePrivilegeLookup for O(n) matching. Can you either reuse/extend TablePrivilegeLookup or add a short comment explaining why filterTables needs different null-catName semantics?



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org