This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 2678f0cc5e0 Account for table dependencies in lookup queries (#20373)
2678f0cc5e0 is described below

commit 2678f0cc5e0bedd2ed0c930cee7f05bb0dd2952d
Author: Xiang Fu <[email protected]>
AuthorDate: Wed Nov 25 23:39:22 2026 -0800

    Account for table dependencies in lookup queries (#20373)
    
    * Collect dimension dependencies from partitioned subqueries
    
    Exercise broker dependency collection using a synthetic query tree in 
BaseSingleStageBrokerRequestHandlerTest.
    
    * Account for table dependencies across lookup paths
---
 .../org/apache/pinot/broker/api/AccessControl.java |  15 ++
 .../broker/BasicAuthAccessControlFactory.java      |  45 ++++-
 .../requesthandler/BaseBrokerRequestHandler.java   |  26 ++-
 .../BaseSingleStageBrokerRequestHandler.java       | 215 ++++++++++++++-------
 .../MultiStageBrokerRequestHandler.java            |  73 ++++++-
 .../broker/broker/BasicAuthAccessControlTest.java  |  26 ++-
 .../BaseSingleStageBrokerRequestHandlerTest.java   |  54 +++++-
 .../MultiStageBrokerRequestHandlerTest.java        |  49 +++++
 .../common/function/TransformFunctionType.java     |   3 +-
 .../pinot/common/utils/request/RequestUtils.java   |  79 ++++++--
 .../pinot/sql/parsers/dml/DeleteStatement.java     |  22 +--
 .../sql/parsers/rewriter/RlsFiltersRewriter.java   |  11 +-
 .../common/utils/request/RequestUtilsTest.java     |  17 ++
 .../apache/pinot/core/auth/BasicAuthPrincipal.java |   6 +
 14 files changed, 506 insertions(+), 135 deletions(-)

diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/api/AccessControl.java 
b/pinot-broker/src/main/java/org/apache/pinot/broker/api/AccessControl.java
index 90c3fede071..6100285d687 100644
--- a/pinot-broker/src/main/java/org/apache/pinot/broker/api/AccessControl.java
+++ b/pinot-broker/src/main/java/org/apache/pinot/broker/api/AccessControl.java
@@ -116,6 +116,21 @@ public interface AccessControl extends 
FineGrainedAccessControl {
   }
 
 
+  /// Authorizes the physical OFFLINE tables read by the single-stage `LOOKUP` 
function.
+  default TableAuthorizationResult authorizeLookupTables(RequesterIdentity 
requesterIdentity,
+      Set<String> offlineTableNames) {
+    return authorize(requesterIdentity, offlineTableNames);
+  }
+
+  /// Returns whether a row-level filter applies to the physical OFFLINE 
target of an authorized `LOOKUP`.
+  default boolean hasLookupTableRowFilters(RequesterIdentity 
requesterIdentity, String offlineTableName) {
+    String rawTableName = 
TableNameBuilder.extractRawTableName(offlineTableName);
+    return getRowColFilters(requesterIdentity, 
offlineTableName).getRLSFilters()
+        .filter(filters -> !filters.isEmpty()).isPresent()
+        || getRowColFilters(requesterIdentity, rawTableName).getRLSFilters()
+            .filter(filters -> !filters.isEmpty()).isPresent();
+  }
+
   /// Verifies that the requester can delete rows from the table with a SQL 
`DELETE` statement. The broker calls it
   /// once the requester passed, in this order: 
[#authorize(RequesterIdentity)], [#authorize(RequesterIdentity, Set)]
   /// with the table as its only element (the WHERE clause of the statement 
reads it), the fine-grained
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/BasicAuthAccessControlFactory.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/BasicAuthAccessControlFactory.java
index f0120880733..5e146ceb60c 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/BasicAuthAccessControlFactory.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/BasicAuthAccessControlFactory.java
@@ -19,6 +19,7 @@
 package org.apache.pinot.broker.broker;
 
 import com.google.common.base.Preconditions;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
@@ -26,10 +27,12 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.function.BiPredicate;
 import java.util.stream.Collectors;
 import javax.annotation.Nullable;
 import javax.ws.rs.NotAuthorizedException;
 import javax.ws.rs.core.HttpHeaders;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.pinot.broker.api.AccessControl;
 import org.apache.pinot.common.auth.BasicAuthTokenUtils;
 import org.apache.pinot.common.request.BrokerRequest;
@@ -41,6 +44,7 @@ import org.apache.pinot.spi.auth.TableRowColAccessResult;
 import org.apache.pinot.spi.auth.TableRowColAccessResultImpl;
 import org.apache.pinot.spi.auth.broker.RequesterIdentity;
 import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 
 
 /// Basic Authentication based on http headers. Configured via the 
"pinot.broker.access.control" family of properties.
@@ -60,6 +64,7 @@ import org.apache.pinot.spi.env.PinotConfiguration;
 /// of its principals before.
 public class BasicAuthAccessControlFactory extends AccessControlFactory {
   private static final String PREFIX = "principals";
+  private static final String RLS_SUFFIX = ".rls";
 
   private AccessControl _accessControl;
 
@@ -69,8 +74,17 @@ public class BasicAuthAccessControlFactory extends 
AccessControlFactory {
 
   @Override
   public void init(PinotConfiguration configuration) {
-    _accessControl = new BasicAuthAccessControl(
-        BasicAuthPrincipalUtils.extractBasicAuthPrincipals(configuration, 
PREFIX));
+    // LOOKUP may match a raw or physical grant. Keep the filter keys for both 
names even if only one name was
+    // listed in the principal's table grants. Ordinary queries continue using 
the principal's parsed filters.
+    Map<String, Boolean> lookupRowFilterKeys = configuration.getKeys().stream()
+        .filter(key -> key.startsWith(PREFIX + ".") && 
key.endsWith(RLS_SUFFIX))
+        .filter(key -> {
+          String filters = configuration.getProperty(key);
+          return filters != null && 
Arrays.stream(filters.split(",")).anyMatch(StringUtils::isNotBlank);
+        })
+        .collect(Collectors.toMap(key -> key, key -> Boolean.TRUE));
+    _accessControl = new 
BasicAuthAccessControl(BasicAuthPrincipalUtils.extractBasicAuthPrincipals(configuration,
+        PREFIX), new PinotConfiguration(lookupRowFilterKeys, Map.of()));
   }
 
   @Override
@@ -81,9 +95,11 @@ public class BasicAuthAccessControlFactory extends 
AccessControlFactory {
   /// Access Control using header-based basic http authentication
   private static class BasicAuthAccessControl implements AccessControl {
     private final Map<String, BasicAuthPrincipal> _token2principal;
+    private final PinotConfiguration _lookupRowFilterKeys;
 
-    public BasicAuthAccessControl(Collection<BasicAuthPrincipal> principals) {
+    public BasicAuthAccessControl(Collection<BasicAuthPrincipal> principals, 
PinotConfiguration lookupRowFilterKeys) {
       _token2principal = 
principals.stream().collect(Collectors.toMap(BasicAuthPrincipal::getToken, p -> 
p));
+      _lookupRowFilterKeys = lookupRowFilterKeys;
     }
 
     @Override
@@ -119,6 +135,17 @@ public class BasicAuthAccessControlFactory extends 
AccessControlFactory {
 
     @Override
     public TableAuthorizationResult authorize(RequesterIdentity 
requesterIdentity, Set<String> tables) {
+      return authorizeTables(requesterIdentity, tables, 
BasicAuthPrincipal::hasTable);
+    }
+
+    @Override
+    public TableAuthorizationResult authorizeLookupTables(RequesterIdentity 
requesterIdentity,
+        Set<String> offlineTableNames) {
+      return authorizeTables(requesterIdentity, offlineTableNames, 
BasicAuthPrincipal::hasLookupTable);
+    }
+
+    private TableAuthorizationResult authorizeTables(RequesterIdentity 
requesterIdentity, Set<String> tables,
+        BiPredicate<BasicAuthPrincipal, String> hasTableAccess) {
       Optional<BasicAuthPrincipal> principalOpt = 
getPrincipalOpt(requesterIdentity);
 
       if (!principalOpt.isPresent()) {
@@ -131,7 +158,7 @@ public class BasicAuthAccessControlFactory extends 
AccessControlFactory {
       BasicAuthPrincipal principal = principalOpt.get();
       Set<String> failedTables = new HashSet<>();
       for (String table : tables) {
-        if (!principal.hasTable(table)) {
+        if (!hasTableAccess.test(principal, table)) {
           failedTables.add(table);
         }
       }
@@ -152,6 +179,16 @@ public class BasicAuthAccessControlFactory extends 
AccessControlFactory {
           principal != null && principal.hasTable(tableName));
     }
 
+    @Override
+    public boolean hasLookupTableRowFilters(RequesterIdentity 
requesterIdentity, String offlineTableName) {
+      BasicAuthPrincipal principal = getPrincipalOpt(requesterIdentity)
+          .orElseThrow(() -> new IllegalStateException("Principal is not 
authorized"));
+      String principalPrefix = PREFIX + "." + principal.getName() + ".";
+      String rawTableName = 
TableNameBuilder.extractRawTableName(offlineTableName);
+      return _lookupRowFilterKeys.containsKey(principalPrefix + 
offlineTableName + RLS_SUFFIX)
+          || _lookupRowFilterKeys.containsKey(principalPrefix + rawTableName + 
RLS_SUFFIX);
+    }
+
     @Override
     public TableRowColAccessResult getRowColFilters(RequesterIdentity 
requesterIdentity, String table) {
       Optional<BasicAuthPrincipal> principalOpt = 
getPrincipalOpt(requesterIdentity);
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseBrokerRequestHandler.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseBrokerRequestHandler.java
index d0f9ab48941..b0fbf4d5ef2 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseBrokerRequestHandler.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseBrokerRequestHandler.java
@@ -231,16 +231,17 @@ public abstract class BaseBrokerRequestHandler implements 
BrokerRequestHandler,
     String query = sql.textValue();
     requestContext.setQuery(query);
 
-    // Parse the query if needed
-    if (sqlNodeAndOptions == null) {
-      try {
+    try {
+      if (sqlNodeAndOptions == null) {
         sqlNodeAndOptions = RequestUtils.parseQuery(query, request);
-      } catch (Exception e) {
-        // Do not log or emit metric here because it is pure user error
-        QueryErrorCode errorCode = QueryErrorCode.fromThrowable(e, 
QueryErrorCode.SQL_PARSING);
-        requestContext.setErrorCode(errorCode);
-        return new BrokerResponseNative(errorCode, e.getMessage());
+      } else {
+        
RequestUtils.validateClientQueryOptions(sqlNodeAndOptions.getOptions());
       }
+    } catch (Exception e) {
+      // Do not log or emit metric here because it is pure user error
+      QueryErrorCode errorCode = QueryErrorCode.fromThrowable(e, 
QueryErrorCode.SQL_PARSING);
+      requestContext.setErrorCode(errorCode);
+      return new BrokerResponseNative(errorCode, e.getMessage());
     }
 
     // check app qps before doing anything
@@ -299,10 +300,17 @@ public abstract class BaseBrokerRequestHandler implements 
BrokerRequestHandler,
   /// Validates whether the requester has access to all the tables.
   protected TableAuthorizationResult hasTableAccess(RequesterIdentity 
requesterIdentity, Set<String> tableNames,
       RequestContext requestContext, HttpHeaders httpHeaders) {
+    return hasTableAccess(requesterIdentity, tableNames, requestContext, 
httpHeaders, false);
+  }
+
+  protected TableAuthorizationResult hasTableAccess(RequesterIdentity 
requesterIdentity, Set<String> tableNames,
+      RequestContext requestContext, HttpHeaders httpHeaders, boolean 
lookupTables) {
     final long startTimeNs = System.nanoTime();
     AccessControl accessControl = _accessControlFactory.create();
 
-    TableAuthorizationResult tableAuthorizationResult = 
accessControl.authorize(requesterIdentity, tableNames);
+    TableAuthorizationResult tableAuthorizationResult = lookupTables
+        ? accessControl.authorizeLookupTables(requesterIdentity, tableNames)
+        : accessControl.authorize(requesterIdentity, tableNames);
 
     Set<String> failedTables = tableNames.stream()
         .filter(table -> !accessControl.hasAccess(httpHeaders, 
TargetType.TABLE, table, Actions.Table.QUERY))
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandler.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandler.java
index f456f0c06be..f79d355c7ff 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandler.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandler.java
@@ -22,11 +22,12 @@ import com.fasterxml.jackson.databind.JsonNode;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import java.net.URI;
+import java.util.ArrayDeque;
 import java.util.ArrayList;
+import java.util.Deque;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.BlockingQueue;
@@ -39,6 +40,7 @@ import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 import javax.annotation.Nullable;
@@ -74,6 +76,7 @@ import org.apache.pinot.common.request.Function;
 import org.apache.pinot.common.request.Identifier;
 import org.apache.pinot.common.request.Literal;
 import org.apache.pinot.common.request.PinotQuery;
+import org.apache.pinot.common.request.context.LiteralContext;
 import org.apache.pinot.common.response.BrokerResponse;
 import org.apache.pinot.common.response.broker.BrokerResponseNative;
 import org.apache.pinot.common.response.broker.QueryProcessingException;
@@ -502,26 +505,8 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
     // A `lookup()` dimension table is not part of the data source, so neither 
the logical-table check nor the
     // BrokerRequest based check below covers it. Authorize it here, for both 
branches.
     Set<String> lookupTableNames = compileResult._lookupTableNames;
-    if (!lookupTableNames.isEmpty()) {
-      AuthorizationResult lookupAuthorizationResult =
-          hasTableAccess(requesterIdentity, lookupTableNames, requestContext, 
httpHeaders);
-      if (!lookupAuthorizationResult.hasAccess()) {
-        throwAccessDeniedError(requestId, query, requestContext, tableName, 
lookupAuthorizationResult);
-      }
-      if (_enableRowColumnLevelAuth) {
-        // `lookup()` resolves a row by primary key against the dimension 
table's in-memory data and never evaluates a
-        // filter against that table, so an RLS filter on it cannot be 
applied. Reject the query instead of returning
-        // rows the principal is not allowed to see.
-        for (String lookupTableName : lookupTableNames) {
-          List<String> rowFilters =
-              accessControl.getRowColFilters(requesterIdentity, 
lookupTableName).getRLSFilters().orElse(null);
-          if (rowFilters != null && !rowFilters.isEmpty()) {
-            throwAccessDeniedError(requestId, query, requestContext, tableName,
-                new TableAuthorizationResult(Set.of(lookupTableName)));
-          }
-        }
-      }
-    }
+    authorizeLookupTables(lookupTableNames, requestId, query, requestContext, 
tableName, requesterIdentity, httpHeaders,
+        accessControl);
 
     TableRouteProvider routeProvider;
 
@@ -641,6 +626,7 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
     /// outcome for downstream consumers: SPLIT path, response annotation, and 
the
     /// `tablesQueried` response field which must tag the user's base table, 
not the MV.
     MaterializedViewContext materializedViewContext = 
MaterializedViewContext.empty();
+    String userTableName = tableName;
     /// Capture the user-facing raw table name BEFORE the FULL_REWRITE swap 
below so the
     /// response's `tablesQueried` field tags the user's base table — not the 
MV the broker
     /// routed through.  Equals `rawTableName` when no MV swap happens.
@@ -735,6 +721,16 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
     // Prepare OFFLINE and REALTIME requests
     BrokerRequest offlineBrokerRequest = null;
     BrokerRequest realtimeBrokerRequest = null;
+    Map<Expression, Expression> offlineOverrides =
+        offlineTableName != null ? 
_tableCache.getExpressionOverrideMap(offlineTableName) : null;
+    Map<Expression, Expression> realtimeOverrides =
+        realtimeTableName != null ? 
_tableCache.getExpressionOverrideMap(realtimeTableName) : null;
+    // Servers can apply table overrides to the independent row filter even if 
the broker's WHERE tree differs.
+    if (rlsFiltersApplied.get()
+        && (hasCrossTableOverride(offlineOverrides) || 
hasCrossTableOverride(realtimeOverrides))) {
+      throwAccessDeniedError(requestId, query, requestContext, userTableName,
+          new BasicAuthorizationResultImpl(false, "Cross-table expression 
overrides are not allowed with row filters"));
+    }
 
     if (routeInfo.isHybrid()) {
       // Hybrid
@@ -742,7 +738,7 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
       offlinePinotQuery.getDataSource().setTableName(offlineTableName);
       assert timeBoundaryInfo != null;
       attachTimeBoundary(offlinePinotQuery, timeBoundaryInfo, true);
-      handleExpressionOverride(offlinePinotQuery, 
_tableCache.getExpressionOverrideMap(offlineTableName));
+      handleExpressionOverride(offlinePinotQuery, offlineOverrides);
       handleTimestampIndexOverride(offlinePinotQuery, offlineTableConfig);
       // Re-optimize after attaching the time boundary filter so that filter 
optimizers (e.g. NumericalFilterOptimizer,
       // FlattenAndOrFilterOptimizer, MergeRangeFilterOptimizer) are applied 
to the time boundary predicate.
@@ -752,7 +748,7 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
       PinotQuery realtimePinotQuery = serverPinotQuery.deepCopy();
       realtimePinotQuery.getDataSource().setTableName(realtimeTableName);
       attachTimeBoundary(realtimePinotQuery, timeBoundaryInfo, false);
-      handleExpressionOverride(realtimePinotQuery, 
_tableCache.getExpressionOverrideMap(realtimeTableName));
+      handleExpressionOverride(realtimePinotQuery, realtimeOverrides);
       handleTimestampIndexOverride(realtimePinotQuery, realtimeTableConfig);
       _queryOptimizer.optimize(realtimePinotQuery, schema);
       realtimeBrokerRequest = 
CalciteSqlCompiler.convertToBrokerRequest(realtimePinotQuery);
@@ -763,10 +759,9 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
     } else if (routeInfo.isOffline()) {
       // OFFLINE only
       setTableName(serverBrokerRequest, offlineTableName);
-      Map<Expression, Expression> expressionOverrideMap = 
_tableCache.getExpressionOverrideMap(offlineTableName);
-      handleExpressionOverride(serverPinotQuery, expressionOverrideMap);
+      handleExpressionOverride(serverPinotQuery, offlineOverrides);
       handleTimestampIndexOverride(serverPinotQuery, offlineTableConfig);
-      if (expressionOverrideMap != null) {
+      if (offlineOverrides != null) {
         _queryOptimizer.optimize(serverPinotQuery, schema);
       }
       offlineBrokerRequest = serverBrokerRequest;
@@ -776,10 +771,9 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
     } else {
       // REALTIME only
       setTableName(serverBrokerRequest, realtimeTableName);
-      Map<Expression, Expression> expressionOverrideMap = 
_tableCache.getExpressionOverrideMap(realtimeTableName);
-      handleExpressionOverride(serverPinotQuery, expressionOverrideMap);
+      handleExpressionOverride(serverPinotQuery, realtimeOverrides);
       handleTimestampIndexOverride(serverPinotQuery, realtimeTableConfig);
-      if (expressionOverrideMap != null) {
+      if (realtimeOverrides != null) {
         _queryOptimizer.optimize(serverPinotQuery, schema);
       }
       realtimeBrokerRequest = serverBrokerRequest;
@@ -788,6 +782,12 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
       
requestContext.setRealtimeServerTenant(getServerTenant(realtimeTableConfig));
     }
 
+    // These rewrites can introduce expressions that were absent from the 
user's compiled query.
+    if (offlineOverrides != null || realtimeOverrides != null || 
materializedViewContext.isFullRewrite()) {
+      authorizeRewrittenLookups(new BrokerRequest[]{offlineBrokerRequest, 
realtimeBrokerRequest}, lookupTableNames,
+          requestId, query, requestContext, userTableName, requesterIdentity, 
httpHeaders, accessControl);
+    }
+
     // Check if response can be sent without server query evaluation.
     if (offlineBrokerRequest != null && 
isFilterAlwaysFalse(offlineBrokerRequest.getPinotQuery())) {
       // We don't need to evaluate offline request
@@ -974,7 +974,9 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
       BrokerResponseNative viewSplitResponse = 
tryExecuteMaterializedViewSplit(requestId, query, sqlNodeAndOptions,
           requesterIdentity, requestContext, brokerRequest, serverPinotQuery, 
schema, materializedViewContext,
           routeInfo, remainingTimeMs, errorMsgs, numPrunedSegmentsTotal, 
database, tableName, userRawTableName,
-          rlsFiltersApplied.get(), serverStats, selectedRoutingManager, 
routeProvider, queryWasLogged);
+          rlsFiltersApplied.get(), serverStats, selectedRoutingManager, 
routeProvider, queryWasLogged,
+          requests -> authorizeRewrittenLookups(requests, lookupTableNames, 
requestId, query,
+              requestContext, userTableName, requesterIdentity, httpHeaders, 
accessControl));
       if (viewSplitResponse != null) {
         return viewSplitResponse;
       }
@@ -1256,10 +1258,16 @@ public abstract class 
BaseSingleStageBrokerRequestHandler extends BaseBrokerRequ
 
     // A `lookup()` dimension table is named by a literal argument rather than 
by the FROM clause, so it is absent from
     // the data source. Collect it here so that `doHandleRequest` can 
authorize it alongside the queried table.
-    Set<String> lookupTableNames = extractLookupTableNames(serverPinotQuery);
-    if (serverPinotQuery != pinotQuery) {
-      // For a gapfill query the two differ, and only the stripped one was 
walked above
-      lookupTableNames.addAll(extractLookupTableNames(pinotQuery));
+    Set<String> lookupTableNames;
+    try {
+      lookupTableNames = extractLookupTableNames(serverPinotQuery);
+      if (serverPinotQuery != pinotQuery) {
+        // For a gapfill query the two differ, and only the stripped one was 
walked above
+        lookupTableNames.addAll(extractLookupTableNames(pinotQuery));
+      }
+    } catch (BadQueryRequestException e) {
+      requestContext.setErrorCode(QueryErrorCode.QUERY_VALIDATION);
+      return new CompileResult(new 
BrokerResponseNative(QueryErrorCode.QUERY_VALIDATION, e.getMessage()));
     }
 
     try {
@@ -1467,6 +1475,43 @@ public abstract class 
BaseSingleStageBrokerRequestHandler extends BaseBrokerRequ
     throw new WebApplicationException("Permission denied." + failureMessage, 
Response.Status.FORBIDDEN);
   }
 
+  private void authorizeLookupTables(Set<String> lookupTableNames, long 
requestId, String query,
+      RequestContext requestContext, String tableName, @Nullable 
RequesterIdentity requesterIdentity,
+      @Nullable HttpHeaders httpHeaders, AccessControl accessControl) {
+    if (lookupTableNames.isEmpty()) {
+      return;
+    }
+    AuthorizationResult result = hasTableAccess(requesterIdentity, 
lookupTableNames, requestContext, httpHeaders, true);
+    if (!result.hasAccess()) {
+      throwAccessDeniedError(requestId, query, requestContext, tableName, 
result);
+    }
+    if (_enableRowColumnLevelAuth) {
+      // A point lookup cannot apply a row filter on the dimension table.
+      for (String lookupTableName : lookupTableNames) {
+        if (accessControl.hasLookupTableRowFilters(requesterIdentity, 
lookupTableName)) {
+          throwAccessDeniedError(requestId, query, requestContext, tableName,
+              new TableAuthorizationResult(Set.of(lookupTableName)));
+        }
+      }
+    }
+  }
+
+  private void authorizeRewrittenLookups(BrokerRequest[] requests, Set<String> 
authorizedLookupTableNames,
+      long requestId, String query, RequestContext requestContext, String 
tableName,
+      @Nullable RequesterIdentity requesterIdentity, @Nullable HttpHeaders 
httpHeaders, AccessControl accessControl) {
+    Set<String> lookupTableNames = new HashSet<>();
+    for (BrokerRequest request : requests) {
+      if (request == null) {
+        continue;
+      }
+      PinotQuery rewrittenQuery = request.getPinotQuery();
+      lookupTableNames.addAll(extractLookupTableNames(rewrittenQuery));
+    }
+    lookupTableNames.removeAll(authorizedLookupTableNames);
+    authorizeLookupTables(lookupTableNames, requestId, query, requestContext, 
tableName, requesterIdentity, httpHeaders,
+        accessControl);
+  }
+
   private boolean isDefaultQueryResponseLimitEnabled() {
     return _defaultQueryLimit > -1;
   }
@@ -2253,48 +2298,83 @@ public abstract class 
BaseSingleStageBrokerRequestHandler extends BaseBrokerRequ
     pinotQuery.setSelectList(newSelections);
   }
 
-  /// Returns the dimension tables read by the `lookup()` calls in the given 
query.
+  /// Returns the dimension tables read by the `lookup()` calls in the query 
and its partitioned subqueries.
   ///
   /// `lookup()` names its dimension table with a string literal argument 
instead of the FROM clause, so the table is
   /// absent from the query's data source and has to be collected explicitly 
for the table-level access checks to see
-  /// it. The names are returned exactly as written, which is how 
`LookupTransformFunction` resolves them on the
-  /// server, so the authorized table is always the one actually read.
+  /// it. Resolve the name the same way as the server, including the physical 
OFFLINE suffix.
   @VisibleForTesting
   static Set<String> extractLookupTableNames(PinotQuery pinotQuery) {
     Set<String> lookupTableNames = new HashSet<>();
-    for (Expression expression : pinotQuery.getSelectList()) {
-      collectLookupTableNames(expression, lookupTableNames);
+    Deque<PinotQuery> pendingQueries = new ArrayDeque<>();
+    pendingQueries.addLast(pinotQuery);
+    while (!pendingQueries.isEmpty()) {
+      PinotQuery query = pendingQueries.removeLast();
+      collectLookupTableNames(query.getSelectList(), lookupTableNames, 
pendingQueries);
+      collectLookupTableNames(query.getFilterExpression(), lookupTableNames, 
pendingQueries);
+      collectLookupTableNames(query.getHavingExpression(), lookupTableNames, 
pendingQueries);
+      collectLookupTableNames(query.getGroupByList(), lookupTableNames, 
pendingQueries);
+      collectLookupTableNames(query.getOrderByList(), lookupTableNames, 
pendingQueries);
+      DataSource dataSource = query.getDataSource();
+      if (dataSource != null && dataSource.isSetSubquery()) {
+        pendingQueries.addLast(dataSource.getSubquery());
+      }
     }
-    collectLookupTableNames(pinotQuery.getFilterExpression(), 
lookupTableNames);
-    collectLookupTableNames(pinotQuery.getHavingExpression(), 
lookupTableNames);
-    collectLookupTableNames(pinotQuery.getGroupByList(), lookupTableNames);
-    collectLookupTableNames(pinotQuery.getOrderByList(), lookupTableNames);
     return lookupTableNames;
   }
 
-  private static void collectLookupTableNames(@Nullable List<Expression> 
expressions, Set<String> lookupTableNames) {
+  private static void collectLookupTableNames(@Nullable List<Expression> 
expressions, Set<String> lookupTableNames,
+      Deque<PinotQuery> pendingQueries) {
     if (expressions != null) {
       for (Expression expression : expressions) {
-        collectLookupTableNames(expression, lookupTableNames);
+        collectLookupTableNames(expression, lookupTableNames, pendingQueries);
       }
     }
   }
 
-  private static void collectLookupTableNames(@Nullable Expression expression, 
Set<String> lookupTableNames) {
+  private static void collectLookupTableNames(@Nullable Expression expression, 
Set<String> lookupTableNames,
+      Deque<PinotQuery> pendingQueries) {
     if (expression == null || expression.getType() != ExpressionType.FUNCTION) 
{
       return;
     }
     Function functionCall = expression.getFunctionCall();
     List<Expression> operands = functionCall.getOperands();
-    if (LOOKUP_FUNCTION.equals(functionCall.getOperator()) && 
!operands.isEmpty()) {
-      Literal tableName = operands.get(0).getLiteral();
-      // A non-literal table name is rejected by LookupTransformFunction on 
the server
-      if (tableName != null && tableName.isSetStringValue()) {
-        lookupTableNames.add(tableName.getStringValue());
+    switch 
(RequestUtils.classifyCrossTableFunction(functionCall.getOperator())) {
+      case LOOKUP -> {
+        Literal tableName = operands.isEmpty() ? null : 
operands.get(0).getLiteral();
+        if (tableName == null) {
+          throw new BadQueryRequestException("LOOKUP requires a literal 
dimension table name");
+        }
+        String name = new LiteralContext(tableName).getStringValue();
+        lookupTableNames.add(TableNameBuilder.OFFLINE.tableNameWithType(name));
+      }
+      case IN_PARTITIONED_SUBQUERY -> 
pendingQueries.addLast(compilePartitionedSubquery(operands));
+      case IN_SUBQUERY -> {
+        // The separately executed broker request authorizes its own tables.
+      }
+      case null -> {
+        // Ordinary functions contribute dependencies from their operands.
       }
     }
     // Recurse regardless, so that a lookup() nested inside another lookup()'s 
join value is collected too
-    collectLookupTableNames(operands, lookupTableNames);
+    collectLookupTableNames(operands, lookupTableNames, pendingQueries);
+  }
+
+  private static PinotQuery compilePartitionedSubquery(List<Expression> 
operands) {
+    Literal sql = operands.size() == 2 ? operands.get(1).getLiteral() : null;
+    if (sql == null || !sql.isSetStringValue()) {
+      throw new BadQueryRequestException("IN_PARTITIONED_SUBQUERY requires a 
literal SQL subquery");
+    }
+    QueryThreadContext.checkTerminationAndSampleUsage("Partitioned subquery 
compilation");
+    PinotQuery subquery;
+    try {
+      subquery = CalciteSqlParser.compileToPinotQuery(sql.getStringValue());
+    } catch (RuntimeException e) {
+      throw new BadQueryRequestException("Cannot compile partitioned 
subquery", e);
+    }
+    // Row-filter options can add predicates during conversion on the server, 
outside the compiled expression tree.
+    RequestUtils.validateClientQueryOptions(subquery.getQueryOptions());
+    return subquery;
   }
 
   /// Returns whether the query calls a cross-table function anywhere: in the 
select list, the filter, the having
@@ -2303,8 +2383,8 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
   @VisibleForTesting
   static boolean hasCrossTableFunction(PinotQuery pinotQuery) {
     return hasCrossTableFunction(pinotQuery.getSelectList())
-        || hasCrossTableFunction(pinotQuery.getFilterExpression())
-        || hasCrossTableFunction(pinotQuery.getHavingExpression())
+        || 
RequestUtils.containsCrossTableFunction(pinotQuery.getFilterExpression())
+        || 
RequestUtils.containsCrossTableFunction(pinotQuery.getHavingExpression())
         || hasCrossTableFunction(pinotQuery.getGroupByList())
         || hasCrossTableFunction(pinotQuery.getOrderByList());
   }
@@ -2312,7 +2392,7 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
   private static boolean hasCrossTableFunction(@Nullable List<Expression> 
expressions) {
     if (expressions != null) {
       for (Expression expression : expressions) {
-        if (hasCrossTableFunction(expression)) {
+        if (RequestUtils.containsCrossTableFunction(expression)) {
           return true;
         }
       }
@@ -2320,18 +2400,9 @@ public abstract class 
BaseSingleStageBrokerRequestHandler extends BaseBrokerRequ
     return false;
   }
 
-  private static boolean hasCrossTableFunction(@Nullable Expression 
expression) {
-    if (expression == null || expression.getType() != ExpressionType.FUNCTION) 
{
-      return false;
-    }
-    Function functionCall = expression.getFunctionCall();
-    // The operator of a compiled call is canonical, see 
RequestUtils.canonicalizeFunctionName(), but lower-cased with
-    // the default locale, while the server resolves IN_PARTITIONED_SUBQUERY 
with equalsIgnoreCase(): fold it through
-    // Locale.ROOT so that a dotless ı (U+0131), written in the query or made 
of the I by a Turkish locale, and a long
-    // ſ (U+017F) are matched as the server matches them, or a server without 
the row-filter guard would run the
-    // subquery unfiltered behind this broker.
-    String canonicalName = 
functionCall.getOperator().toUpperCase(Locale.ROOT).toLowerCase(Locale.ROOT);
-    return RequestUtils.isCrossTableFunction(canonicalName) || 
hasCrossTableFunction(functionCall.getOperands());
+  private static boolean hasCrossTableOverride(@Nullable Map<Expression, 
Expression> expressionOverrides) {
+    return expressionOverrides != null
+        && 
expressionOverrides.values().stream().anyMatch(RequestUtils::containsCrossTableFunction);
   }
 
   /// Fixes the column names to the actual column names in the given 
expression.
@@ -2622,13 +2693,14 @@ public abstract class 
BaseSingleStageBrokerRequestHandler extends BaseBrokerRequ
       MaterializedViewContext materializedViewContext, TableRouteInfo 
routeInfo, long remainingTimeMs,
       List<QueryProcessingException> errorMsgs, int numPrunedSegmentsTotal, 
String database,
       String tableName, String userRawTableName, boolean rlsFiltersApplied, 
ServerStats serverStats,
-      RoutingManager selectedRoutingManager, TableRouteProvider routeProvider, 
boolean queryWasLogged) {
+      RoutingManager selectedRoutingManager, TableRouteProvider routeProvider, 
boolean queryWasLogged,
+      Consumer<BrokerRequest[]> authorizeRewrittenLookups) {
     String clientRequestId = extractClientRequestId(sqlNodeAndOptions);
     MaterializedViewSplitDispatcher dispatcher =
         (originalReq, baseQ, baseRoute, baseSch, viewQ, viewTable, viewSch, 
timeoutMs) ->
             dispatchMaterializedViewSplit(requestId, originalReq, baseQ, 
baseRoute, baseSch, viewQ, viewTable,
                 viewSch, timeoutMs, serverStats, requestContext, 
selectedRoutingManager, routeProvider,
-                clientRequestId, query);
+                clientRequestId, query, authorizeRewrittenLookups);
     MaterializedViewSplitExecutionContext splitCtx = 
MaterializedViewSplitExecutionContext.builder()
         .originalBrokerRequest(brokerRequest)
         .baseServerPinotQuery(serverPinotQuery)
@@ -2684,7 +2756,8 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
       BrokerRequest originalBrokerRequest, PinotQuery baseQueryWithTimeFilter, 
TableRouteInfo baseRouteInfo,
       Schema baseSchema, PinotQuery viewQueryWithTimeFilter, String 
viewTableNameWithType, Schema viewSchema,
       long timeoutMs, ServerStats serverStats, RequestContext requestContext, 
RoutingManager routingManager,
-      TableRouteProvider routeProvider, @Nullable String clientRequestId, 
String query) throws Exception {
+      TableRouteProvider routeProvider, @Nullable String clientRequestId, 
String query,
+      Consumer<BrokerRequest[]> authorizeRewrittenLookups) throws Exception {
     /// 1. Optimize and route the base-table side (handles hybrid 
offline/realtime split).
     _queryOptimizer.optimize(baseQueryWithTimeFilter, baseSchema);
     BrokerRequest baseBrokerRequest = 
CalciteSqlCompiler.convertToBrokerRequest(baseQueryWithTimeFilter);
@@ -2712,6 +2785,8 @@ public abstract class BaseSingleStageBrokerRequestHandler 
extends BaseBrokerRequ
     handleTimestampIndexOverride(viewQueryWithTimeFilter, 
_tableCache.getTableConfig(viewTableNameWithType));
     _queryOptimizer.optimize(viewQueryWithTimeFilter, viewSchema);
     BrokerRequest viewBrokerRequest = 
CalciteSqlCompiler.convertToBrokerRequest(viewQueryWithTimeFilter);
+    authorizeRewrittenLookups.accept(
+        new BrokerRequest[]{baseOfflineBrokerRequest, 
baseRealtimeBrokerRequest, viewBrokerRequest});
     TableRouteInfo viewRouteInfo = 
routeProvider.getTableRouteInfo(viewTableNameWithType, _tableCache, 
routingManager);
     /// The MV table can disappear between compile (broker MV cache) and 
execute (route lookup)
     /// — operator dropped it, controller mid-state-transition, etc.  Treat 
missing-route the
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
index b02b643e0b6..466b16a062c 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandler.java
@@ -41,6 +41,7 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
+import java.util.function.Predicate;
 import java.util.stream.Collectors;
 import javax.annotation.Nullable;
 import javax.ws.rs.WebApplicationException;
@@ -89,6 +90,7 @@ import 
org.apache.pinot.query.planner.explain.AskingServerStageExplainer;
 import org.apache.pinot.query.planner.logical.SpoolMode;
 import org.apache.pinot.query.planner.physical.DispatchablePlanFragment;
 import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
+import org.apache.pinot.query.planner.plannode.JoinNode;
 import org.apache.pinot.query.planner.plannode.PlanNode;
 import org.apache.pinot.query.routing.QueryServerInstance;
 import org.apache.pinot.query.routing.WorkerManager;
@@ -111,9 +113,11 @@ import org.apache.pinot.spi.trace.QueryFingerprint;
 import org.apache.pinot.spi.trace.RequestContext;
 import org.apache.pinot.spi.utils.CommonConstants;
 import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
+import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.apache.pinot.sql.parsers.CalciteSqlParser;
 import org.apache.pinot.sql.parsers.PinotSqlType;
 import org.apache.pinot.sql.parsers.SqlNodeAndOptions;
+import org.apache.pinot.sql.parsers.rewriter.RlsFiltersRewriter;
 import org.apache.pinot.sql.parsers.rewriter.RlsUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -475,16 +479,19 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
             httpHeaders, queryTimer)) {
       
validatePhysicalTablesWithMultiClusterRouting(compiledQuery.getTableNames(), 
compiledQuery.getOptions());
       boolean rlsFiltersApplied = checkAuthorization(requesterIdentity, 
requestContext, httpHeaders, compiledQuery);
+      Predicate<String> lookupRowFilterCheck = _enableRowColumnLevelAuth
+          ? tableName -> 
_accessControlFactory.create().hasLookupTableRowFilters(requesterIdentity, 
tableName)
+          : null;
 
       // Apply broker-default query options before branching to 
EXPLAIN/execute so both paths see the same options.
       applyBrokerDefaultQueryOptions(compiledQuery.getOptions());
       prepareCompiledQueryForPlanning(compiledQuery, requestId, 
requestContext, httpHeaders);
 
       if (sqlNodeAndOptions.getSqlNode().getKind() == SqlKind.EXPLAIN) {
-        return explain(compiledQuery, requestId, requestContext, queryTimer, 
idSetSubqueries);
+        return explain(compiledQuery, requestId, requestContext, queryTimer, 
idSetSubqueries, lookupRowFilterCheck);
       } else {
         return query(compiledQuery, requestId, requesterIdentity, 
requestContext, httpHeaders, queryTimer,
-            rlsFiltersApplied, queryWasLogged, workloadName);
+            rlsFiltersApplied, queryWasLogged, workloadName, 
lookupRowFilterCheck);
       }
     }
   }
@@ -549,6 +556,12 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
       }
       String combinedFilters =
           rowFilters.stream().map(filter -> "( " + filter + " 
)").collect(Collectors.joining(" AND "));
+      try {
+        RlsFiltersRewriter.compileRowFilter(combinedFilters);
+      } catch (RuntimeException e) {
+        // Do not expose the configured policy or its parse error.
+        throw QueryErrorCode.QUERY_VALIDATION.asException("Cannot apply the 
row-level security filter");
+      }
       queryOptions.put(RlsUtils.buildRlsFilterKey(tableName), combinedFilters);
       _brokerMetrics.addMeteredTableValue(tableName, 
BrokerMeter.RLS_FILTERS_APPLIED, 1);
       applied = true;
@@ -556,6 +569,46 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
     return applied;
   }
 
+  @VisibleForTesting
+  static void checkLookupJoinRowFilters(@Nullable DispatchableSubPlan plan,
+      @Nullable Predicate<String> lookupRowFilterCheck) {
+    // A broker-only empty plan has already replaced its table scans with 
empty values.
+    if (plan == null || plan.isAllLeafStagesEmpty() || lookupRowFilterCheck == 
null) {
+      return;
+    }
+    for (DispatchablePlanFragment fragment : plan.getQueryStageMap().values()) 
{
+      if (hasRowFilteredLookupJoin(fragment, lookupRowFilterCheck)) {
+        throw new WebApplicationException(
+            "Permission denied. Lookup joins cannot read dimension tables with 
row filters.",
+            Response.Status.FORBIDDEN);
+      }
+    }
+  }
+
+  /// Lookup joins probe the dimension table without executing the right-side 
scan. The stage metadata identifies the
+  /// routed table used to construct that scan's server request, including the 
resolved table spelling.
+  private static boolean hasRowFilteredLookupJoin(DispatchablePlanFragment 
fragment,
+      Predicate<String> lookupRowFilterCheck) {
+    if (!hasLookupJoin(fragment.getPlanFragment().getFragmentRoot())) {
+      return false;
+    }
+    String tableName = fragment.getTableName();
+    return tableName == null || lookupRowFilterCheck.test(
+        
TableNameBuilder.OFFLINE.tableNameWithType(TableNameBuilder.extractRawTableName(tableName)));
+  }
+
+  private static boolean hasLookupJoin(PlanNode node) {
+    if (node instanceof JoinNode join && join.getJoinStrategy() == 
JoinNode.JoinStrategy.LOOKUP) {
+      return true;
+    }
+    for (PlanNode input : node.getInputs()) {
+      if (hasLookupJoin(input)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   private ImmutableQueryEnvironment.Config getQueryEnvConf(HttpHeaders 
httpHeaders, Map<String, String> queryOptions,
       long requestId) {
     String database = 
DatabaseUtils.extractDatabaseFromQueryRequest(queryOptions, httpHeaders);
@@ -708,7 +761,7 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
   ///
   /// @param idSetSubqueries the IdSet subqueries that did not run, see 
[IdSetSubqueryRewriter]
   private BrokerResponse explain(QueryEnvironment.CompiledQuery query, long 
requestId, RequestContext requestContext,
-      Timer timer, List<String> idSetSubqueries)
+      Timer timer, List<String> idSetSubqueries, @Nullable Predicate<String> 
lookupRowFilterCheck)
       throws WebApplicationException, QueryException {
     Map<String, String> queryOptions = query.getOptions();
 
@@ -716,11 +769,18 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
         .orElse(_explainAskingServerDefault);
     @Nullable
     AskingServerStageExplainer.OnServerExplainer fragmentToPlanNode = 
askServers
-        ? fragment -> requestPhysicalPlan(fragment, requestContext, 
timer.getRemainingTimeMs(), queryOptions)
+        ? fragment -> {
+          // Skip server requests for a forbidden stage and report the 
permission error on the request thread.
+          if (lookupRowFilterCheck != null && 
hasRowFilteredLookupJoin(fragment, lookupRowFilterCheck)) {
+            return List.of();
+          }
+          return requestPhysicalPlan(fragment, requestContext, 
timer.getRemainingTimeMs(), queryOptions);
+        }
         : null;
 
     QueryEnvironment.QueryPlannerResult queryPlanResult = callAsync(requestId, 
query.getTextQuery(),
         () -> query.explain(requestId, fragmentToPlanNode), timer);
+    checkLookupJoinRowFilters(queryPlanResult.getQueryPlan(), 
lookupRowFilterCheck);
     String plan = queryPlanResult.getExplainPlan();
     Map<String, String> extraFields = queryPlanResult.getExtraFields();
     if (!idSetSubqueries.isEmpty()) {
@@ -879,7 +939,8 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
 
   private BrokerResponse query(QueryEnvironment.CompiledQuery query, long 
requestId,
       RequesterIdentity requesterIdentity, RequestContext requestContext, 
HttpHeaders httpHeaders, Timer timer,
-      boolean rlsFiltersApplied, boolean queryWasLogged, String workloadName)
+      boolean rlsFiltersApplied, boolean queryWasLogged, String workloadName,
+      @Nullable Predicate<String> lookupRowFilterCheck)
       throws QueryException, WebApplicationException {
     QueryEnvironment.QueryPlannerResult queryPlanResult = callAsync(requestId, 
query.getTextQuery(),
         () -> query.planQuery(requestId), timer);
@@ -922,6 +983,8 @@ public class MultiStageBrokerRequestHandler extends 
BaseBrokerRequestHandler {
       throwTableAccessError(tableAuthorizationResult);
     }
 
+    checkLookupJoinRowFilters(dispatchableSubPlan, lookupRowFilterCheck);
+
     // Validate QPS quota
     if (hasExceededQPSQuota(query.getDatabase(), tableNames, requestContext)) {
       String errorMessage = String.format("Request %d: %s exceeds query 
quota.", requestId,
diff --git 
a/pinot-broker/src/test/java/org/apache/pinot/broker/broker/BasicAuthAccessControlTest.java
 
b/pinot-broker/src/test/java/org/apache/pinot/broker/broker/BasicAuthAccessControlTest.java
index 4f8bdecd22f..b524d8b339e 100644
--- 
a/pinot-broker/src/test/java/org/apache/pinot/broker/broker/BasicAuthAccessControlTest.java
+++ 
b/pinot-broker/src/test/java/org/apache/pinot/broker/broker/BasicAuthAccessControlTest.java
@@ -64,6 +64,7 @@ public class BasicAuthAccessControlTest {
     config.put("principals.admin.password", "verysecret");
     config.put("principals.user.password", "secret");
     config.put("principals.user.tables", 
"lessImportantStuff,lesserImportantStuff,leastImportantStuff");
+    config.put("principals.user.lessImportantStuff_OFFLINE.rls", "true");
     config.put("principals.deleter.password", "delsecret");
     config.put("principals.deleter.tables", "lessImportantStuff");
     config.put("principals.deleter.permissions", "read,delete");
@@ -71,10 +72,11 @@ public class BasicAuthAccessControlTest {
     config.put("principals.reader.tables", "lessImportantStuff");
     config.put("principals.reader.permissions", "read");
     config.put("principals.excluder.password", "exclsecret");
-    config.put("principals.excluder.excludeTables", "billing");
+    config.put("principals.excluder.excludeTables", 
"billing,internal_OFFLINE");
     config.put("principals.excluder.permissions", "read,delete");
     config.put("principals.typedDeleter.password", "typedsecret");
     config.put("principals.typedDeleter.tables", "lessImportantStuff_OFFLINE");
+    config.put("principals.typedDeleter.lessImportantStuff.rls", "true");
     config.put("principals.typedDeleter.permissions", "read,delete");
     config.put("principals.star.password", "starsecret");
     config.put("principals.star.permissions", "*");
@@ -276,6 +278,28 @@ public class BasicAuthAccessControlTest {
     Assert.assertTrue(_accessControl.authorize(identity, 
_tableNames).hasAccess());
   }
 
+  @Test
+  public void testLookupAuthorizationUsesBothPolicyNames() {
+    String table = "lessImportantStuff_OFFLINE";
+    HttpRequesterIdentity identity = new HttpRequesterIdentity();
+    Multimap<String, String> headers = ArrayListMultimap.create();
+    identity.setHttpHeaders(headers);
+
+    headers.put(HEADER_AUTHORIZATION, TOKEN_USER);
+    Assert.assertTrue(_accessControl.authorizeLookupTables(identity, 
Set.of(table)).hasAccess());
+    Assert.assertFalse(_accessControl.authorize(identity, 
Set.of(table)).hasAccess());
+    Assert.assertTrue(_accessControl.hasLookupTableRowFilters(identity, 
table));
+
+    headers.replaceValues(HEADER_AUTHORIZATION, List.of(TOKEN_TYPED_DELETER));
+    Assert.assertTrue(_accessControl.authorizeLookupTables(identity, 
Set.of(table)).hasAccess());
+    Assert.assertTrue(_accessControl.hasLookupTableRowFilters(identity, 
table));
+
+    headers.replaceValues(HEADER_AUTHORIZATION, List.of(TOKEN_EXCLUDER));
+    assertEquals(_accessControl.authorizeLookupTables(identity, 
Set.of("billing_OFFLINE", "internal_OFFLINE", table))
+        .getFailedTables(), Set.of("billing_OFFLINE", "internal_OFFLINE"));
+    Assert.assertFalse(_accessControl.hasLookupTableRowFilters(identity, 
table));
+  }
+
   @Test
   public void testDeleteRowsChecksTheRawTableName() {
     // excludeTables lists raw names: a type suffix does not bypass it
diff --git 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandlerTest.java
 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandlerTest.java
index e6dd0b7dd3a..824b43d0f77 100644
--- 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandlerTest.java
+++ 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandlerTest.java
@@ -53,6 +53,7 @@ import org.apache.pinot.common.request.PinotQuery;
 import org.apache.pinot.common.response.BrokerResponse;
 import org.apache.pinot.common.response.broker.BrokerResponseNative;
 import org.apache.pinot.common.response.broker.QueryProcessingException;
+import org.apache.pinot.common.utils.request.RequestUtils;
 import org.apache.pinot.core.routing.RoutingTable;
 import org.apache.pinot.core.routing.SegmentsToQuery;
 import org.apache.pinot.core.routing.TableRouteInfo;
@@ -951,6 +952,7 @@ public class BaseSingleStageBrokerRequestHandlerTest {
     when(queryQuotaManager.acquireApplication(anyString())).thenReturn(true);
 
     AtomicReference<List<String>> rowFilters = new 
AtomicReference<>(List.of("tenant = 'allowed'"));
+    AtomicReference<Set<String>> deniedTables = new 
AtomicReference<>(Set.of());
     AccessControl accessControl = new AccessControl() {
       @Override
       public AuthorizationResult authorize(RequesterIdentity identity, 
BrokerRequest request) {
@@ -959,7 +961,9 @@ public class BaseSingleStageBrokerRequestHandlerTest {
 
       @Override
       public TableAuthorizationResult authorize(RequesterIdentity identity, 
Set<String> tables) {
-        return TableAuthorizationResult.success();
+        Set<String> denied = new HashSet<>(tables);
+        denied.retainAll(deniedTables.get());
+        return denied.isEmpty() ? TableAuthorizationResult.success() : new 
TableAuthorizationResult(denied);
       }
 
       @Override
@@ -1003,6 +1007,16 @@ public class BaseSingleStageBrokerRequestHandlerTest {
       
assertTrue(BaseSingleStageBrokerRequestHandler.hasCrossTableFunction(serverRequest.get().getPinotQuery()),
           function);
     }
+
+    // The broker must also check a dimension dependency introduced by a 
table's expression override.
+    
when(tableCache.getExpressionOverrideMap(tableName)).thenReturn(Map.of(RequestUtils.getIdentifierExpression("col1"),
+        CalciteSqlParser.compileToExpression("lookup('dimTable', 'dimValue', 
'dimKey', col1)")));
+    deniedTables.set(Set.of("dimTable_OFFLINE"));
+    serverRequest.set(null);
+    WebApplicationException error = expectThrows(WebApplicationException.class,
+        () -> handler.handleRequest("SELECT col1 FROM myTable"));
+    assertEquals(error.getResponse().getStatus(), 
Response.Status.FORBIDDEN.getStatusCode());
+    assertNull(serverRequest.get());
   }
 
   /// A handler that records the request it would send to the servers instead 
of sending it.
@@ -2289,31 +2303,53 @@ public class BaseSingleStageBrokerRequestHandlerTest {
     Assert.assertEquals(extractLookupTableNames("SELECT col FROM tbl WHERE col 
> 1"), Set.of());
 
     // Select list, filter, group-by, order-by and having
-    Assert.assertEquals(extractLookupTableNames("SELECT lookup('dimA', 'c', 
'pk', col) FROM tbl"), Set.of("dimA"));
+    Assert.assertEquals(extractLookupTableNames("SELECT lookup('dimA', 'c', 
'pk', col) FROM tbl"),
+        Set.of("dimA_OFFLINE"));
     Assert.assertEquals(extractLookupTableNames("SELECT col FROM tbl WHERE 
lookup('dimA', 'c', 'pk', col) = 'x'"),
-        Set.of("dimA"));
+        Set.of("dimA_OFFLINE"));
     Assert.assertEquals(
-        extractLookupTableNames("SELECT COUNT(*) FROM tbl GROUP BY 
lookup('dimA', 'c', 'pk', col)"), Set.of("dimA"));
+        extractLookupTableNames("SELECT COUNT(*) FROM tbl GROUP BY 
lookup('dimA', 'c', 'pk', col)"),
+        Set.of("dimA_OFFLINE"));
     Assert.assertEquals(extractLookupTableNames("SELECT col FROM tbl ORDER BY 
lookup('dimA', 'c', 'pk', col)"),
-        Set.of("dimA"));
+        Set.of("dimA_OFFLINE"));
     Assert.assertEquals(
         extractLookupTableNames("SELECT COUNT(*) FROM tbl GROUP BY col HAVING 
COUNT(*) > 1 AND MAX(col) > 0"),
         Set.of());
 
     // Wrapped in another function, aliased, and nested inside another 
lookup's join value
     Assert.assertEquals(extractLookupTableNames("SELECT UPPER(lookup('dimA', 
'c', 'pk', col)) AS a FROM tbl"),
-        Set.of("dimA"));
+        Set.of("dimA_OFFLINE"));
     Assert.assertEquals(
         extractLookupTableNames("SELECT lookup('dimA', 'c', 'pk', 
lookup('dimB', 'c', 'pk', col)) FROM tbl"),
-        Set.of("dimA", "dimB"));
+        Set.of("dimA_OFFLINE", "dimB_OFFLINE"));
 
     // The function name is canonicalized, so casing in the query must not 
hide the table
-    Assert.assertEquals(extractLookupTableNames("SELECT LOOKUP('dimA', 'c', 
'pk', col) FROM tbl"), Set.of("dimA"));
+    Assert.assertEquals(extractLookupTableNames("SELECT LOOKUP('dimA', 'c', 
'pk', col) FROM tbl"),
+        Set.of("dimA_OFFLINE"));
 
     // Multiple distinct dimension tables
     Assert.assertEquals(extractLookupTableNames(
             "SELECT lookup('dimA', 'c', 'pk', col) FROM tbl WHERE 
lookup('dimB', 'c', 'pk', col) = 'x'"),
-        Set.of("dimA", "dimB"));
+        Set.of("dimA_OFFLINE", "dimB_OFFLINE"));
+  }
+
+  @Test
+  public void testExtractLookupTableNamesFromPartitionedSubquery() {
+    // Use a synthetic expression tree to exercise dependency collection 
without executing a partitioned query.
+    PinotQuery query = new PinotQuery();
+    Expression column = RequestUtils.getIdentifierExpression("col");
+    Expression subquery = 
RequestUtils.getFunctionExpression("In_Partitioned_Subquery", column,
+        RequestUtils.getLiteralExpression("SELECT lookup('dimA_OFFLINE', 'c', 
'pk', col) FROM tbl"));
+    query.setSelectList(List.of(subquery));
+    
Assert.assertEquals(BaseSingleStageBrokerRequestHandler.extractLookupTableNames(query),
 Set.of("dimA_OFFLINE"));
+
+    subquery.getFunctionCall().setOperands(List.of(column,
+        RequestUtils.getLiteralExpression("SELECT ID_SET(col) FROM tbl")));
+    
Assert.assertTrue(BaseSingleStageBrokerRequestHandler.extractLookupTableNames(query).isEmpty());
+
+    subquery.getFunctionCall().setOperands(List.of(column, column));
+    expectThrows(BadQueryRequestException.class,
+        () -> 
BaseSingleStageBrokerRequestHandler.extractLookupTableNames(query));
   }
 
   private static Set<String> extractLookupTableNames(String sql) {
diff --git 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
index 38fca87845f..fb259f833ab 100644
--- 
a/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
+++ 
b/pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/MultiStageBrokerRequestHandlerTest.java
@@ -25,7 +25,11 @@ import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicReference;
 import javax.annotation.Nullable;
+import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.runtime.PairList;
 import org.apache.pinot.broker.api.AccessControl;
 import org.apache.pinot.broker.broker.AccessControlFactory;
 import org.apache.pinot.broker.broker.AllowAllAccessControlFactory;
@@ -38,6 +42,8 @@ import org.apache.pinot.common.metrics.BrokerMetrics;
 import org.apache.pinot.common.response.BrokerResponse;
 import org.apache.pinot.common.response.broker.BrokerResponseNativeV2;
 import org.apache.pinot.common.response.broker.ResultTable;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
 import org.apache.pinot.core.routing.MockRoutingManagerFactory;
 import org.apache.pinot.core.routing.MultiClusterRoutingContext;
 import org.apache.pinot.core.routing.RoutingManager;
@@ -45,9 +51,16 @@ import org.apache.pinot.core.transport.ServerInstance;
 import 
org.apache.pinot.core.transport.server.routing.stats.ServerRoutingStatsManager;
 import org.apache.pinot.query.QueryEnvironmentTestBase;
 import org.apache.pinot.query.mailbox.MailboxService;
+import org.apache.pinot.query.planner.PlanFragment;
+import org.apache.pinot.query.planner.logical.RexExpression;
 import org.apache.pinot.query.planner.physical.DispatchablePlanFragment;
 import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
 import org.apache.pinot.query.planner.physical.PinotDispatchPlanner;
+import org.apache.pinot.query.planner.plannode.JoinNode;
+import org.apache.pinot.query.planner.plannode.JoinNode.JoinStrategy;
+import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.query.planner.plannode.ProjectNode;
+import org.apache.pinot.query.planner.plannode.TableScanNode;
 import org.apache.pinot.query.routing.WorkerManager;
 import org.apache.pinot.query.runtime.operator.BaseMailboxReceiveOperator;
 import org.apache.pinot.query.runtime.operator.LeafOperator;
@@ -62,6 +75,7 @@ import org.apache.pinot.spi.auth.broker.RequesterIdentity;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import 
org.apache.pinot.spi.eventlistener.query.BrokerQueryEventListenerFactory;
 import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
 import org.apache.pinot.spi.query.QueryThreadContext;
 import org.apache.pinot.spi.trace.QueryFingerprint;
 import org.apache.pinot.spi.trace.RequestContext;
@@ -100,6 +114,7 @@ import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertNull;
+import static org.testng.Assert.expectThrows;
 
 
 public class MultiStageBrokerRequestHandlerTest extends 
QueryEnvironmentTestBase {
@@ -576,6 +591,40 @@ public class MultiStageBrokerRequestHandlerTest extends 
QueryEnvironmentTestBase
     Assert.assertTrue(handler.applyRlsFilters(null, Set.of("empty", "absent", 
"filtered"), queryOptions));
     assertEquals(queryOptions,
         Map.of(RlsUtils.buildRlsFilterKey("filtered"), "( col1 = 'a' ) AND ( 
col2 = 'b' )"));
+
+    when(accessControl.getRowColFilters(any(), eq("filtered"))).thenReturn(
+        new TableRowColAccessResultImpl(List.of("lookup('dimension', 'name', 
'id', col1) = 'a'")));
+    expectThrows(QueryException.class, () -> handler.applyRlsFilters(null, 
Set.of("filtered"), new HashMap<>()));
+  }
+
+  @Test
+  public void testLookupJoinRowFilters() {
+    DataSchema schema = new DataSchema(new String[]{"id"}, new 
ColumnDataType[]{ColumnDataType.INT});
+    TableScanNode fact = new TableScanNode(1, schema, null, List.of(), "fact", 
List.of("id"));
+    TableScanNode dimension = new TableScanNode(1, schema, null, List.of(), 
"db.dimension", List.of("id"));
+    ProjectNode projectedDimension = new ProjectNode(1, schema, null, 
List.of(dimension),
+        List.of(new RexExpression.InputRef(0)));
+    for (PlanNode rightInput : List.of(dimension, projectedDimension)) {
+      DispatchableSubPlan lookupPlan = joinPlan(fact, rightInput, 
JoinStrategy.LOOKUP);
+      MultiStageBrokerRequestHandler.checkLookupJoinRowFilters(lookupPlan, 
null);
+      MultiStageBrokerRequestHandler.checkLookupJoinRowFilters(lookupPlan, 
Set.of("fact_OFFLINE")::contains);
+
+      WebApplicationException denied = 
expectThrows(WebApplicationException.class,
+          () -> 
MultiStageBrokerRequestHandler.checkLookupJoinRowFilters(lookupPlan,
+              Set.of("db.Dimension_OFFLINE")::contains));
+      assertEquals(denied.getResponse().getStatus(), 
Response.Status.FORBIDDEN.getStatusCode());
+    }
+    MultiStageBrokerRequestHandler.checkLookupJoinRowFilters(joinPlan(fact, 
dimension, JoinStrategy.HASH),
+        Set.of("db.Dimension_OFFLINE")::contains);
+  }
+
+  private static DispatchableSubPlan joinPlan(PlanNode fact, PlanNode 
dimension, JoinStrategy strategy) {
+    JoinNode join = new JoinNode(1, fact.getDataSchema(), null, List.of(fact, 
dimension), JoinRelType.SEMI,
+        List.of(0), List.of(0), List.of(), strategy);
+    DispatchablePlanFragment fragment = new DispatchablePlanFragment(new 
PlanFragment(1, join, List.of()));
+    fragment.setTableName("db.Dimension");
+    return new DispatchableSubPlan(PairList.of(0, "id"), Map.of(1, fragment), 
Set.of("fact", "db.dimension"), Map.of(),
+        0);
   }
 
   /// The failure detector keeps an instance unhealthy while any retrier 
returns UNHEALTHY for it. A multi-stage worker
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/function/TransformFunctionType.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/function/TransformFunctionType.java
index b257e61056e..4fac0bc902a 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/function/TransformFunctionType.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/function/TransformFunctionType.java
@@ -184,8 +184,7 @@ public enum TransformFunctionType {
   // Nullable: both the transform and the scalar function return NULL for a 
NULL value, unless the IdSet is empty. The
   // multi-stage planner also uses this operator for the inIdSet scalar 
function (see IdSetFunctions).
   IN_ID_SET("inIdSet", ReturnTypes.BOOLEAN_NULLABLE, 
OperandTypes.family(SqlTypeFamily.ANY, SqlTypeFamily.CHARACTER)),
-  // Reads another table: a DELETE predicate rejects it, see 
DeleteStatement#CROSS_TABLE_FUNCTIONS, which lists the
-  // functions by hand and must gain any new function that reads another table
+  // Reads another table. Register any new table-reading transform in 
RequestUtils.CrossTableFunction as well.
   LOOKUP("lookUp"),
   // Runs a script: a DELETE predicate rejects it, see 
DeleteStatement#SCRIPT_FUNCTIONS, which must gain any new
   // script function
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
index 6eedf81e9a4..30190b89e30 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/request/RequestUtils.java
@@ -35,6 +35,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
@@ -97,10 +98,20 @@ public class RequestUtils {
     long parserStartTimeNs = System.nanoTime();
     SqlNodeAndOptions sqlNodeAndOptions = 
CalciteSqlParser.compileToSqlNodeAndOptions(query);
     setOptions(sqlNodeAndOptions, request);
+    validateClientQueryOptions(sqlNodeAndOptions.getOptions());
     sqlNodeAndOptions.setParseTimeNs(System.nanoTime() - parserStartTimeNs);
     return sqlNodeAndOptions;
   }
 
+  /// Rejects row-filter metadata from clients. Only the broker can attach row 
filters after authorization.
+  public static void validateClientQueryOptions(Map<String, String> options) {
+    for (String key : options.keySet()) {
+      if (Strings.CI.startsWith(key, CommonConstants.RLS_FILTERS)) {
+        throw QueryErrorCode.QUERY_VALIDATION.asException("Row-filter options 
are reserved for the broker");
+      }
+    }
+  }
+
   /// Extracts and merges SQL and request payload options without parsing the 
executable SQL statement.
   /// Callers can pass null when they only need the payload options. The 
broker still validates the statement,
   /// including policies that depend on the statement type.
@@ -630,24 +641,58 @@ public class RequestUtils {
     return CANONICAL_NAME_TO_SPECIAL_KEY_MAP.getOrDefault(canonicalName, 
canonicalName);
   }
 
-  /// Canonical names, see [#canonicalizeFunctionName(String)], of the 
functions that read rows from somewhere other
-  /// than the FROM clause of the query that calls them: `lookup()` joins a 
dimension table by primary key,
-  /// `IN_SUBQUERY` runs its quoted subquery as a request of its own and 
`IN_PARTITIONED_SUBQUERY` runs it on the
-  /// server. The access checks keyed on the FROM clause do not cover them, so 
the single-stage broker rejects them
-  /// under row-level security, see [#isCrossTableFunction(String)].
-  ///
-  /// Nothing derives this set from the function registries, so a function 
that reads another table or runs a nested
-  /// query must be added here when it is defined, and to 
`DeleteStatement#CROSS_TABLE_FUNCTIONS`, which keeps the
-  /// same list in its own fold: `lookup` is `TransformFunctionType#LOOKUP` 
(with `LookupTransformFunction` in
-  /// pinot-core), `insubquery` is rewritten by 
`BaseSingleStageBrokerRequestHandler#IN_SUBQUERY` in pinot-broker and
-  /// `inpartitionedsubquery` by 
`ServerQueryExecutorV1Impl#IN_PARTITIONED_SUBQUERY` in pinot-core.
-  private static final Set<String> CROSS_TABLE_FUNCTIONS = Set.of("lookup", 
"insubquery", "inpartitionedsubquery");
-
-  /// Returns whether `canonicalName` names a function that reads rows from 
somewhere other than the FROM clause, see
-  /// [#CROSS_TABLE_FUNCTIONS]. The name must already be canonical, see 
[#canonicalizeFunctionName(String)], as the
-  /// parser leaves the operator of every compiled function call; a name as 
written in a query is not matched.
+  /// Built-in functions whose execution reads a table or runs a query through 
an expression rather than a data source.
+  /// The single-stage broker uses this classification to account for table 
dependencies and enforce row-level security.
+  /// DELETE rejects these functions because its authorization only covers the 
table being modified.
+  public enum CrossTableFunction {
+    LOOKUP,
+    IN_SUBQUERY,
+    IN_PARTITIONED_SUBQUERY
+  }
+
+  // Classify each new built-in that reads another table or runs a nested 
query and define how its dependencies are
+  // authorized. The transform function registry describes LOOKUP, and the two 
subqueries are handled by rewriters.
+  private static final Map<String, CrossTableFunction> CROSS_TABLE_FUNCTIONS = 
Map.of(
+      "lookup", CrossTableFunction.LOOKUP, "insubquery", 
CrossTableFunction.IN_SUBQUERY,
+      "inpartitionedsubquery", CrossTableFunction.IN_PARTITIONED_SUBQUERY);
+
+  /// Returns the built-in's classification, or null for other functions. The 
name must already be canonical, see
+  /// [#canonicalizeFunctionName(String)].
+  @Nullable
+  public static CrossTableFunction getCrossTableFunction(String canonicalName) 
{
+    return CROSS_TABLE_FUNCTIONS.get(canonicalName);
+  }
+
+  /// Returns whether a canonical name belongs to a built-in function with 
table dependencies outside its data source.
   public static boolean isCrossTableFunction(String canonicalName) {
-    return CROSS_TABLE_FUNCTIONS.contains(canonicalName);
+    return getCrossTableFunction(canonicalName) != null;
+  }
+
+  /// Classifies a compiled operator, matching the server's case-insensitive 
partitioned-subquery name check.
+  @Nullable
+  public static CrossTableFunction classifyCrossTableFunction(String operator) 
{
+    String name = StringUtils.remove(operator, '_');
+    if (name.equalsIgnoreCase("inPartitionedSubquery")) {
+      return CrossTableFunction.IN_PARTITIONED_SUBQUERY;
+    }
+    return getCrossTableFunction(name.toLowerCase(Locale.ROOT));
+  }
+
+  /// Returns whether any call in this expression reads a table outside its 
data source.
+  public static boolean containsCrossTableFunction(@Nullable Expression 
expression) {
+    Function function = expression == null ? null : 
expression.getFunctionCall();
+    if (function == null) {
+      return false;
+    }
+    if (classifyCrossTableFunction(function.getOperator()) != null) {
+      return true;
+    }
+    for (Expression operand : function.getOperands()) {
+      if (containsCrossTableFunction(operand)) {
+        return true;
+      }
+    }
+    return false;
   }
 
   /// Returns true iff `expression` is an `AS`-wrapped function call
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/dml/DeleteStatement.java
 
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/dml/DeleteStatement.java
index c0d01d324b4..a66bf615a3a 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/dml/DeleteStatement.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/dml/DeleteStatement.java
@@ -54,6 +54,7 @@ import org.apache.pinot.common.request.ExpressionType;
 import org.apache.pinot.common.request.Function;
 import org.apache.pinot.common.utils.DataSchema;
 import org.apache.pinot.common.utils.DatabaseUtils;
+import org.apache.pinot.common.utils.request.RequestUtils;
 import org.apache.pinot.spi.config.task.AdhocTaskConfig;
 import org.apache.pinot.spi.exception.QueryErrorCode;
 import org.apache.pinot.spi.exception.QueryException;
@@ -136,23 +137,10 @@ public class DeleteStatement implements 
DataManipulationStatement {
     }
   };
 
-  /// Canonical names (upper case, without underscores) of the functions that 
read another table than the one the
-  /// statement deletes from, which the caller is not authorized to read. 
Upper case because the compiled function
-  /// names are lower-cased with the default locale, and lower-casing with a 
Turkish locale turns `I` into the dotless
-  /// `ı` (U+0131), which only an upper-case fold with [Locale#ROOT] maps back 
to `I`.
-  ///
-  /// Nothing derives this set from the function registries, so a function 
that reads another table must be added
-  /// here when it is defined: `lookUp` is `TransformFunctionType#LOOKUP` 
(with `LookupTransformFunction` in
-  /// pinot-core), `inSubquery` is rewritten by 
`BaseSingleStageBrokerRequestHandler#IN_SUBQUERY` in pinot-broker, and
-  /// `inPartitionedSubquery` by 
`ServerQueryExecutorV1Impl#IN_PARTITIONED_SUBQUERY` in pinot-core.
-  /// `RequestUtils#isCrossTableFunction(String)` keeps the same list in lower 
case for the single-stage broker's
-  /// row-level security check; add the function there too.
-  private static final Set<String> CROSS_TABLE_FUNCTIONS = Set.of("LOOKUP", 
"INSUBQUERY", "INPARTITIONEDSUBQUERY");
-
   /// Canonical names of the functions that run a script. Rejected because the 
broker's groovy policy
   /// (`pinot.broker.disable.query.groovy`, the per-table 
`queryConfig.disableGroovy` override and the static
   /// analyzer) only applies to queries, not to a `DELETE`, and the executor 
may run the predicate on another role.
-  /// Like [#CROSS_TABLE_FUNCTIONS], it is maintained by hand: `groovy` is 
`TransformFunctionType#GROOVY` (with
+  /// The set is maintained by hand: `groovy` is 
`TransformFunctionType#GROOVY` (with
   /// `GroovyTransformFunction` in pinot-core), and a new script function must 
be added here.
   private static final Set<String> SCRIPT_FUNCTIONS = Set.of("GROOVY");
 
@@ -391,8 +379,8 @@ public class DeleteStatement implements 
DataManipulationStatement {
   /// the functions that run a script, see [#SCRIPT_FUNCTIONS], the window 
functions, which
   /// [#PREDICATE_NODE_CHECKER] already rejects on the parsed node, and a 
`LIKE` with an escape character (a third or
   /// later operand) written as a function call, see [#LIKE_FUNCTIONS]. 
Function names are folded with
-  /// `toUpperCase(Locale.ROOT)`, see
-  /// [#CROSS_TABLE_FUNCTIONS], and a function name with non-ASCII characters 
is rejected outright: no supported
+  /// `toUpperCase(Locale.ROOT)` to recognize names compiled under a Turkish 
locale. The result is lower-cased for
+  /// [RequestUtils#isCrossTableFunction(String)]. A function name with 
non-ASCII characters is rejected: no supported
   /// function has one, and a look-alike spelling (e.g. with a dotless `ı`) 
may be resolved case-insensitively to the
   /// real function by an executor.
   private static void checkFunctions(Expression expression) {
@@ -402,7 +390,7 @@ public class DeleteStatement implements 
DataManipulationStatement {
     Function function = expression.getFunctionCall();
     String operator = function.getOperator();
     String functionName = operator.replace("_", "").toUpperCase(Locale.ROOT);
-    checkArgument(!CROSS_TABLE_FUNCTIONS.contains(functionName),
+    
checkArgument(!RequestUtils.isCrossTableFunction(functionName.toLowerCase(Locale.ROOT)),
         "Unsupported WHERE clause in DELETE, %s reads another table", 
operator);
     checkArgument(!SCRIPT_FUNCTIONS.contains(functionName),
         "Unsupported WHERE clause in DELETE, %s is not supported in a DELETE 
predicate", operator);
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/rewriter/RlsFiltersRewriter.java
 
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/rewriter/RlsFiltersRewriter.java
index 2a777e78d7a..739de2f203c 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/sql/parsers/rewriter/RlsFiltersRewriter.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/sql/parsers/rewriter/RlsFiltersRewriter.java
@@ -61,7 +61,7 @@ public class RlsFiltersRewriter implements QueryRewriter {
       return pinotQuery;
     }
 
-    Expression expression = CalciteSqlParser.compileToExpression(rowFilters);
+    Expression expression = compileRowFilter(rowFilters);
     Expression existingFilterExpression = pinotQuery.getFilterExpression();
     if (existingFilterExpression != null) {
       Expression combinedFilterExpression =
@@ -72,4 +72,13 @@ public class RlsFiltersRewriter implements QueryRewriter {
     }
     return pinotQuery;
   }
+
+  /// Compiles a row filter that can be evaluated without reading another 
table.
+  public static Expression compileRowFilter(String rowFilters) {
+    Expression expression = CalciteSqlParser.compileToExpression(rowFilters);
+    if (RequestUtils.containsCrossTableFunction(expression)) {
+      throw new IllegalArgumentException("Cross-table functions are not 
supported in row filters");
+    }
+    return expression;
+  }
 }
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/request/RequestUtilsTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/request/RequestUtilsTest.java
index f151815bfe8..6921bf3e48a 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/request/RequestUtilsTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/request/RequestUtilsTest.java
@@ -19,6 +19,7 @@
 package org.apache.pinot.common.utils.request;
 
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
 import org.apache.calcite.sql.SqlDialect;
@@ -31,6 +32,10 @@ import org.apache.pinot.common.request.Function;
 import org.apache.pinot.common.request.Identifier;
 import org.apache.pinot.common.request.Literal;
 import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.common.utils.request.RequestUtils.CrossTableFunction;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
+import org.apache.pinot.spi.utils.CommonConstants;
 import org.apache.pinot.spi.utils.UuidUtils;
 import org.apache.pinot.sql.parsers.CalciteSqlParser;
 import org.apache.pinot.sql.parsers.PinotSqlType;
@@ -44,6 +49,7 @@ import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertSame;
 import static org.testng.Assert.assertThrows;
 import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
 
 
 public class RequestUtilsTest {
@@ -147,6 +153,14 @@ public class RequestUtilsTest {
         "SELECT `foo`\n" + "FROM `countries`\n" + "WHERE `bar` > 1");
   }
 
+  @Test
+  public void testClientQueryOptionsRejectRowFilters() {
+    RequestUtils.validateClientQueryOptions(Map.of("timeoutMs", "100"));
+    QueryException exception = expectThrows(QueryException.class,
+        () -> 
RequestUtils.validateClientQueryOptions(Map.of(CommonConstants.RLS_FILTERS, 
"")));
+    assertEquals(exception.getErrorCode(), QueryErrorCode.QUERY_VALIDATION);
+  }
+
   @DataProvider(name = "queryProvider")
   public Object[][] queryProvider() {
     return new Object[][] {
@@ -269,6 +283,9 @@ public class RequestUtilsTest {
 
   @Test
   public void testIsCrossTableFunction() {
+    assertSame(RequestUtils.getCrossTableFunction("lookup"), 
CrossTableFunction.LOOKUP);
+    assertSame(RequestUtils.getCrossTableFunction("insubquery"), 
CrossTableFunction.IN_SUBQUERY);
+    assertSame(RequestUtils.getCrossTableFunction("inpartitionedsubquery"), 
CrossTableFunction.IN_PARTITIONED_SUBQUERY);
     // The names the parser leaves on a compiled call, see 
RequestUtils.canonicalizeFunctionName()
     String[] spellings = {
         "LOOKUP", "look_Up", "IN_SUBQUERY", "inSubquery", 
"IN_PARTITIONED_SUBQUERY", "In_Partitioned_Sub_Query"
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/auth/BasicAuthPrincipal.java 
b/pinot-core/src/main/java/org/apache/pinot/core/auth/BasicAuthPrincipal.java
index aa8797b0a55..e5e669c75e8 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/auth/BasicAuthPrincipal.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/auth/BasicAuthPrincipal.java
@@ -75,6 +75,12 @@ public class BasicAuthPrincipal {
     return isTableIncluded(tableName) && isTableNotExcluded(tableName);
   }
 
+  /// Checks both grant names for the same physical OFFLINE table. A denial on 
either name takes precedence.
+  public boolean hasLookupTable(String offlineTableName) {
+    String rawTableName = 
TableNameBuilder.extractRawTableName(offlineTableName);
+    return (isTableIncluded(offlineTableName) || 
isTableIncluded(rawTableName)) && isTableNotExcluded(offlineTableName);
+  }
+
   /// Returns whether this principal is scoped to every table, i.e. it carries 
neither an allow-list nor an
   /// exclude-list. Access control implementations use this to decide requests 
that name no table, so the return value
   /// must satisfy: `true` implies [#hasTable(String)] holds for every table 
name. A subclass that narrows table scope


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

Reply via email to