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 05c81927b4b Add a routing customizer hook to the time-series broker 
path (#20280)
05c81927b4b is described below

commit 05c81927b4bb45e04b7139f2635316a8c2072d85
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Tue Nov 17 20:59:56 2026 -0800

    Add a routing customizer hook to the time-series broker path (#20280)
    
    * Add a routing customizer hook to the time-series broker path
    
    The SQL engines let a broker narrow routing and add server query options
    through protected factory methods and hooks. The time-series path had
    neither: BaseBrokerStarter built TimeSeriesRequestHandler inline, and
    TableScanVisitor routed each leaf with a request that carried no query
    options.
    
    Add TimeSeriesRoutingCustomizer, called once per leaf after the routing
    manager picks its segments, on the planning thread and before dispatch. It
    gets the leaf and a TimeSeriesRoutingContext: the request's query options
    and the query's routing query options (both read-only) plus
    putRoutingQueryOption. It can narrow the leaf's routing table and add
    routing query options. A later leaf sees what an earlier one added, and
    TimeSeriesQueryEnvironment sends them with every leaf, replacing a leaf's
    own option with the same key. BaseBrokerStarter gains a
    createTimeSeriesRequestHandler factory method, like its single-stage and
    multi-stage siblings, so a broker can supply one. The customizer travels
    with each query's TableScanVisitor.Context rather than on the
    TableScanVisitor singleton, and sees only the narrow context.
    
    Routing fixes the hook relies on:
    - A leaf with no segments on any server yields no data instead of failing
      with "No servers selected for the query": its exchange expects no server
      and returns an empty block over the query's time buckets, and a query
      with no server at all dispatches nothing while the broker fragment still
      runs. This resolves the TODO in computeNumServersForExchangePlanNode. A
      leaf whose segments are all unavailable still fails, with
      SERVER_SEGMENT_MISSING, so an outage does not read as no data.
    - Each server now receives only the fragments of the leaves it holds
      segments for (all of them when one server runs the whole plan). Every
      server used to run every fragment and send a block for each, while an
      exchange waits for one block per server holding its leaf, so in a query
      whose leaves route to different servers an exchange could take an
      empty block in place of a server's real data.
    - Optional segments (e.g. newly pushed segments not yet ONLINE in the
      external view) now reach the server, under a new metadata key, and are
      queried if the server has them, as in the single-stage engine. They used
      to be dropped, and a server holding only optional segments for a leaf
      was sent an empty segment list that it decoded as one missing segment
      named "". A server that does not know the new key ignores it.
    - The query's tables are authorized before routing, so a caller who may
      not query a table is refused before a customizer does any work.
    
    Use case: a table format with snapshots can pin every leaf of a query to one
    snapshot and tell the servers which one, honoring a snapshot the caller
    pinned in the request, as a broker can already do for single-stage SQL.
    
    The default NO_OP customizer keeps routing and leaf plans unchanged.
    
    * Fix time-series routing for unrouted leaves, optional-only servers and 
empty assignments
    
    - One server runs the whole plan only when it holds segments for every
      leaf. Before, a query whose leaves all routed to one server, except a
      leaf the customizer narrowed to nothing, sent the whole plan to that
      server, so the unrouted leaf ran there anyway: it could fail with
      SERVER_TABLE_MISSING when the server does not host its table, or read
      segments the customizer had excluded. Such a plan now runs one fragment
      per leaf, and the unrouted leaf's exchange expects no server.
    - BaseBrokerRoutingManager left out servers that hold only optional
      segments, so a segment a server has loaded while the external view lags
      could never be queried, and a leaf with only such segments read as no
      data. A new routing request option,
      RoutingManager.ROUTE_SERVERS_WITH_ONLY_OPTIONAL_SEGMENTS, keeps those
      servers; the time-series planner sets it, since its servers query
      optional segments. Other engines keep the old behavior.
    - A leaf fails with SERVER_SEGMENT_MISSING whenever none of its server
      entries has a segment and some segments are unavailable, including when
      the routing table keeps server entries with empty segment lists.
    
    Tests: TimeSeriesQueryEnvironmentTest gains one-server pushdown, empty
    server entries with unavailable segments, and the routing option on the
    routing request; BrokerRoutingManagerTest gains the optional-only server
    case through the routing manager. Each fails without its fix.
    
    * Keep optional time-series routing safe
    
    Reproduce by querying while a server loads its first optional segment, or 
while the leaf has only optional routes and known unavailable segments.
    Use an internal routing opt-in, preserve missing required segment errors, 
and let optional-only scans skip an absent table.
    
    * Keep time-series routing failures and upsert scans correct
    
    Reproduce by losing an optional-only target or the last required server 
during routing, or by narrowing an upsert leaf in a customizer.
    Keep optional work on required RPCs, report lost required routes, and 
preserve validated upsert assignments.
    
    ---------
    
    Co-authored-by: Xiang Fu <[email protected]>
---
 .../broker/broker/helix/BaseBrokerStarter.java     |  13 +-
 .../requesthandler/TimeSeriesRequestHandler.java   |  25 +-
 .../routing/manager/BaseBrokerRoutingManager.java  |  38 ++-
 .../routing/manager/BrokerRoutingManagerTest.java  |  38 +++
 .../core/query/request/ServerQueryRequest.java     |   9 +-
 .../apache/pinot/core/routing/RoutingManager.java  |   8 +-
 .../apache/pinot/query/runtime/QueryRunner.java    |  24 +-
 .../PhysicalTimeSeriesBrokerPlanVisitor.java       |   3 +-
 .../PhysicalTimeSeriesServerPlanVisitor.java       |  13 +-
 .../TimeSeriesExchangeReceiveOperator.java         |  15 +-
 .../TimeSeriesExchangeReceivePlanNode.java         |  10 +-
 .../timeseries/TimeSeriesExecutionContext.java     |  15 +
 .../timeseries/TimeSeriesQueryDispatcher.java      |  16 +-
 .../query/runtime/QueryRunnerSegmentListTest.java  |  35 ++
 .../PhysicalTimeSeriesServerPlanVisitorTest.java   |  20 ++
 .../TimeSeriesExchangeReceiveOperatorTest.java     |  30 +-
 .../TimeSeriesQueryDispatcherMetadataTest.java     |  54 +++
 .../apache/pinot/spi/utils/CommonConstants.java    |  18 +
 pinot-timeseries/pinot-timeseries-planner/pom.xml  |   5 +
 .../tsdb/planner/TimeSeriesQueryEnvironment.java   |  89 ++++-
 .../tsdb/planner/physical/TableScanVisitor.java    | 164 ++++++++-
 .../physical/TimeSeriesDispatchablePlan.java       |  35 +-
 .../planner/physical/TimeSeriesRoutingContext.java |  37 ++
 .../physical/TimeSeriesRoutingCustomizer.java      |  51 +++
 .../planner/TimeSeriesQueryEnvironmentTest.java    | 377 +++++++++++++++++++++
 .../planner/physical/TableScanVisitorTest.java     | 279 +++++++++++++++
 .../tsdb/spi/plan/LeafTimeSeriesPlanNode.java      |   5 +
 27 files changed, 1351 insertions(+), 75 deletions(-)

diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
index 3f51069d68a..dd2dc1df0fd 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
@@ -347,6 +347,17 @@ public abstract class BaseBrokerStarter implements 
ServiceStartable {
         serverRoutingStatsManager);
   }
 
+  /// Override to supply a custom [TimeSeriesRequestHandler], e.g. one built 
with a
+  /// `TimeSeriesRoutingCustomizer` that adjusts how each time-series leaf is 
routed.
+  /// The default implementation routes every leaf exactly as the routing 
manager chooses.
+  protected TimeSeriesRequestHandler 
createTimeSeriesRequestHandler(PinotConfiguration config, String brokerId,
+      BrokerRequestIdGenerator requestIdGenerator, BrokerRoutingManager 
routingManager,
+      AccessControlFactory accessControlFactory, QueryQuotaManager 
queryQuotaManager, TableCache tableCache,
+      ThreadAccountant threadAccountant, MultiClusterRoutingContext 
multiClusterRoutingContext) {
+    return new TimeSeriesRequestHandler(config, brokerId, requestIdGenerator, 
routingManager, accessControlFactory,
+        queryQuotaManager, tableCache, threadAccountant, 
multiClusterRoutingContext);
+  }
+
   private void setupHelixSystemProperties() {
     // NOTE: Helix will disconnect the manager and disable the instance if it 
detects flapping (too frequent disconnect
     // from ZooKeeper). Setting flapping time window to a small value can 
avoid this from happening. Helix ignores the
@@ -606,7 +617,7 @@ public abstract class BaseBrokerStarter implements 
ServiceStartable {
     TimeSeriesRequestHandler timeSeriesRequestHandler = null;
     if 
(StringUtils.isNotBlank(_brokerConf.getProperty(PinotTimeSeriesConfiguration.getEnabledLanguagesConfigKey())))
 {
       timeSeriesRequestHandler =
-          new TimeSeriesRequestHandler(_brokerConf, brokerId, 
requestIdGenerator, _routingManager,
+          createTimeSeriesRequestHandler(_brokerConf, brokerId, 
requestIdGenerator, _routingManager,
               _accessControlFactory, _queryQuotaManager, _tableCache, 
_threadAccountant,
               multiClusterRoutingContext);
     }
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/TimeSeriesRequestHandler.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/TimeSeriesRequestHandler.java
index 06f835950e7..17ad2eff4dd 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/TimeSeriesRequestHandler.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/TimeSeriesRequestHandler.java
@@ -75,6 +75,7 @@ import org.apache.pinot.sql.parsers.CalciteSqlParser;
 import org.apache.pinot.sql.parsers.SqlNodeAndOptions;
 import org.apache.pinot.tsdb.planner.TimeSeriesQueryEnvironment;
 import org.apache.pinot.tsdb.planner.physical.TimeSeriesDispatchablePlan;
+import org.apache.pinot.tsdb.planner.physical.TimeSeriesRoutingCustomizer;
 import org.apache.pinot.tsdb.spi.RangeTimeSeriesRequest;
 import org.apache.pinot.tsdb.spi.TimeSeriesLogicalPlanResult;
 import org.apache.pinot.tsdb.spi.plan.BaseTimeSeriesPlanNode;
@@ -97,10 +98,19 @@ public class TimeSeriesRequestHandler extends 
BaseBrokerRequestHandler {
       AccessControlFactory accessControlFactory, QueryQuotaManager 
queryQuotaManager, TableCache tableCache,
       ThreadAccountant threadAccountant,
       MultiClusterRoutingContext multiClusterRoutingContext) {
+    this(config, brokerId, requestIdGenerator, routingManager, 
accessControlFactory, queryQuotaManager, tableCache,
+        threadAccountant, multiClusterRoutingContext, 
TimeSeriesRoutingCustomizer.NO_OP);
+  }
+
+  public TimeSeriesRequestHandler(PinotConfiguration config, String brokerId,
+      BrokerRequestIdGenerator requestIdGenerator, BrokerRoutingManager 
routingManager,
+      AccessControlFactory accessControlFactory, QueryQuotaManager 
queryQuotaManager, TableCache tableCache,
+      ThreadAccountant threadAccountant, MultiClusterRoutingContext 
multiClusterRoutingContext,
+      TimeSeriesRoutingCustomizer routingCustomizer) {
     super(config, brokerId, requestIdGenerator, routingManager, 
accessControlFactory, queryQuotaManager, tableCache,
         threadAccountant, multiClusterRoutingContext);
     TimeSeriesBuilderFactoryProvider.init(config);
-    _queryEnvironment = new TimeSeriesQueryEnvironment(config, routingManager, 
tableCache);
+    _queryEnvironment = new TimeSeriesQueryEnvironment(config, routingManager, 
tableCache, routingCustomizer);
     _queryEnvironment.init(config);
     _queryDispatcher = new TimeSeriesQueryDispatcher();
   }
@@ -161,9 +171,9 @@ public class TimeSeriesRequestHandler extends 
BaseBrokerRequestHandler {
         timeSeriesBlock = new 
TimeSeriesBlock(logicalPlanResult.getTimeBuckets(), new HashMap<>());
         return timeSeriesBlock;
       }
-      TimeSeriesDispatchablePlan dispatchablePlan =
-          _queryEnvironment.buildPhysicalPlan(timeSeriesRequest, 
requestContext, logicalPlanResult);
-      validatePhysicalPlan(httpHeaders, dispatchablePlan);
+      TimeSeriesDispatchablePlan dispatchablePlan = 
_queryEnvironment.buildPhysicalPlan(timeSeriesRequest,
+          requestContext, logicalPlanResult, tableNames -> 
tableLevelAccessControlCheck(httpHeaders, tableNames));
+      validatePhysicalPlanColumns(dispatchablePlan);
 
       timeSeriesBlock = 
_queryDispatcher.submitAndGet(requestContext.getRequestId(), dispatchablePlan,
           timeSeriesRequest.getTimeout().toMillis(), requestContext);
@@ -299,13 +309,6 @@ public class TimeSeriesRequestHandler extends 
BaseBrokerRequestHandler {
     }
   }
 
-  private void validatePhysicalPlan(HttpHeaders httpHeaders, 
TimeSeriesDispatchablePlan dispatchablePlan) {
-    // check authorization for table
-    tableLevelAccessControlCheck(httpHeaders, 
dispatchablePlan.getTableNames());
-    // validate column names for all LeafTimeSeriesPlanNode in the physical 
plan
-    validatePhysicalPlanColumns(dispatchablePlan);
-  }
-
   private void validatePhysicalPlanColumns(TimeSeriesDispatchablePlan 
dispatchablePlan) {
     for (BaseTimeSeriesPlanNode serverFragmentRoot : 
dispatchablePlan.getServerFragments()) {
       // traverse tree and validate all LeafTimeSeriesPlanNode has valid 
columns
diff --git 
a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
 
b/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
index 2dd20caff30..b217fd49b8c 100644
--- 
a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
+++ 
b/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
@@ -1330,6 +1330,18 @@ public abstract class BaseBrokerRoutingManager
   @Nullable
   @Override
   public RoutingTable getRoutingTable(BrokerRequest brokerRequest, String 
tableNameWithType, long requestId) {
+    return getRoutingTable(brokerRequest, tableNameWithType, requestId, false);
+  }
+
+  @Nullable
+  @Override
+  public RoutingTable getRoutingTableWithMissingServerSegments(BrokerRequest 
brokerRequest, long requestId) {
+    return getRoutingTable(brokerRequest, 
brokerRequest.getQuerySource().getTableName(), requestId, true);
+  }
+
+  @Nullable
+  private RoutingTable getRoutingTable(BrokerRequest brokerRequest, String 
tableNameWithType, long requestId,
+      boolean reportMissingServerSegments) {
     RoutingEntry routingEntry = _routingEntryMap.get(tableNameWithType);
     if (routingEntry == null) {
       return null;
@@ -1337,35 +1349,35 @@ public abstract class BaseBrokerRoutingManager
     String samplerName = extractSamplerName(brokerRequest);
     InstanceSelector.SelectionResult selectionResult =
         routingEntry.calculateRouting(brokerRequest, requestId, samplerName);
-    return new RoutingTable(getServerInstanceToSegmentsMap(tableNameWithType, 
selectionResult),
-        selectionResult.getUnavailableSegments(), 
selectionResult.getNumPrunedSegments());
-  }
-
-  private Map<ServerInstance, SegmentsToQuery> 
getServerInstanceToSegmentsMap(String tableNameWithType,
-      InstanceSelector.SelectionResult selectionResult) {
+    List<String> unavailableSegments = 
selectionResult.getUnavailableSegments();
+    List<String> unavailableSegmentsWithMissingServers = null;
     Map<String, SegmentsToQuery> instanceToSegmentsMap = 
selectionResult.getInstanceToSegmentsMap();
     Map<ServerInstance, SegmentsToQuery> serverInstanceToSegmentsMap =
         Maps.newHashMapWithExpectedSize(instanceToSegmentsMap.size());
     for (Map.Entry<String, SegmentsToQuery> entry : 
instanceToSegmentsMap.entrySet()) {
       SegmentsToQuery segmentsToQuery = entry.getValue();
       int numSegments = segmentsToQuery.getSegments().size();
-      // Skip servers that don't have non-optional segments, so that servers 
always get some non-optional segments
-      // to process, to be backward compatible.
-      // TODO: allow servers only with optional segments
+      // Query optional segments only on servers with required segments.
       if (numSegments == 0) {
         continue;
       }
-      // The server instance is looked up per query, because an instance 
config change replaces it
+      // The server instance is looked up per query because an instance config 
change replaces it.
       ServerInstance serverInstance = 
_enabledServerInstanceMap.get(entry.getKey());
       if (serverInstance != null) {
         serverInstanceToSegmentsMap.put(serverInstance, segmentsToQuery);
       } else {
-        // Should not happen in normal case unless encountered unexpected 
exception when updating routing entries
         _brokerMetrics.addMeteredTableValue(tableNameWithType, 
BrokerMeter.SERVER_MISSING_FOR_ROUTING, numSegments);
-        // TODO: Report missing server metrics for optional segments when we 
allow servers only with optional segments.
+        if (reportMissingServerSegments) {
+          if (unavailableSegmentsWithMissingServers == null) {
+            unavailableSegmentsWithMissingServers = new 
ArrayList<>(unavailableSegments);
+          }
+          
unavailableSegmentsWithMissingServers.addAll(segmentsToQuery.getSegments());
+        }
       }
     }
-    return serverInstanceToSegmentsMap;
+    return new RoutingTable(serverInstanceToSegmentsMap,
+        unavailableSegmentsWithMissingServers != null ? 
unavailableSegmentsWithMissingServers : unavailableSegments,
+        selectionResult.getNumPrunedSegments());
   }
 
   @Nullable
diff --git 
a/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
 
b/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
index 16d51b94eb6..e179ed1eccd 100644
--- 
a/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
+++ 
b/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
@@ -254,6 +254,44 @@ public class BrokerRoutingManagerTest {
     verifyNoMoreInteractions(_brokerMetrics);
   }
 
+  @Test
+  public void testRoutingTableReportsRequiredSegmentsOnMissingServers()
+      throws Exception {
+    String optionalOnlyInstanceId = "Server_optional_8000";
+    ServerInstance requiredServer =
+        new ServerInstance(new 
InstanceConfig(createEnabledServerZNRecord(SERVER_INSTANCE_ID)));
+    ServerInstance optionalOnlyServer =
+        new ServerInstance(new 
InstanceConfig(createEnabledServerZNRecord(optionalOnlyInstanceId)));
+    _routingManager.getEnabledServerInstanceMap().put(SERVER_INSTANCE_ID, 
requiredServer);
+    _routingManager.getEnabledServerInstanceMap().put(optionalOnlyInstanceId, 
optionalOnlyServer);
+    Map<String, SegmentsToQuery> instanceToSegmentsMap = Map.of(
+        SERVER_INSTANCE_ID, segmentsToQuery(List.of("required"), 
List.of("optional")),
+        optionalOnlyInstanceId, segmentsToQuery(List.of(), 
List.of("optionalOnly")));
+    InstanceSelector instanceSelector = mock(InstanceSelector.class);
+    InstanceSelector.SelectionResult selectionResult =
+        new InstanceSelector.SelectionResult(instanceToSegmentsMap, 
List.of("alreadyUnavailable"), 0);
+    when(instanceSelector.select(any(), any(), 
anyLong())).thenReturn(selectionResult);
+    putRoutingEntry(TEST_TABLE, createRoutingEntry(TEST_TABLE,
+        selectorOf("required", "optional", "optionalOnly", 
"alreadyUnavailable"), List.of(), instanceSelector));
+    clearInvocations(_brokerMetrics);
+
+    BrokerRequest request = brokerRequest(TEST_TABLE);
+    RoutingTable routingTable = 
_routingManager.getRoutingTableWithMissingServerSegments(request, 0);
+    Map<ServerInstance, SegmentsToQuery> serverSegments = 
routingTable.getServerInstanceToSegmentsMap();
+    assertEquals(serverSegments.keySet(), Set.of(requiredServer));
+    assertEquals(serverSegments.get(requiredServer).getSegments(), 
List.of("required"));
+    assertEquals(serverSegments.get(requiredServer).getOptionalSegments(), 
List.of("optional"));
+    assertEquals(routingTable.getUnavailableSegments(), 
List.of("alreadyUnavailable"));
+
+    // Model a query that selected a server just before it became disabled.
+    _routingManager.getEnabledServerInstanceMap().remove(SERVER_INSTANCE_ID);
+    routingTable = 
_routingManager.getRoutingTableWithMissingServerSegments(request, 0);
+    assertTrue(routingTable.getServerInstanceToSegmentsMap().isEmpty());
+    assertEquals(routingTable.getUnavailableSegments(), 
List.of("alreadyUnavailable", "required"));
+    assertEquals(selectionResult.getUnavailableSegments(), 
List.of("alreadyUnavailable"));
+    verify(_brokerMetrics).addMeteredTableValue(TEST_TABLE, 
BrokerMeter.SERVER_MISSING_FOR_ROUTING, 1L);
+  }
+
   @Test
   public void testNoErrorWhenCallbackNotSet() {
     // Don't set callback
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/query/request/ServerQueryRequest.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/query/request/ServerQueryRequest.java
index 0c8440c16dd..f718c0fccd0 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/query/request/ServerQueryRequest.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/query/request/ServerQueryRequest.java
@@ -162,6 +162,13 @@ public class ServerQueryRequest {
   /// To be used by Time Series Query Engine.
   public ServerQueryRequest(QueryContext queryContext, List<String> 
segmentsToQuery, Map<String, String> metadata,
       ServerMetrics serverMetrics) {
+    this(queryContext, segmentsToQuery, null, metadata, serverMetrics);
+  }
+
+  /// To be used by Time Series Query Engine. `optionalSegments` are queried 
when the server has them and skipped
+  /// otherwise, as in the single-stage engine.
+  public ServerQueryRequest(QueryContext queryContext, List<String> 
segmentsToQuery,
+      @Nullable List<String> optionalSegments, Map<String, String> metadata, 
ServerMetrics serverMetrics) {
     long queryArrivalTimeMs = System.currentTimeMillis();
     _queryContext = queryContext;
     _tableType = 
TableNameBuilder.getTableTypeFromTableName(_queryContext.getTableName());
@@ -176,7 +183,7 @@ public class ServerQueryRequest {
     _queryHash = 
QueryOptionsUtils.getQueryHash(_queryContext.getQueryOptions());
 
     _segmentsToQuery = segmentsToQuery;
-    _optionalSegments = null;
+    _optionalSegments = optionalSegments;
 
     _timerContext = new TimerContext(_queryContext.getTableName(), 
serverMetrics, queryArrivalTimeMs);
     _tableSegmentsContexts = null;
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java 
b/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
index fbd6fa27f37..f04bdde57bd 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
@@ -38,7 +38,6 @@ import org.apache.pinot.spi.annotations.InterfaceStability;
 @InterfaceAudience.Public
 @InterfaceStability.Evolving
 public interface RoutingManager {
-
   /// Get all enabled server instances in the cluster.
   ///
   /// @return all currently enabled server instances.
@@ -69,6 +68,13 @@ public interface RoutingManager {
   @Nullable
   RoutingTable getRoutingTable(BrokerRequest brokerRequest, long requestId);
 
+  /// Get the routing table and report required segments whose selected server 
has since disappeared as unavailable.
+  /// Implementations without this capability fall back to regular routing.
+  @Nullable
+  default RoutingTable getRoutingTableWithMissingServerSegments(BrokerRequest 
brokerRequest, long requestId) {
+    return getRoutingTable(brokerRequest, requestId);
+  }
+
   /// Get the [RoutingTable] for a specific broker request.
   /// @param brokerRequest the broker request constructed from a query.
   /// @param tableNameWithType the name of the table.
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/QueryRunner.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/QueryRunner.java
index c65756cda57..e524fabe0c9 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/QueryRunner.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/QueryRunner.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.query.runtime;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import io.grpc.stub.StreamObserver;
 import java.time.Duration;
@@ -426,7 +427,7 @@ public class QueryRunner {
       TimeSeriesExecutionContext context =
           new 
TimeSeriesExecutionContext(metadata.get(Request.MetadataKeys.TimeSeries.LANGUAGE),
               extractTimeBuckets(metadata), deadlineMs, metadata, 
extractPlanToSegmentMap(metadata),
-              Map.of());
+              extractPlanToOptionalSegmentMap(metadata), Map.of());
       final List<BaseTimeSeriesOperator> fragmentOpChains = 
fragmentRoots.stream().map(x -> {
         return _timeSeriesPhysicalPlanVisitor.compile(x, context);
       }).collect(Collectors.toList());
@@ -667,10 +668,27 @@ public class QueryRunner {
     for (var entry : metadataMap.entrySet()) {
       if (Request.MetadataKeys.TimeSeries.isKeySegmentList(entry.getKey())) {
         String planId = 
Request.MetadataKeys.TimeSeries.decodeSegmentListKey(entry.getKey());
-        String[] segments = entry.getValue().split(",");
-        result.put(planId, 
Stream.of(segments).map(String::strip).collect(Collectors.toList()));
+        result.put(planId, decodeSegmentList(entry.getValue()));
       }
     }
     return result;
   }
+
+  private Map<String, List<String>> 
extractPlanToOptionalSegmentMap(Map<String, String> metadataMap) {
+    Map<String, List<String>> result = new HashMap<>();
+    for (var entry : metadataMap.entrySet()) {
+      if 
(Request.MetadataKeys.TimeSeries.isKeyOptionalSegmentList(entry.getKey())) {
+        String planId = 
Request.MetadataKeys.TimeSeries.decodeOptionalSegmentListKey(entry.getKey());
+        result.put(planId, decodeSegmentList(entry.getValue()));
+      }
+    }
+    return result;
+  }
+
+  /// An empty value is an empty list, not one segment named "".
+  @VisibleForTesting
+  static List<String> decodeSegmentList(String encoded) {
+    return Stream.of(encoded.split(",")).map(String::strip).filter(segment -> 
!segment.isEmpty())
+        .collect(Collectors.toList());
+  }
 }
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesBrokerPlanVisitor.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesBrokerPlanVisitor.java
index 533c4e1bb1e..0028c1f23a2 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesBrokerPlanVisitor.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesBrokerPlanVisitor.java
@@ -73,7 +73,8 @@ public class PhysicalTimeSeriesBrokerPlanVisitor {
     TimeSeriesExchangeReceivePlanNode exchangeReceivePlanNode = new 
TimeSeriesExchangeReceivePlanNode(
         exchangeNode.getId(), context.getDeadlineMs(), 
exchangeNode.getAggInfo(), context.getSeriesBuilderFactory());
     BlockingQueue<Object> receiver = 
context.getExchangeReceiverByPlanId().get(exchangeNode.getId());
-    exchangeReceivePlanNode.init(Objects.requireNonNull(receiver, "No receiver 
for node"), numServersQueried);
+    exchangeReceivePlanNode.init(Objects.requireNonNull(receiver, "No receiver 
for node"), numServersQueried,
+        context.getInitialTimeBuckets());
     return exchangeReceivePlanNode;
   }
 }
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitor.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitor.java
index 26a204a3d08..e873fd950f0 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitor.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitor.java
@@ -82,16 +82,19 @@ public class PhysicalTimeSeriesServerPlanVisitor {
 
   private TimeSeriesPhysicalTableScan 
convertLeafToPhysicalTableScan(LeafTimeSeriesPlanNode leafNode,
       TimeSeriesExecutionContext context) {
-    List<String> segments = 
context.getPlanIdToSegmentsMap().getOrDefault(leafNode.getId(), List.of());
-    ServerQueryRequest serverQueryRequest = 
compileLeafServerQueryRequest(leafNode, segments, context);
+    ServerQueryRequest serverQueryRequest = 
compileLeafServerQueryRequest(leafNode, context);
     return new TimeSeriesPhysicalTableScan(context, leafNode.getId(), 
serverQueryRequest, _queryExecutor,
         _executorService);
   }
 
-  public ServerQueryRequest 
compileLeafServerQueryRequest(LeafTimeSeriesPlanNode leafNode, List<String> 
segments,
+  /// The leaf's request with the required and optional segments the broker 
assigned this server.
+  @VisibleForTesting
+  ServerQueryRequest compileLeafServerQueryRequest(LeafTimeSeriesPlanNode 
leafNode,
       TimeSeriesExecutionContext context) {
-    return new ServerQueryRequest(compileQueryContext(leafNode, context),
-        segments, getServerQueryRequestMetadataMap(context), _serverMetrics);
+    List<String> segments = 
context.getPlanIdToSegmentsMap().getOrDefault(leafNode.getId(), List.of());
+    List<String> optionalSegments = 
context.getPlanIdToOptionalSegmentsMap().get(leafNode.getId());
+    return new ServerQueryRequest(compileQueryContext(leafNode, context), 
segments, optionalSegments,
+        getServerQueryRequestMetadataMap(context), _serverMetrics);
   }
 
   /// Create a transform expression, and link it with an aggregation function.
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperator.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperator.java
index 9c76f071058..b4525d14d3f 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperator.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperator.java
@@ -87,20 +87,31 @@ public class TimeSeriesExchangeReceiveOperator extends 
BaseTimeSeriesOperator {
   @Nullable
   private final AggInfo _aggInfo;
   private final TimeSeriesBuilderFactory _factory;
+  @Nullable
+  private final TimeBuckets _timeBuckets;
 
+  /// @param numServersQueried servers that send a block; 0 when no server 
holds segments for the plan node, in which
+  ///     case the operator returns an empty block over `timeBuckets` without 
waiting
   public TimeSeriesExchangeReceiveOperator(BlockingQueue<Object> receiver, 
long deadlineMs, int numServersQueried,
-      @Nullable AggInfo aggInfo, TimeSeriesBuilderFactory 
seriesBuilderFactory) {
+      @Nullable AggInfo aggInfo, TimeSeriesBuilderFactory 
seriesBuilderFactory, @Nullable TimeBuckets timeBuckets) {
     super(List.of());
-    Preconditions.checkArgument(numServersQueried > 0, "No servers to query in 
receive operator");
+    Preconditions.checkArgument(numServersQueried >= 0, "Negative number of 
servers in receive operator");
+    Preconditions.checkArgument(numServersQueried > 0 || timeBuckets != null,
+        "Time buckets are required when no server is queried");
     _receiver = receiver;
     _deadlineMs = deadlineMs;
     _numServersQueried = numServersQueried;
     _aggInfo = aggInfo;
     _factory = seriesBuilderFactory;
+    _timeBuckets = timeBuckets;
   }
 
   @Override
   public TimeSeriesBlock getNextBlock() {
+    if (_numServersQueried == 0) {
+      // No server holds segments for this plan node: it has no data.
+      return new TimeSeriesBlock(_timeBuckets, new HashMap<>());
+    }
     try {
       if (_aggInfo == null) {
         return getNextBlockNoAggregation();
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceivePlanNode.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceivePlanNode.java
index 7b578c749cc..5187b38c5f9 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceivePlanNode.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceivePlanNode.java
@@ -22,6 +22,7 @@ import java.util.List;
 import java.util.concurrent.BlockingQueue;
 import javax.annotation.Nullable;
 import org.apache.pinot.tsdb.spi.AggInfo;
+import org.apache.pinot.tsdb.spi.TimeBuckets;
 import org.apache.pinot.tsdb.spi.operator.BaseTimeSeriesOperator;
 import org.apache.pinot.tsdb.spi.plan.BaseTimeSeriesPlanNode;
 import org.apache.pinot.tsdb.spi.series.TimeSeriesBuilderFactory;
@@ -35,6 +36,8 @@ public class TimeSeriesExchangeReceivePlanNode extends 
BaseTimeSeriesPlanNode {
   private final TimeSeriesBuilderFactory _factory;
   private BlockingQueue<Object> _receiver;
   private int _numServersQueried;
+  @Nullable
+  private TimeBuckets _timeBuckets;
 
   public TimeSeriesExchangeReceivePlanNode(String id, long deadlineMs, 
@Nullable AggInfo aggInfo,
       TimeSeriesBuilderFactory factory) {
@@ -44,9 +47,11 @@ public class TimeSeriesExchangeReceivePlanNode extends 
BaseTimeSeriesPlanNode {
     _factory = factory;
   }
 
-  public void init(BlockingQueue<Object> receiver, int numExpectedBlocks) {
+  /// @param timeBuckets the query's time buckets, for the empty block 
returned when `numExpectedBlocks` is 0
+  public void init(BlockingQueue<Object> receiver, int numExpectedBlocks, 
@Nullable TimeBuckets timeBuckets) {
     _receiver = receiver;
     _numServersQueried = numExpectedBlocks;
+    _timeBuckets = timeBuckets;
   }
 
   @Override
@@ -66,6 +71,7 @@ public class TimeSeriesExchangeReceivePlanNode extends 
BaseTimeSeriesPlanNode {
 
   @Override
   public BaseTimeSeriesOperator run() {
-    return new TimeSeriesExchangeReceiveOperator(_receiver, _deadlineMs, 
_numServersQueried, _aggInfo, _factory);
+    return new TimeSeriesExchangeReceiveOperator(_receiver, _deadlineMs, 
_numServersQueried, _aggInfo, _factory,
+        _timeBuckets);
   }
 }
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExecutionContext.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExecutionContext.java
index 74f62329e96..242ad34f177 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExecutionContext.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExecutionContext.java
@@ -30,6 +30,7 @@ public class TimeSeriesExecutionContext {
   private final String _language;
   private final TimeBuckets _initialTimeBuckets;
   private final Map<String, List<String>> _planIdToSegmentsMap;
+  private final Map<String, List<String>> _planIdToOptionalSegmentsMap;
   private final Map<String, BlockingQueue<Object>> _exchangeReceiverByPlanId;
   private final long _deadlineMs;
   private final Map<String, String> _metadataMap;
@@ -38,11 +39,20 @@ public class TimeSeriesExecutionContext {
   public TimeSeriesExecutionContext(String language, TimeBuckets 
initialTimeBuckets, long deadlineMs,
       Map<String, String> metadataMap, Map<String, List<String>> 
planIdToSegmentsMap,
       Map<String, BlockingQueue<Object>> exchangeReceiverByPlanId) {
+    this(language, initialTimeBuckets, deadlineMs, metadataMap, 
planIdToSegmentsMap, Map.of(),
+        exchangeReceiverByPlanId);
+  }
+
+  public TimeSeriesExecutionContext(String language, TimeBuckets 
initialTimeBuckets, long deadlineMs,
+      Map<String, String> metadataMap, Map<String, List<String>> 
planIdToSegmentsMap,
+      Map<String, List<String>> planIdToOptionalSegmentsMap,
+      Map<String, BlockingQueue<Object>> exchangeReceiverByPlanId) {
     _language = language;
     _initialTimeBuckets = initialTimeBuckets;
     _deadlineMs = deadlineMs;
     _metadataMap = metadataMap;
     _planIdToSegmentsMap = planIdToSegmentsMap;
+    _planIdToOptionalSegmentsMap = planIdToOptionalSegmentsMap;
     _exchangeReceiverByPlanId = exchangeReceiverByPlanId;
     _seriesBuilderFactory = 
TimeSeriesBuilderFactoryProvider.getSeriesBuilderFactory(language);
   }
@@ -71,6 +81,11 @@ public class TimeSeriesExecutionContext {
     return _planIdToSegmentsMap;
   }
 
+  /// Segments of each plan that the server queries if it has them and skips 
otherwise.
+  public Map<String, List<String>> getPlanIdToOptionalSegmentsMap() {
+    return _planIdToOptionalSegmentsMap;
+  }
+
   public Map<String, BlockingQueue<Object>> getExchangeReceiverByPlanId() {
     return _exchangeReceiverByPlanId;
   }
diff --git 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcher.java
 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcher.java
index dab8467ddd0..62d39264bf9 100644
--- 
a/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcher.java
+++ 
b/pinot-query-runtime/src/main/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcher.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.query.service.dispatch.timeseries;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import io.grpc.Deadline;
 import java.util.HashMap;
@@ -74,7 +75,7 @@ public class TimeSeriesQueryDispatcher {
       Deadline deadline = Deadline.after(deadlineMs - 
System.currentTimeMillis(), TimeUnit.MILLISECONDS);
       Preconditions.checkState(!deadline.isExpired(), "Deadline expired before 
query could be sent to servers");
       Worker.TimeSeriesQueryRequest request = 
Worker.TimeSeriesQueryRequest.newBuilder()
-          .addAllDispatchPlan(plan.getSerializedServerFragments())
+          .addAllDispatchPlan(plan.getSerializedServerFragments(serverId))
           .putAllMetadata(initializeTimeSeriesMetadataMap(plan, deadlineMs, 
requestContext, serverId))
           .putMetadata(MetadataKeys.REQUEST_ID, Long.toString(requestId))
           .build();
@@ -93,7 +94,8 @@ public class TimeSeriesQueryDispatcher {
     }
   }
 
-  private Map<String, String> 
initializeTimeSeriesMetadataMap(TimeSeriesDispatchablePlan dispatchablePlan,
+  @VisibleForTesting
+  static Map<String, String> 
initializeTimeSeriesMetadataMap(TimeSeriesDispatchablePlan dispatchablePlan,
       long deadlineMs, RequestContext requestContext, String instanceId) {
     Map<String, String> result = new HashMap<>();
     TimeBuckets timeBuckets = dispatchablePlan.getTimeBuckets();
@@ -104,7 +106,15 @@ public class TimeSeriesQueryDispatcher {
     result.put(MetadataKeys.TimeSeries.DEADLINE_MS, Long.toString(deadlineMs));
     Map<String, List<String>> leafIdToSegments = 
dispatchablePlan.getLeafIdToSegmentsByInstanceId().get(instanceId);
     for (Map.Entry<String, List<String>> entry : leafIdToSegments.entrySet()) {
-      result.put(MetadataKeys.TimeSeries.encodeSegmentListKey(entry.getKey()), 
String.join(",", entry.getValue()));
+      if (!entry.getValue().isEmpty()) {
+        
result.put(MetadataKeys.TimeSeries.encodeSegmentListKey(entry.getKey()), 
String.join(",", entry.getValue()));
+      }
+    }
+    Map<String, List<String>> leafIdToOptionalSegments =
+        
dispatchablePlan.getLeafIdToOptionalSegmentsByInstanceId().getOrDefault(instanceId,
 Map.of());
+    for (Map.Entry<String, List<String>> entry : 
leafIdToOptionalSegments.entrySet()) {
+      
result.put(MetadataKeys.TimeSeries.encodeOptionalSegmentListKey(entry.getKey()),
+          String.join(",", entry.getValue()));
     }
     result.put(MetadataKeys.REQUEST_ID, 
Long.toString(requestContext.getRequestId()));
     result.put(MetadataKeys.BROKER_ID, requestContext.getBrokerId());
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/QueryRunnerSegmentListTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/QueryRunnerSegmentListTest.java
new file mode 100644
index 00000000000..079a9d0f4ed
--- /dev/null
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/QueryRunnerSegmentListTest.java
@@ -0,0 +1,35 @@
+/**
+ * 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.pinot.query.runtime;
+
+import java.util.List;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+/// The segment lists a time-series server reads from the dispatch metadata.
+public class QueryRunnerSegmentListTest {
+  @Test
+  public void testDecodeSegmentList() {
+    assertEquals(QueryRunner.decodeSegmentList("seg1, seg2"), List.of("seg1", 
"seg2"));
+    // An empty list must not become one segment named "", which the server 
would report as missing.
+    assertEquals(QueryRunner.decodeSegmentList(""), List.of());
+  }
+}
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitorTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitorTest.java
index 0391c825b79..bb109fdf33d 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitorTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/PhysicalTimeSeriesServerPlanVisitorTest.java
@@ -25,8 +25,10 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.TimeUnit;
 import org.apache.pinot.common.metrics.ServerMetrics;
 import org.apache.pinot.core.query.executor.QueryExecutor;
+import org.apache.pinot.core.query.request.ServerQueryRequest;
 import org.apache.pinot.core.query.request.context.QueryContext;
 import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
+import org.apache.pinot.spi.utils.CommonConstants.Query.Request.MetadataKeys;
 import org.apache.pinot.tsdb.spi.AggInfo;
 import org.apache.pinot.tsdb.spi.RangeTimeSeriesRequest;
 import org.apache.pinot.tsdb.spi.TimeBuckets;
@@ -100,6 +102,24 @@ public class PhysicalTimeSeriesServerPlanVisitorTest {
     }
   }
 
+  @Test
+  public void testLeafRequestCarriesOptionalSegments() {
+    PhysicalTimeSeriesServerPlanVisitor serverPlanVisitor = new 
PhysicalTimeSeriesServerPlanVisitor(
+        mock(QueryExecutor.class), mock(ExecutorService.class), 
mock(ServerMetrics.class));
+    LeafTimeSeriesPlanNode leafNode = new LeafTimeSeriesPlanNode("leaf", 
List.of(), "orderTable", "orderTime",
+        TimeUnit.SECONDS, 0L, "", "orderCount", new AggInfo("SUM", false, 
Map.of()), List.of(), SERIES_LIMIT,
+        QUERY_OPTIONS);
+    TimeSeriesExecutionContext context =
+        new TimeSeriesExecutionContext(LANGUAGE, TimeBuckets.ofSeconds(1000L, 
Duration.ofSeconds(10), 100),
+            DUMMY_DEADLINE_MS, Map.of(MetadataKeys.REQUEST_ID, "1", 
MetadataKeys.BROKER_ID, "broker"),
+            Map.of("leaf", List.of("seg1")), Map.of("leaf", List.of("seg2")), 
Map.of());
+
+    ServerQueryRequest request = 
serverPlanVisitor.compileLeafServerQueryRequest(leafNode, context);
+
+    assertEquals(request.getSegmentsToQuery(), List.of("seg1"));
+    assertEquals(request.getOptionalSegments(), List.of("seg2"));
+  }
+
   private boolean isNumber(String s) {
     try {
       Long.parseLong(s);
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperatorTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperatorTest.java
index 02e24a2dad5..5407227b2c3 100644
--- 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperatorTest.java
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/runtime/timeseries/TimeSeriesExchangeReceiveOperatorTest.java
@@ -25,6 +25,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.TimeoutException;
 import org.apache.pinot.tsdb.spi.AggInfo;
 import org.apache.pinot.tsdb.spi.TimeBuckets;
@@ -47,6 +48,27 @@ public class TimeSeriesExchangeReceiveOperatorTest {
   private static final Long SF_SERIES_HASH = TimeSeries.hash(SF_SERIES_VALUES);
   private static final SimpleTimeSeriesBuilderFactory SERIES_BUILDER_FACTORY = 
new SimpleTimeSeriesBuilderFactory();
 
+  @Test
+  public void testNoServerQueriedReturnsEmptyBlockWithoutWaiting() {
+    // A plan node no server holds segments for: nothing will arrive, so the 
operator must not wait for the deadline.
+    BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1);
+    long deadlineMs = System.currentTimeMillis() + 60_000L;
+    for (AggInfo aggInfo : new AggInfo[]{SUM_AGG_INFO, null}) {
+      TimeSeriesExchangeReceiveOperator operator = new 
TimeSeriesExchangeReceiveOperator(blockingQueue, deadlineMs, 0,
+          aggInfo, SERIES_BUILDER_FACTORY, TIME_BUCKETS);
+      long startMs = System.currentTimeMillis();
+
+      TimeSeriesBlock block = operator.nextBlock();
+
+      assertTrue(System.currentTimeMillis() - startMs < 10_000L, "must not 
wait for the deadline");
+      assertEquals(block.getTimeBuckets(), TIME_BUCKETS);
+      assertTrue(block.getSeriesMap().isEmpty());
+      assertTrue(block.getExceptions().isEmpty());
+    }
+    assertThrows(IllegalArgumentException.class, () -> new 
TimeSeriesExchangeReceiveOperator(blockingQueue,
+        deadlineMs, 0, SUM_AGG_INFO, SERIES_BUILDER_FACTORY, null));
+  }
+
   @Test
   public void testGetNextBlockWithAggregation() {
     // Setup test
@@ -54,7 +76,7 @@ public class TimeSeriesExchangeReceiveOperatorTest {
     ArrayBlockingQueue<Object> blockingQueue = new 
ArrayBlockingQueue<>(NUM_SERVERS_QUERIED);
     blockingQueue.addAll(generateTimeSeriesBlocks());
     TimeSeriesExchangeReceiveOperator operator = new 
TimeSeriesExchangeReceiveOperator(blockingQueue, deadlineMs,
-        NUM_SERVERS_QUERIED, SUM_AGG_INFO, SERIES_BUILDER_FACTORY);
+        NUM_SERVERS_QUERIED, SUM_AGG_INFO, SERIES_BUILDER_FACTORY, 
TIME_BUCKETS);
     // Run test
     TimeSeriesBlock block = operator.nextBlock();
     // Validate results
@@ -78,7 +100,7 @@ public class TimeSeriesExchangeReceiveOperatorTest {
     ArrayBlockingQueue<Object> blockingQueue = new 
ArrayBlockingQueue<>(NUM_SERVERS_QUERIED);
     blockingQueue.addAll(generateTimeSeriesBlocks());
     TimeSeriesExchangeReceiveOperator operator = new 
TimeSeriesExchangeReceiveOperator(blockingQueue, deadlineMs,
-        NUM_SERVERS_QUERIED, null, SERIES_BUILDER_FACTORY);
+        NUM_SERVERS_QUERIED, null, SERIES_BUILDER_FACTORY, TIME_BUCKETS);
     // Run test
     TimeSeriesBlock block = operator.nextBlock();
     // Validate results
@@ -106,7 +128,7 @@ public class TimeSeriesExchangeReceiveOperatorTest {
     // Run test with aggregation
     try {
       TimeSeriesExchangeReceiveOperator operator = new 
TimeSeriesExchangeReceiveOperator(blockingQueue, deadlineMs,
-          NUM_SERVERS_QUERIED, SUM_AGG_INFO, SERIES_BUILDER_FACTORY);
+          NUM_SERVERS_QUERIED, SUM_AGG_INFO, SERIES_BUILDER_FACTORY, 
TIME_BUCKETS);
       TimeSeriesBlock block = operator.nextBlock();
       fail();
     } catch (Throwable t) {
@@ -115,7 +137,7 @@ public class TimeSeriesExchangeReceiveOperatorTest {
     blockingQueue.add(new TimeoutException("Test error"));
     try {
       TimeSeriesExchangeReceiveOperator operator = new 
TimeSeriesExchangeReceiveOperator(blockingQueue, deadlineMs,
-          NUM_SERVERS_QUERIED, null, SERIES_BUILDER_FACTORY);
+          NUM_SERVERS_QUERIED, null, SERIES_BUILDER_FACTORY, TIME_BUCKETS);
       TimeSeriesBlock block = operator.nextBlock();
       fail();
     } catch (Throwable t) {
diff --git 
a/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcherMetadataTest.java
 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcherMetadataTest.java
new file mode 100644
index 00000000000..09415270aea
--- /dev/null
+++ 
b/pinot-query-runtime/src/test/java/org/apache/pinot/query/service/dispatch/timeseries/TimeSeriesQueryDispatcherMetadataTest.java
@@ -0,0 +1,54 @@
+/**
+ * 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.pinot.query.service.dispatch.timeseries;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import org.apache.pinot.spi.trace.RequestContext;
+import org.apache.pinot.spi.utils.CommonConstants.Query.Request.MetadataKeys;
+import org.apache.pinot.tsdb.planner.physical.TimeSeriesDispatchablePlan;
+import org.apache.pinot.tsdb.spi.TimeBuckets;
+import org.testng.annotations.Test;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+
+/// The segment lists a server receives with a time-series query.
+public class TimeSeriesQueryDispatcherMetadataTest {
+  @Test
+  public void testSegmentListsInServerMetadata() {
+    // Server_1 reads leafA from required and optional (not yet ONLINE) 
segments.
+    TimeSeriesDispatchablePlan plan = new TimeSeriesDispatchablePlan("m3ql", 
List.of(), null, List.of(), false,
+        TimeBuckets.ofSeconds(1000L, Duration.ofSeconds(10), 6),
+        Map.of("Server_1", Map.of("leafA", List.of("seg1", "seg2"))),
+        Map.of("Server_1", Map.of("leafA", List.of("seg3"))), Map.of(), 
List.of());
+    RequestContext requestContext = mock(RequestContext.class);
+    when(requestContext.getRequestId()).thenReturn(7L);
+    when(requestContext.getBrokerId()).thenReturn("broker");
+
+    Map<String, String> metadata =
+        TimeSeriesQueryDispatcher.initializeTimeSeriesMetadataMap(plan, 1000L, 
requestContext, "Server_1");
+
+    
assertEquals(metadata.get(MetadataKeys.TimeSeries.encodeSegmentListKey("leafA")),
 "seg1,seg2");
+    
assertEquals(metadata.get(MetadataKeys.TimeSeries.encodeOptionalSegmentListKey("leafA")),
 "seg3");
+  }
+}
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index cb2ac964d5e..8bf337227c9 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -2775,6 +2775,24 @@ public class CommonConstants {
           public static String decodeSegmentListKey(String key) {
             return key.substring(SEGMENT_MAP_ENTRY_PREFIX.length());
           }
+
+          /// Optional segments of a plan: segments the routing manager lets a 
server skip if it does not have them
+          /// yet, e.g. newly pushed segments not yet ONLINE in the external 
view. A server that does not know the key
+          /// ignores it and queries only the required segments.
+          public static final String OPTIONAL_SEGMENT_MAP_ENTRY_PREFIX = 
"$optionalSegmentMapEntry#";
+
+          public static boolean isKeyOptionalSegmentList(String key) {
+            return key.startsWith(OPTIONAL_SEGMENT_MAP_ENTRY_PREFIX);
+          }
+
+          public static String encodeOptionalSegmentListKey(String planId) {
+            return OPTIONAL_SEGMENT_MAP_ENTRY_PREFIX + planId;
+          }
+
+          /// Returns the plan-id corresponding to the encoded optional 
segment list key.
+          public static String decodeOptionalSegmentListKey(String key) {
+            return key.substring(OPTIONAL_SEGMENT_MAP_ENTRY_PREFIX.length());
+          }
         }
       }
 
diff --git a/pinot-timeseries/pinot-timeseries-planner/pom.xml 
b/pinot-timeseries/pinot-timeseries-planner/pom.xml
index 25212733c1c..1966a993b41 100644
--- a/pinot-timeseries/pinot-timeseries-planner/pom.xml
+++ b/pinot-timeseries/pinot-timeseries-planner/pom.xml
@@ -48,6 +48,11 @@
       <artifactId>testng</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.mockito</groupId>
+      <artifactId>mockito-core</artifactId>
+      <scope>test</scope>
+    </dependency>
     <dependency>
       <groupId>org.apache.pinot</groupId>
       <artifactId>pinot-query-planner</artifactId>
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironment.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironment.java
index c62b931765a..6b6026db44f 100644
--- 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironment.java
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironment.java
@@ -20,11 +20,14 @@ package org.apache.pinot.tsdb.planner;
 
 import com.google.common.base.Preconditions;
 import java.lang.reflect.Constructor;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Consumer;
 import org.apache.pinot.common.config.provider.TableCache;
 import org.apache.pinot.core.routing.ImplicitHybridTableRouteProvider;
 import org.apache.pinot.core.routing.RoutingManager;
@@ -33,12 +36,14 @@ import org.apache.pinot.spi.trace.RequestContext;
 import org.apache.pinot.tsdb.planner.physical.TableScanVisitor;
 import org.apache.pinot.tsdb.planner.physical.TimeSeriesDispatchablePlan;
 import org.apache.pinot.tsdb.planner.physical.TimeSeriesQueryServerInstance;
+import org.apache.pinot.tsdb.planner.physical.TimeSeriesRoutingCustomizer;
 import org.apache.pinot.tsdb.spi.PinotTimeSeriesConfiguration;
 import org.apache.pinot.tsdb.spi.RangeTimeSeriesRequest;
 import org.apache.pinot.tsdb.spi.TimeSeriesLogicalPlanResult;
 import org.apache.pinot.tsdb.spi.TimeSeriesLogicalPlanner;
 import org.apache.pinot.tsdb.spi.TimeSeriesMetadata;
 import org.apache.pinot.tsdb.spi.plan.BaseTimeSeriesPlanNode;
+import org.apache.pinot.tsdb.spi.plan.LeafTimeSeriesPlanNode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -47,12 +52,15 @@ public class TimeSeriesQueryEnvironment {
   private final RoutingManager _routingManager;
   private final TableCache _tableCache;
   private final TimeSeriesMetadata _metadataProvider;
+  private final TimeSeriesRoutingCustomizer _routingCustomizer;
   private final Map<String, TimeSeriesLogicalPlanner> _plannerMap = new 
HashMap<>();
 
-  public TimeSeriesQueryEnvironment(PinotConfiguration config, RoutingManager 
routingManager, TableCache tableCache) {
+  public TimeSeriesQueryEnvironment(PinotConfiguration config, RoutingManager 
routingManager, TableCache tableCache,
+      TimeSeriesRoutingCustomizer routingCustomizer) {
     _routingManager = routingManager;
     _tableCache = tableCache;
     _metadataProvider = new TimeSeriesTableMetadataProvider(_tableCache);
+    _routingCustomizer = routingCustomizer;
   }
 
   public void init(PinotConfiguration config) {
@@ -95,38 +103,80 @@ public class TimeSeriesQueryEnvironment {
     return _plannerMap.get(request.getLanguage()).plan(request, 
_metadataProvider);
   }
 
+  /// @param tableAuthorizer authorizes the query's tables, named with their 
type; it runs before any routing, so a
+  ///     caller who may not query a table gets its error before a 
[TimeSeriesRoutingCustomizer] does any work
   public TimeSeriesDispatchablePlan buildPhysicalPlan(RangeTimeSeriesRequest 
timeSeriesRequest,
-      RequestContext requestContext, TimeSeriesLogicalPlanResult logicalPlan) {
-    // Step-0: Add table type info to the logical plan.
+      RequestContext requestContext, TimeSeriesLogicalPlanResult logicalPlan, 
Consumer<List<String>> tableAuthorizer) {
+    // Step-0: Add table type info to the logical plan, and authorize the 
tables before routing them.
     logicalPlan = new 
TimeSeriesLogicalPlanResult(TableScanVisitor.INSTANCE.addTableTypeInfoToPlan(
       logicalPlan.getPlanNode(), requestContext), 
logicalPlan.getTimeBuckets());
+    tableAuthorizer.accept(leafTableNames(logicalPlan.getPlanNode()));
     // Step-1: Assign segments to servers for each leaf node.
-    TableScanVisitor.Context scanVisitorContext = 
TableScanVisitor.createContext(requestContext.getRequestId());
+    TableScanVisitor.Context scanVisitorContext =
+        TableScanVisitor.createContext(requestContext.getRequestId(), 
timeSeriesRequest.getQueryOptions(),
+            _routingCustomizer);
     TableScanVisitor.INSTANCE.assignSegmentsToPlan(logicalPlan.getPlanNode(), 
logicalPlan.getTimeBuckets(),
         scanVisitorContext);
+    // Step-1b: Send the query options the routing customizer added with every 
leaf.
+    logicalPlan = new 
TimeSeriesLogicalPlanResult(TableScanVisitor.INSTANCE.addQueryOptionsToPlan(
+        logicalPlan.getPlanNode(), 
scanVisitorContext.getRoutingQueryOptions()), logicalPlan.getTimeBuckets());
     List<TimeSeriesQueryServerInstance> serverInstances = 
scanVisitorContext.getQueryServers();
-    // Step-2: Create plan fragments.
+    Map<String, Map<String, List<String>>> leafIdToSegmentsByInstanceId =
+        scanVisitorContext.getLeafIdToSegmentsByInstanceId();
+    // Step-2: Create plan fragments. One server runs the whole plan only when 
it holds segments for every leaf: a
+    // leaf it holds none for must not run there, since its table may not be 
on that server, and must read nothing.
+    boolean wholePlanOnOneServer = serverInstances.size() == 1 && 
leafIdToSegmentsByInstanceId.get(
+        
serverInstances.get(0).getInstanceId()).keySet().containsAll(leafIds(logicalPlan.getPlanNode()));
     List<BaseTimeSeriesPlanNode> fragments = 
TimeSeriesPlanFragmenter.getFragments(
-        logicalPlan.getPlanNode(), serverInstances.size() == 1);
+        logicalPlan.getPlanNode(), wholePlanOnOneServer);
     // Step-3: Compute number of servers each exchange node will receive data 
from.
-    Map<String, Integer> numServersForExchangePlanNode = 
computeNumServersForExchangePlanNode(serverInstances,
-        fragments, scanVisitorContext.getLeafIdToSegmentsByInstanceId());
+    Map<String, Integer> numServersForExchangePlanNode = 
computeNumServersForExchangePlanNode(wholePlanOnOneServer,
+        fragments, leafIdToSegmentsByInstanceId);
     return new TimeSeriesDispatchablePlan(timeSeriesRequest.getLanguage(), 
serverInstances, fragments.get(0),
-        fragments.subList(1, fragments.size()), logicalPlan.getTimeBuckets(),
-        scanVisitorContext.getLeafIdToSegmentsByInstanceId(), 
numServersForExchangePlanNode,
-      scanVisitorContext.getTableNames());
+        fragments.subList(1, fragments.size()), wholePlanOnOneServer, 
logicalPlan.getTimeBuckets(),
+        leafIdToSegmentsByInstanceId, 
scanVisitorContext.getLeafIdToOptionalSegmentsByInstanceId(),
+        numServersForExchangePlanNode, scanVisitorContext.getTableNames());
   }
 
-  private Map<String, Integer> 
computeNumServersForExchangePlanNode(List<TimeSeriesQueryServerInstance> 
serverInstances,
+  /// The distinct tables the plan's leaves scan, in plan order.
+  private static List<String> leafTableNames(BaseTimeSeriesPlanNode planNode) {
+    Set<String> tableNames = new LinkedHashSet<>();
+    collectLeafTableNames(planNode, tableNames);
+    return new ArrayList<>(tableNames);
+  }
+
+  private static Set<String> leafIds(BaseTimeSeriesPlanNode planNode) {
+    Set<String> leafIds = new HashSet<>();
+    collectLeafIds(planNode, leafIds);
+    return leafIds;
+  }
+
+  private static void collectLeafIds(BaseTimeSeriesPlanNode planNode, 
Set<String> leafIds) {
+    if (planNode instanceof LeafTimeSeriesPlanNode) {
+      leafIds.add(planNode.getId());
+    }
+    for (BaseTimeSeriesPlanNode input : planNode.getInputs()) {
+      collectLeafIds(input, leafIds);
+    }
+  }
+
+  private static void collectLeafTableNames(BaseTimeSeriesPlanNode planNode, 
Set<String> tableNames) {
+    if (planNode instanceof LeafTimeSeriesPlanNode) {
+      tableNames.add(((LeafTimeSeriesPlanNode) planNode).getTableName());
+    }
+    for (BaseTimeSeriesPlanNode input : planNode.getInputs()) {
+      collectLeafTableNames(input, tableNames);
+    }
+  }
+
+  private Map<String, Integer> computeNumServersForExchangePlanNode(boolean 
wholePlanOnOneServer,
       List<BaseTimeSeriesPlanNode> planNodes, Map<String, Map<String, 
List<String>>> leafIdToSegmentsByInstanceId) {
-    // TODO(timeseries): Handle this gracefully and return an empty block.
-    Preconditions.checkState(!serverInstances.isEmpty(), "No servers selected 
for the query");
-    if (serverInstances.size() == 1) {
+    if (wholePlanOnOneServer) {
       // For single-server case, the broker fragment consists only of the 
TimeSeriesExchangeNode.
       return Map.of(planNodes.get(0).getId(), 1);
     }
-    // For the multi-server case, the leafIdToSegmentsByInstanceId map already 
has the information we need, but we
-    // just need to restructure it so that we can get number of servers by 
planId.
+    // Otherwise each leaf is its own fragment. The 
leafIdToSegmentsByInstanceId map already has the information we
+    // need, but we just need to restructure it so that we can get number of 
servers by planId.
     Map<String, Set<String>> planIdToServers = new HashMap<>();
     for (var entry : leafIdToSegmentsByInstanceId.entrySet()) {
       String instanceId = entry.getKey();
@@ -136,6 +186,11 @@ public class TimeSeriesQueryEnvironment {
       }
     }
     Map<String, Integer> result = new HashMap<>();
+    // A leaf no server holds segments for still gets an exchange; it receives 
from no server and yields no data, as a
+    // range with no data does. With no server at all, every leaf is such a 
leaf.
+    for (BaseTimeSeriesPlanNode serverFragment : planNodes.subList(1, 
planNodes.size())) {
+      result.put(serverFragment.getId(), 0);
+    }
     for (var entry : planIdToServers.entrySet()) {
       result.put(entry.getKey(), entry.getValue().size());
     }
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitor.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitor.java
index 6647cd12f70..cb53ab2683b 100644
--- 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitor.java
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitor.java
@@ -18,8 +18,10 @@
  */
 package org.apache.pinot.tsdb.planner.physical;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -33,9 +35,13 @@ import org.apache.pinot.common.request.PinotQuery;
 import org.apache.pinot.common.request.QuerySource;
 import org.apache.pinot.core.routing.RoutingManager;
 import org.apache.pinot.core.routing.RoutingTable;
+import org.apache.pinot.core.routing.SegmentsToQuery;
 import org.apache.pinot.core.routing.TableRouteInfo;
 import org.apache.pinot.core.routing.TableRouteProvider;
 import org.apache.pinot.core.transport.ServerInstance;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
 import org.apache.pinot.spi.trace.RequestContext;
 import org.apache.pinot.sql.parsers.CalciteSqlParser;
 import org.apache.pinot.tsdb.spi.TimeBuckets;
@@ -63,15 +69,35 @@ public class TableScanVisitor {
       LeafTimeSeriesPlanNode sfpNode = (LeafTimeSeriesPlanNode) planNode;
       Expression filterExpression = 
CalciteSqlParser.compileToExpression(sfpNode.getEffectiveFilter(timeBuckets));
       context.addTableName(sfpNode.getTableName());
-      RoutingTable routingTable = _routingManager.getRoutingTable(
-          compileBrokerRequest(sfpNode.getTableName(), filterExpression),
-          context._requestId);
+      RoutingTable routingTable = 
_routingManager.getRoutingTableWithMissingServerSegments(
+          compileBrokerRequest(sfpNode.getTableName(), filterExpression), 
context._requestId);
       Preconditions.checkNotNull(routingTable, "Failed to get routing table 
for table: " + sfpNode.getTableName());
+      routingTable = customizeRouting(sfpNode, routingTable, context);
+      // A later callback can still hold references to this leaf's routing 
lists.
+      boolean copyAssignments = context._routingCustomizer != 
TimeSeriesRoutingCustomizer.NO_OP;
+      boolean hasRequiredSegments = false;
       for (var entry : 
routingTable.getServerInstanceToSegmentsMap().entrySet()) {
         ServerInstance serverInstance = entry.getKey();
         List<String> segments = entry.getValue().getSegments();
+        // The exchange waits for each dispatched server. Optional segments 
alone cannot require an RPC.
+        if (segments == null || segments.isEmpty()) {
+          continue;
+        }
+        hasRequiredSegments = true;
+        List<String> optionalSegments = entry.getValue().getOptionalSegments();
         context.getLeafIdToSegmentsByServer().computeIfAbsent(serverInstance, 
(x) -> new HashMap<>())
-            .put(sfpNode.getId(), segments);
+            .put(sfpNode.getId(), copyAssignments ? List.copyOf(segments) : 
segments);
+        if (optionalSegments != null && !optionalSegments.isEmpty()) {
+          
context._leafIdToOptionalSegmentsByServer.computeIfAbsent(serverInstance, (x) 
-> new HashMap<>())
+              .put(sfpNode.getId(), copyAssignments ? 
List.copyOf(optionalSegments) : optionalSegments);
+        }
+      }
+      List<String> unavailableSegments = routingTable.getUnavailableSegments();
+      if (!hasRequiredSegments && unavailableSegments != null && 
!unavailableSegments.isEmpty()) {
+        // Optional segments may still be loading. Their assignments do not 
cover unavailable required segments.
+        throw new QueryException(QueryErrorCode.SERVER_SEGMENT_MISSING, 
String.format(
+            "No server can serve %d unavailable segment(s) of table: %s", 
unavailableSegments.size(),
+            sfpNode.getTableName()));
       }
     }
     for (BaseTimeSeriesPlanNode childNode : planNode.getInputs()) {
@@ -79,6 +105,75 @@ public class TableScanVisitor {
     }
   }
 
+  private RoutingTable customizeRouting(LeafTimeSeriesPlanNode leaf, 
RoutingTable routingTable, Context context) {
+    TimeSeriesRoutingCustomizer customizer = context._routingCustomizer;
+    if (customizer == TimeSeriesRoutingCustomizer.NO_OP) {
+      return routingTable;
+    }
+    String tableName = leaf.getTableName();
+    TableConfig tableConfig = _tableCache.getTableConfig(tableName);
+    if (tableConfig == null) {
+      throw QueryErrorCode.BROKER_RESOURCE_MISSING.asException("Table config 
not found for " + tableName);
+    }
+    // Upsert execution adds recently loaded segments on the server. Snapshot 
the assignments before the hook
+    // so that it cannot accidentally narrow an upsert scan, including by 
modifying the routing table in place.
+    RoutingAssignments original = tableConfig.isUpsertEnabled() ? 
RoutingAssignments.snapshot(routingTable) : null;
+    RoutingTable customized = 
Preconditions.checkNotNull(customizer.customize(leaf, routingTable,
+        context._routingContext), "Routing customizer returned no routing for 
table: " + tableName);
+    if (original != null && 
!original.equals(RoutingAssignments.snapshot(customized))) {
+      throw QueryErrorCode.QUERY_VALIDATION.asException(
+          "Time-series routing cannot change segment assignments for upsert 
table " + tableName);
+    }
+    return customized;
+  }
+
+  private record SegmentAssignment(List<String> required, List<String> 
optional) {
+  }
+
+  private record RoutingAssignments(Map<ServerInstance, SegmentAssignment> 
byServer, List<String> unavailable) {
+    private static RoutingAssignments snapshot(RoutingTable routingTable) {
+      Map<ServerInstance, SegmentAssignment> byServer = new HashMap<>();
+      for (var entry : 
routingTable.getServerInstanceToSegmentsMap().entrySet()) {
+        SegmentsToQuery segments = entry.getValue();
+        byServer.put(entry.getKey(),
+            new SegmentAssignment(copySegments(segments.getSegments()), 
copySegments(segments.getOptionalSegments())));
+      }
+      return new RoutingAssignments(byServer, 
copySegments(routingTable.getUnavailableSegments()));
+    }
+
+    private static List<String> copySegments(@Nullable List<String> segments) {
+      return segments == null ? List.of() : List.copyOf(segments);
+    }
+  }
+
+  /// Adds the query options the [TimeSeriesRoutingCustomizer] collected 
during [#assignSegmentsToPlan] to every leaf,
+  /// so the servers receive them. Returns the plan unchanged when there are 
none. A collected option replaces a leaf's
+  /// own option with the same key.
+  ///
+  /// @param planNode The [BaseTimeSeriesPlanNode] to process.
+  /// @param queryOptions The options collected for the query, from 
[Context#getRoutingQueryOptions()].
+  /// @return The plan with the options added to every leaf.
+  public BaseTimeSeriesPlanNode addQueryOptionsToPlan(BaseTimeSeriesPlanNode 
planNode,
+      Map<String, String> queryOptions) {
+    if (queryOptions.isEmpty()) {
+      return planNode;
+    }
+    if (planNode instanceof LeafTimeSeriesPlanNode) {
+      LeafTimeSeriesPlanNode leafNode = (LeafTimeSeriesPlanNode) planNode;
+      Map<String, String> leafQueryOptions = new HashMap<>();
+      if (leafNode.getQueryOptions() != null) {
+        leafQueryOptions.putAll(leafNode.getQueryOptions());
+      }
+      leafQueryOptions.putAll(queryOptions);
+      return leafNode.withQueryOptions(leafQueryOptions);
+    }
+    List<BaseTimeSeriesPlanNode> newInputs = new ArrayList<>();
+    for (BaseTimeSeriesPlanNode childNode : planNode.getInputs()) {
+      newInputs.add(addQueryOptionsToPlan(childNode, queryOptions));
+    }
+    return planNode.withInputs(newInputs);
+  }
+
   /// Adds table type information (offline/realtime) to the plan node.
   /// If the plan node is a leaf node, it retrieves the table route info and 
updates the table name with type.
   /// If the plan node has child nodes, it recursively processes each child 
node.
@@ -121,17 +216,43 @@ public class TableScanVisitor {
     return null;
   }
 
-  public static Context createContext(Long requestId) {
-    return new Context(requestId);
+  public static Context createContext(Long requestId, @Nullable Map<String, 
String> requestQueryOptions,
+      TimeSeriesRoutingCustomizer routingCustomizer) {
+    return new Context(requestId, requestQueryOptions, routingCustomizer);
   }
 
   public static class Context {
     private final Map<ServerInstance, Map<String, List<String>>> 
_leafIdToSegmentsByServer = new HashMap<>();
+    private final Map<ServerInstance, Map<String, List<String>>> 
_leafIdToOptionalSegmentsByServer = new HashMap<>();
     private final Long _requestId;
     private final List<String> _tableNames = new ArrayList<>();
+    private final Map<String, String> _requestQueryOptions;
+    private final Map<String, String> _routingQueryOptions = new HashMap<>();
+    private final TimeSeriesRoutingCustomizer _routingCustomizer;
+    // The customizer's view of this query, so it cannot reach the planner's 
own state through the context.
+    private final TimeSeriesRoutingContext _routingContext = new 
TimeSeriesRoutingContext() {
+      @Override
+      public Map<String, String> getRequestQueryOptions() {
+        return _requestQueryOptions;
+      }
+
+      @Override
+      public Map<String, String> getRoutingQueryOptions() {
+        return Collections.unmodifiableMap(_routingQueryOptions);
+      }
+
+      @Override
+      public void putRoutingQueryOption(String key, String value) {
+        _routingQueryOptions.put(key, value);
+      }
+    };
 
-    public Context(Long requestId) {
+    public Context(Long requestId, @Nullable Map<String, String> 
requestQueryOptions,
+        TimeSeriesRoutingCustomizer routingCustomizer) {
       _requestId = requestId;
+      _requestQueryOptions =
+          requestQueryOptions == null ? Map.of() : 
Collections.unmodifiableMap(new HashMap<>(requestQueryOptions));
+      _routingCustomizer = routingCustomizer;
     }
 
     public List<TimeSeriesQueryServerInstance> getQueryServers() {
@@ -140,8 +261,18 @@ public class TableScanVisitor {
     }
 
     public Map<String, Map<String, List<String>>> 
getLeafIdToSegmentsByInstanceId() {
+      return byInstanceId(_leafIdToSegmentsByServer);
+    }
+
+    /// Per server, the non-empty optional segments of each leaf: segments the 
server queries if it has them.
+    public Map<String, Map<String, List<String>>> 
getLeafIdToOptionalSegmentsByInstanceId() {
+      return byInstanceId(_leafIdToOptionalSegmentsByServer);
+    }
+
+    private static Map<String, Map<String, List<String>>> byInstanceId(
+        Map<ServerInstance, Map<String, List<String>>> byServer) {
       Map<String, Map<String, List<String>>> result = new HashMap<>();
-      for (var entry : _leafIdToSegmentsByServer.entrySet()) {
+      for (var entry : byServer.entrySet()) {
         result.put(entry.getKey().getInstanceId(), entry.getValue());
       }
       return result;
@@ -158,6 +289,23 @@ public class TableScanVisitor {
     public void addTableName(String tableName) {
       _tableNames.add(tableName);
     }
+
+    /// The query options of the request, read-only.
+    @VisibleForTesting
+    Map<String, String> getRequestQueryOptions() {
+      return _requestQueryOptions;
+    }
+
+    /// Query options the [TimeSeriesRoutingCustomizer] added while routing 
the leaves of this query, read-only.
+    public Map<String, String> getRoutingQueryOptions() {
+      return Collections.unmodifiableMap(_routingQueryOptions);
+    }
+
+    /// What the [TimeSeriesRoutingCustomizer] sees of this query.
+    @VisibleForTesting
+    TimeSeriesRoutingContext getRoutingContext() {
+      return _routingContext;
+    }
   }
 
   private BrokerRequest compileBrokerRequest(String tableName, Expression 
filterExpression) {
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesDispatchablePlan.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesDispatchablePlan.java
index a8e3c494d73..626893e518c 100644
--- 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesDispatchablePlan.java
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesDispatchablePlan.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.tsdb.planner.physical;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
@@ -31,22 +32,32 @@ public class TimeSeriesDispatchablePlan {
   private final String _language;
   private final BaseTimeSeriesPlanNode _brokerFragment;
   private final List<BaseTimeSeriesPlanNode> _serverFragments;
+  private final boolean _wholePlanOnOneServer;
   private final TimeBuckets _timeBuckets;
   private final Map<String, Map<String, List<String>>> 
_leafIdToSegmentsByInstanceId;
+  private final Map<String, Map<String, List<String>>> 
_leafIdToOptionalSegmentsByInstanceId;
   private final Map<String, Integer> _numInputServersForExchangePlanNode;
   private final List<String> _serializedServerFragments;
   private final List<String> _tableNames;
 
+  /// @param wholePlanOnOneServer whether the query's one server runs the 
whole plan, which needs it to hold segments
+  ///     for every leaf; the server fragments are then the whole plan rather 
than one fragment per leaf
+  /// @param leafIdToSegmentsByInstanceId per server, the non-empty required 
segments of each leaf it reads
+  /// @param leafIdToOptionalSegmentsByInstanceId per server, the optional 
segments of leaves with required segments
   public TimeSeriesDispatchablePlan(String language, 
List<TimeSeriesQueryServerInstance> queryServerInstances,
       BaseTimeSeriesPlanNode brokerFragment, List<BaseTimeSeriesPlanNode> 
serverFragments,
-      TimeBuckets initialTimeBuckets, Map<String, Map<String, List<String>>> 
leafIdToSegmentsByInstanceId,
+      boolean wholePlanOnOneServer, TimeBuckets initialTimeBuckets,
+      Map<String, Map<String, List<String>>> leafIdToSegmentsByInstanceId,
+      Map<String, Map<String, List<String>>> 
leafIdToOptionalSegmentsByInstanceId,
       Map<String, Integer> numInputServersForExchangePlanNode, List<String> 
tableNames) {
     _language = language;
     _queryServerInstances = queryServerInstances;
     _brokerFragment = brokerFragment;
     _serverFragments = serverFragments;
+    _wholePlanOnOneServer = wholePlanOnOneServer;
     _timeBuckets = initialTimeBuckets;
     _leafIdToSegmentsByInstanceId = leafIdToSegmentsByInstanceId;
+    _leafIdToOptionalSegmentsByInstanceId = 
leafIdToOptionalSegmentsByInstanceId;
     _numInputServersForExchangePlanNode = numInputServersForExchangePlanNode;
     _serializedServerFragments = 
serverFragments.stream().map(TimeSeriesPlanSerde::serialize).collect(
         Collectors.toList());
@@ -69,8 +80,22 @@ public class TimeSeriesDispatchablePlan {
     return _serverFragments;
   }
 
-  public List<String> getSerializedServerFragments() {
-    return _serializedServerFragments;
+  /// The serialized fragments a server runs: the whole plan when the query's 
one server holds segments for every leaf,
+  /// else the fragments of the leaves it holds segments for. A server sends 
one block per fragment it runs, and each
+  /// exchange waits for one block from each server holding its leaf, so a 
server that ran a leaf it holds no segments
+  /// for would send an extra block that the exchange could take in place of a 
server's real data.
+  public List<String> getSerializedServerFragments(String instanceId) {
+    if (_wholePlanOnOneServer) {
+      return _serializedServerFragments;
+    }
+    Map<String, List<String>> segmentsByLeafId = 
_leafIdToSegmentsByInstanceId.getOrDefault(instanceId, Map.of());
+    List<String> fragments = new ArrayList<>();
+    for (int i = 0; i < _serverFragments.size(); i++) {
+      if (segmentsByLeafId.containsKey(_serverFragments.get(i).getId())) {
+        fragments.add(_serializedServerFragments.get(i));
+      }
+    }
+    return fragments;
   }
 
   public TimeBuckets getTimeBuckets() {
@@ -81,6 +106,10 @@ public class TimeSeriesDispatchablePlan {
     return _leafIdToSegmentsByInstanceId;
   }
 
+  public Map<String, Map<String, List<String>>> 
getLeafIdToOptionalSegmentsByInstanceId() {
+    return _leafIdToOptionalSegmentsByInstanceId;
+  }
+
   public Map<String, Integer> getNumInputServersForExchangePlanNode() {
     return _numInputServersForExchangePlanNode;
   }
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesRoutingContext.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesRoutingContext.java
new file mode 100644
index 00000000000..08182fe37a3
--- /dev/null
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesRoutingContext.java
@@ -0,0 +1,37 @@
+/**
+ * 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.pinot.tsdb.planner.physical;
+
+import java.util.Map;
+
+
+/// What a [TimeSeriesRoutingCustomizer] sees of the time-series query being 
planned. One instance per query, used by
+/// one planning thread.
+public interface TimeSeriesRoutingContext {
+  /// The query options of the request, read-only.
+  Map<String, String> getRequestQueryOptions();
+
+  /// Query options added while routing the leaves of this query, read-only. 
They are sent to the servers with every
+  /// leaf of the query, replacing a leaf's own option with the same key. A 
later leaf sees what an earlier one added.
+  Map<String, String> getRoutingQueryOptions();
+
+  /// Adds or replaces a routing query option. It applies to every leaf of the 
query, so a value that differs per
+  /// table should be keyed by table inside the value.
+  void putRoutingQueryOption(String key, String value);
+}
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesRoutingCustomizer.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesRoutingCustomizer.java
new file mode 100644
index 00000000000..994dd3d8e56
--- /dev/null
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/main/java/org/apache/pinot/tsdb/planner/physical/TimeSeriesRoutingCustomizer.java
@@ -0,0 +1,51 @@
+/**
+ * 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.pinot.tsdb.planner.physical;
+
+import org.apache.pinot.core.routing.RoutingTable;
+import org.apache.pinot.tsdb.spi.plan.LeafTimeSeriesPlanNode;
+
+
+/// Broker hook that adjusts how each leaf of a time-series query is routed, 
after the routing manager has picked
+/// its segments. A broker can narrow a leaf to a subset of segments and add 
query options the servers need to read
+/// them. For example, a table format with snapshots can pin every leaf of a 
query to one snapshot and tell the servers
+/// which one, the way the single-stage engine lets a broker rewrite its 
routing and server query options.
+///
+/// [TableScanVisitor] calls it once per leaf, in plan order, on the broker 
thread that plans the query: after the
+/// query's tables are authorized and before anything is dispatched to 
servers. The [TimeSeriesRoutingContext] carries
+/// the request's query options (read-only) and the routing query options: 
entries added there are sent to the servers
+/// with every leaf of the query, replacing a leaf's own option with the same 
key. A later leaf sees what an earlier one
+/// added, so an implementation can keep all leaves of a query consistent. One 
customizer serves every query of a
+/// broker, so it must be thread-safe.
+public interface TimeSeriesRoutingCustomizer {
+  /// Routes every leaf exactly as the routing manager chose and adds no query 
options.
+  TimeSeriesRoutingCustomizer NO_OP = (leaf, routingTable, context) -> 
routingTable;
+
+  /// A leaf dispatches to servers assigned required segments. Optional 
segments travel only to those servers.
+  /// A leaf with no required assignments yields no data unless the routing 
reports unavailable segments.
+  ///
+  /// For upsert tables the customizer can add query options but must preserve 
the required, optional, and
+  /// unavailable segment assignments. Upsert execution can include recently 
loaded segments on the server.
+  ///
+  /// @param leaf the leaf being routed; its table name carries the table type
+  /// @param routingTable the routing the routing manager chose for the leaf
+  /// @param context the query being planned; add options for the servers to 
its routing query options
+  /// @return the routing to use for the leaf, never null
+  RoutingTable customize(LeafTimeSeriesPlanNode leaf, RoutingTable 
routingTable, TimeSeriesRoutingContext context);
+}
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/test/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironmentTest.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/test/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironmentTest.java
new file mode 100644
index 00000000000..3fbdb02423d
--- /dev/null
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/test/java/org/apache/pinot/tsdb/planner/TimeSeriesQueryEnvironmentTest.java
@@ -0,0 +1,377 @@
+/**
+ * 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.pinot.tsdb.planner;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.common.config.provider.TableCache;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.core.routing.RoutingManager;
+import org.apache.pinot.core.routing.RoutingTable;
+import org.apache.pinot.core.routing.SegmentsToQuery;
+import org.apache.pinot.core.transport.ServerInstance;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
+import org.apache.pinot.spi.trace.RequestContext;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
+import org.apache.pinot.tsdb.planner.physical.TimeSeriesDispatchablePlan;
+import org.apache.pinot.tsdb.planner.physical.TimeSeriesRoutingCustomizer;
+import org.apache.pinot.tsdb.spi.AggInfo;
+import org.apache.pinot.tsdb.spi.PinotTimeSeriesConfiguration;
+import org.apache.pinot.tsdb.spi.RangeTimeSeriesRequest;
+import org.apache.pinot.tsdb.spi.TimeBuckets;
+import org.apache.pinot.tsdb.spi.TimeSeriesLogicalPlanResult;
+import org.apache.pinot.tsdb.spi.TimeSeriesLogicalPlanner;
+import org.apache.pinot.tsdb.spi.TimeSeriesMetadata;
+import org.apache.pinot.tsdb.spi.operator.BaseTimeSeriesOperator;
+import org.apache.pinot.tsdb.spi.plan.BaseTimeSeriesPlanNode;
+import org.apache.pinot.tsdb.spi.plan.LeafTimeSeriesPlanNode;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// Plans a time-series query end to end with a routing customizer, and checks 
that what the customizer decides reaches
+/// the plan the broker dispatches to servers.
+@Test(singleThreaded = true)
+public class TimeSeriesQueryEnvironmentTest {
+  private static final String LANGUAGE = "test";
+  private static final String TABLE = "myTable_OFFLINE";
+  private static final TimeBuckets TIME_BUCKETS = TimeBuckets.ofSeconds(1000L, 
Duration.ofSeconds(10), 6);
+
+  @AfterMethod
+  public void tearDown() {
+    // Planning initializes the TableScanVisitor singleton; leave it 
initialized for other tests.
+    newEnvironment(mock(RoutingManager.class), mock(TableCache.class), 
TimeSeriesRoutingCustomizer.NO_OP);
+  }
+
+  @Test
+  public void testDispatchedLeafCarriesRoutingDecisions() {
+    ServerInstance server = mock(ServerInstance.class);
+    when(server.getInstanceId()).thenReturn("Server_1");
+    RoutingManager routingManager = mock(RoutingManager.class);
+    when(routingManager.routingExists(TABLE)).thenReturn(true);
+    Map<ServerInstance, SegmentsToQuery> routed = new HashMap<>();
+    routed.put(server, new SegmentsToQuery(List.of("seg1", "seg2"), 
List.of()));
+    
when(routingManager.getRoutingTableWithMissingServerSegments(any(BrokerRequest.class),
 anyLong()))
+        .thenReturn(new RoutingTable(routed, List.of(), 0));
+    TableCache tableCache = mock(TableCache.class);
+    when(tableCache.getTableConfig(TABLE))
+        .thenReturn(new 
TableConfigBuilder(TableType.OFFLINE).setTableName("myTable").build());
+    // Keeps only seg1, and pins the version the request asked for.
+    TimeSeriesRoutingCustomizer customizer = (leaf, routingTable, context) -> {
+      context.putRoutingQueryOption("pinnedVersion", 
context.getRequestQueryOptions().get("pinnedVersion"));
+      return new RoutingTable(Map.of(server, new 
SegmentsToQuery(List.of("seg1"), List.of())), List.of(), 1);
+    };
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache, customizer);
+    RangeTimeSeriesRequest request = new RangeTimeSeriesRequest(LANGUAGE, "q", 
1000L, 1060L, 10L,
+        Duration.ofSeconds(10), 100, 100, "q", Map.of("pinnedVersion", "7"));
+    RequestContext requestContext = mock(RequestContext.class);
+    when(requestContext.getRequestId()).thenReturn(1L);
+
+    TimeSeriesDispatchablePlan plan = environment.buildPhysicalPlan(request, 
requestContext,
+        new TimeSeriesLogicalPlanResult(leaf("myTable"), TIME_BUCKETS), 
tableNames -> { });
+
+    assertEquals(plan.getLeafIdToSegmentsByInstanceId(), Map.of("Server_1", 
Map.of("leaf", List.of("seg1"))));
+    assertEquals(plan.getServerFragments().size(), 1);
+    LeafTimeSeriesPlanNode dispatchedLeaf = (LeafTimeSeriesPlanNode) 
plan.getServerFragments().get(0);
+    assertEquals(dispatchedLeaf.getTableName(), TABLE);
+    assertEquals(dispatchedLeaf.getQueryOptions(), Map.of("numGroupsLimit", 
"100", "pinnedVersion", "7"));
+  }
+
+  @Test
+  public void testLeafNarrowedToNothingYieldsNoServersInsteadOfFailing() {
+    RoutingManager routingManager = 
routingManagerWith(Map.of(mockServer("Server_1"), List.of("seg1")));
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> new RoutingTable(Map.of(), List.of(), 
1));
+
+    TimeSeriesDispatchablePlan plan = environment.buildPhysicalPlan(request(), 
requestContext(),
+        new TimeSeriesLogicalPlanResult(leaf("leaf", "myTable"), 
TIME_BUCKETS), tableNames -> { });
+
+    // Nothing is dispatched; the broker's exchange for the leaf expects no 
server, so the query has no data.
+    assertTrue(plan.getQueryServerInstances().isEmpty());
+    assertEquals(plan.getNumInputServersForExchangePlanNode(), Map.of("leaf", 
0));
+  }
+
+  @Test
+  public void testOnlyTheLeafWithoutServersExpectsNone() {
+    ServerInstance serverOne = mockServer("Server_1");
+    ServerInstance serverTwo = mockServer("Server_2");
+    RoutingManager routingManager =
+        routingManagerWith(Map.of(serverOne, List.of("seg1"), serverTwo, 
List.of("seg2")));
+    // The right leaf is narrowed to nothing; the left one keeps both servers.
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> leaf.getId().equals("right") ? new 
RoutingTable(Map.of(), List.of(), 2)
+            : routingTable);
+    BaseTimeSeriesPlanNode root =
+        new TestPlanNode("root", List.of(leaf("left", "myTable"), 
leaf("right", "myTable")));
+
+    TimeSeriesDispatchablePlan plan = environment.buildPhysicalPlan(request(), 
requestContext(),
+        new TimeSeriesLogicalPlanResult(root, TIME_BUCKETS), tableNames -> { 
});
+
+    assertEquals(plan.getQueryServerInstances().size(), 2);
+    assertEquals(plan.getNumInputServersForExchangePlanNode(), Map.of("left", 
2, "right", 0));
+  }
+
+  @Test
+  public void testServerRunsOnlyTheLeavesItHoldsSegmentsFor() {
+    ServerInstance serverOne = mockServer("Server_1");
+    ServerInstance serverTwo = mockServer("Server_2");
+    RoutingManager routingManager =
+        routingManagerWith(Map.of(serverOne, List.of("seg1"), serverTwo, 
List.of("seg2")));
+    // Each leaf keeps one server: left reads Server_1, right reads Server_2.
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> new RoutingTable(
+            Map.of(leaf.getId().equals("left") ? serverOne : serverTwo,
+                new SegmentsToQuery(List.of(leaf.getId().equals("left") ? 
"seg1" : "seg2"), List.of())),
+            List.of(), 1));
+    BaseTimeSeriesPlanNode root =
+        new TestPlanNode("root", List.of(leaf("left", "myTable"), 
leaf("right", "myTable")));
+
+    TimeSeriesDispatchablePlan plan = environment.buildPhysicalPlan(request(), 
requestContext(),
+        new TimeSeriesLogicalPlanResult(root, TIME_BUCKETS), tableNames -> { 
});
+
+    // Each exchange waits for one block, so each server must run, and send a 
block for, only its own leaf.
+    assertEquals(plan.getNumInputServersForExchangePlanNode(), Map.of("left", 
1, "right", 1));
+    assertEquals(fragmentIds(plan.getSerializedServerFragments("Server_1")), 
List.of("left"));
+    assertEquals(fragmentIds(plan.getSerializedServerFragments("Server_2")), 
List.of("right"));
+  }
+
+  @Test
+  public void testOneServerRunsTheWholePlanOnlyWhenItHoldsEveryLeaf() {
+    RoutingManager routingManager = 
routingManagerWith(Map.of(mockServer("Server_1"), List.of("seg1")));
+    BaseTimeSeriesPlanNode root =
+        new TestPlanNode("root", List.of(leaf("left", "myTable"), 
leaf("right", "myTable")));
+
+    // Both leaves route to Server_1, so it runs the whole plan.
+    TimeSeriesDispatchablePlan wholePlan =
+        newEnvironment(routingManager, tableCache(), 
TimeSeriesRoutingCustomizer.NO_OP).buildPhysicalPlan(
+            request(), requestContext(), new TimeSeriesLogicalPlanResult(root, 
TIME_BUCKETS), tableNames -> { });
+    
assertEquals(fragmentIds(wholePlan.getSerializedServerFragments("Server_1")), 
List.of("root"));
+
+    // The right leaf is narrowed to nothing: Server_1 runs only the left 
leaf, and the right leaf reads nothing
+    // rather than whatever Server_1 holds of its table.
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> leaf.getId().equals("right") ? new 
RoutingTable(Map.of(), List.of(), 1)
+            : routingTable);
+    TimeSeriesDispatchablePlan plan = environment.buildPhysicalPlan(request(), 
requestContext(),
+        new TimeSeriesLogicalPlanResult(root, TIME_BUCKETS), tableNames -> { 
});
+    assertEquals(fragmentIds(plan.getSerializedServerFragments("Server_1")), 
List.of("left"));
+    assertEquals(plan.getNumInputServersForExchangePlanNode(), Map.of("left", 
1, "right", 0));
+  }
+
+  @Test
+  public void testCustomizerCannotAddAnOptionalOnlyRpc() {
+    ServerInstance serverOne = mockServer("Server_1");
+    ServerInstance serverTwo = mockServer("Server_2");
+    RoutingManager routingManager = routingManagerWith(Map.of(serverOne, 
List.of("seg1"), serverTwo, List.of("seg2")));
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> new RoutingTable(Map.of(
+            serverOne, new SegmentsToQuery(List.of("seg1"), 
List.of("optional1")),
+            serverTwo, new SegmentsToQuery(List.of(), List.of("optional2"))), 
List.of(), 1));
+
+    TimeSeriesDispatchablePlan plan = environment.buildPhysicalPlan(request(), 
requestContext(),
+        new TimeSeriesLogicalPlanResult(leaf("leaf", "myTable"), 
TIME_BUCKETS), tableNames -> { });
+
+    assertEquals(plan.getNumInputServersForExchangePlanNode(), Map.of("leaf", 
1));
+    assertEquals(plan.getQueryServerInstances().size(), 1);
+    assertEquals(plan.getQueryServerInstances().get(0).getInstanceId(), 
"Server_1");
+    assertEquals(plan.getLeafIdToOptionalSegmentsByInstanceId(),
+        Map.of("Server_1", Map.of("leaf", List.of("optional1"))));
+  }
+
+  @Test
+  public void testTablesAreAuthorizedBeforeRouting() {
+    List<String> events = new ArrayList<>();
+    RoutingManager routingManager = 
routingManagerWith(Map.of(mockServer("Server_1"), List.of("seg1")));
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> {
+          events.add("customize " + leaf.getTableName());
+          return routingTable;
+        });
+
+    environment.buildPhysicalPlan(request(), requestContext(),
+        new TimeSeriesLogicalPlanResult(leaf("leaf", "myTable"), TIME_BUCKETS),
+        tableNames -> events.add("authorize " + tableNames));
+    assertEquals(events, List.of("authorize [" + TABLE + "]", "customize " + 
TABLE));
+
+    // A caller who may not query the table never reaches the customizer.
+    events.clear();
+    assertThrows(SecurityException.class, () -> 
environment.buildPhysicalPlan(request(), requestContext(),
+        new TimeSeriesLogicalPlanResult(leaf("leaf", "myTable"), 
TIME_BUCKETS), tableNames -> {
+          throw new SecurityException("denied");
+        }));
+    assertEquals(events, List.of());
+  }
+
+  @Test
+  public void testLeafWithOnlyUnavailableSegmentsFailsTheQuery() {
+    // No server can serve the leaf's segments: an outage, which must not read 
as a range without data.
+    RoutingManager routingManager = mock(RoutingManager.class);
+    when(routingManager.routingExists(TABLE)).thenReturn(true);
+    
when(routingManager.getRoutingTableWithMissingServerSegments(any(BrokerRequest.class),
 anyLong()))
+        .thenReturn(new RoutingTable(Map.of(), List.of("seg1", "seg2"), 0));
+    TimeSeriesQueryEnvironment environment =
+        newEnvironment(routingManager, tableCache(), 
TimeSeriesRoutingCustomizer.NO_OP);
+
+    QueryException e = expectThrows(QueryException.class, () -> 
environment.buildPhysicalPlan(request(),
+        requestContext(), new TimeSeriesLogicalPlanResult(leaf("leaf", 
"myTable"), TIME_BUCKETS), tableNames -> { }));
+    assertEquals(e.getErrorCode(), QueryErrorCode.SERVER_SEGMENT_MISSING);
+  }
+
+  @DataProvider
+  public Object[][] optionalSegments() {
+    return new Object[][]{{List.of()}, {List.of("optional")}};
+  }
+
+  @Test(dataProvider = "optionalSegments")
+  public void 
testServerEntriesWithoutRequiredSegmentsDoNotHideUnavailableSegments(List<String>
 optionalSegments) {
+    ServerInstance server = mockServer("Server_1");
+    RoutingManager routingManager = routingManagerWith(Map.of(server, 
List.of("seg1")));
+    // The customizer keeps the server but clears its required segments, and 
seg2 has no server.
+    TimeSeriesQueryEnvironment environment = newEnvironment(routingManager, 
tableCache(),
+        (leaf, routingTable, context) -> new RoutingTable(
+            Map.of(server, new SegmentsToQuery(List.of(), optionalSegments)), 
List.of("seg2"), 1));
+
+    QueryException e = expectThrows(QueryException.class, () -> 
environment.buildPhysicalPlan(request(),
+        requestContext(), new TimeSeriesLogicalPlanResult(leaf("leaf", 
"myTable"), TIME_BUCKETS), tableNames -> { }));
+    assertEquals(e.getErrorCode(), QueryErrorCode.SERVER_SEGMENT_MISSING);
+  }
+
+  /// The ids of the serialized fragments' root nodes; reads the JSON, since a 
[TestPlanNode] does not deserialize.
+  private static List<String> fragmentIds(List<String> serializedFragments) {
+    return serializedFragments.stream().map(fragment -> {
+      try {
+        return JsonUtils.stringToJsonNode(fragment).get("id").asText();
+      } catch (IOException e) {
+        throw new UncheckedIOException(e);
+      }
+    }).toList();
+  }
+
+  private static RoutingManager routingManagerWith(Map<ServerInstance, 
List<String>> segmentsByServer) {
+    RoutingManager routingManager = mock(RoutingManager.class);
+    when(routingManager.routingExists(TABLE)).thenReturn(true);
+    Map<ServerInstance, SegmentsToQuery> routed = new HashMap<>();
+    segmentsByServer.forEach((server, segments) -> routed.put(server, new 
SegmentsToQuery(segments, List.of())));
+    
when(routingManager.getRoutingTableWithMissingServerSegments(any(BrokerRequest.class),
 anyLong()))
+        .thenReturn(new RoutingTable(routed, List.of(), 0));
+    return routingManager;
+  }
+
+  private static ServerInstance mockServer(String instanceId) {
+    ServerInstance server = mock(ServerInstance.class);
+    when(server.getInstanceId()).thenReturn(instanceId);
+    return server;
+  }
+
+  private static TableCache tableCache() {
+    TableCache tableCache = mock(TableCache.class);
+    when(tableCache.getTableConfig(TABLE))
+        .thenReturn(new 
TableConfigBuilder(TableType.OFFLINE).setTableName("myTable").build());
+    return tableCache;
+  }
+
+  private static RangeTimeSeriesRequest request() {
+    return new RangeTimeSeriesRequest(LANGUAGE, "q", 1000L, 1060L, 10L, 
Duration.ofSeconds(10), 100, 100, "q",
+        Map.of());
+  }
+
+  private static RequestContext requestContext() {
+    RequestContext requestContext = mock(RequestContext.class);
+    when(requestContext.getRequestId()).thenReturn(1L);
+    return requestContext;
+  }
+
+  private static TimeSeriesQueryEnvironment newEnvironment(RoutingManager 
routingManager, TableCache tableCache,
+      TimeSeriesRoutingCustomizer customizer) {
+    PinotConfiguration config = new PinotConfiguration(Map.of(
+        PinotTimeSeriesConfiguration.getEnabledLanguagesConfigKey(), LANGUAGE,
+        PinotTimeSeriesConfiguration.getLogicalPlannerConfigKey(LANGUAGE), 
NoOpPlanner.class.getName()));
+    TimeSeriesQueryEnvironment environment =
+        new TimeSeriesQueryEnvironment(config, routingManager, tableCache, 
customizer);
+    environment.init(config);
+    return environment;
+  }
+
+  private static LeafTimeSeriesPlanNode leaf(String tableName) {
+    return leaf("leaf", tableName);
+  }
+
+  private static LeafTimeSeriesPlanNode leaf(String id, String tableName) {
+    return new LeafTimeSeriesPlanNode(id, List.of(), tableName, "ts", 
TimeUnit.SECONDS, 0L, "", "value",
+        new AggInfo("SUM", false, Map.of()), List.of(), 100, 
Map.of("numGroupsLimit", "100"));
+  }
+
+  /// The planner the environment requires for a configured language; this 
test builds its logical plan directly.
+  public static class NoOpPlanner implements TimeSeriesLogicalPlanner {
+    @Override
+    public void init(PinotConfiguration pinotConfiguration) {
+    }
+
+    @Override
+    public TimeSeriesLogicalPlanResult plan(RangeTimeSeriesRequest request, 
TimeSeriesMetadata metadata) {
+      throw new UnsupportedOperationException();
+    }
+  }
+
+  private static class TestPlanNode extends BaseTimeSeriesPlanNode {
+    TestPlanNode(String id, List<BaseTimeSeriesPlanNode> inputs) {
+      super(id, inputs);
+    }
+
+    @Override
+    public BaseTimeSeriesPlanNode withInputs(List<BaseTimeSeriesPlanNode> 
newInputs) {
+      return new TestPlanNode(_id, newInputs);
+    }
+
+    @Override
+    public String getKlass() {
+      return "";
+    }
+
+    @Override
+    public String getExplainName() {
+      return "";
+    }
+
+    @Override
+    public BaseTimeSeriesOperator run() {
+      return null;
+    }
+  }
+}
diff --git 
a/pinot-timeseries/pinot-timeseries-planner/src/test/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitorTest.java
 
b/pinot-timeseries/pinot-timeseries-planner/src/test/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitorTest.java
new file mode 100644
index 00000000000..a4f1bd2e9c9
--- /dev/null
+++ 
b/pinot-timeseries/pinot-timeseries-planner/src/test/java/org/apache/pinot/tsdb/planner/physical/TableScanVisitorTest.java
@@ -0,0 +1,279 @@
+/**
+ * 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.pinot.tsdb.planner.physical;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.common.config.provider.TableCache;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.core.routing.RoutingManager;
+import org.apache.pinot.core.routing.RoutingTable;
+import org.apache.pinot.core.routing.SegmentsToQuery;
+import org.apache.pinot.core.routing.TableRouteProvider;
+import org.apache.pinot.core.transport.ServerInstance;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.exception.QueryException;
+import org.apache.pinot.tsdb.spi.TimeBuckets;
+import org.apache.pinot.tsdb.spi.operator.BaseTimeSeriesOperator;
+import org.apache.pinot.tsdb.spi.plan.BaseTimeSeriesPlanNode;
+import org.apache.pinot.tsdb.spi.plan.LeafTimeSeriesPlanNode;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// Uses the [TableScanVisitor] singleton, so the methods must not run in 
parallel.
+@Test(singleThreaded = true)
+public class TableScanVisitorTest {
+  private static final String TABLE = "myTable_OFFLINE";
+  private static final TimeBuckets TIME_BUCKETS = TimeBuckets.ofSeconds(1000L, 
Duration.ofSeconds(10), 6);
+
+  private RoutingManager _routingManager;
+  private TableCache _tableCache;
+  private ServerInstance _serverOne;
+  private ServerInstance _serverTwo;
+
+  @BeforeMethod
+  public void setUp() {
+    _routingManager = mock(RoutingManager.class);
+    _tableCache = mock(TableCache.class);
+    
when(_tableCache.getTableConfig(TABLE)).thenReturn(mock(TableConfig.class));
+    _serverOne = mock(ServerInstance.class);
+    _serverTwo = mock(ServerInstance.class);
+    when(_serverOne.getInstanceId()).thenReturn("Server_1");
+    when(_serverTwo.getInstanceId()).thenReturn("Server_2");
+    Map<ServerInstance, SegmentsToQuery> routed = new HashMap<>();
+    routed.put(_serverOne, new SegmentsToQuery(new ArrayList<>(List.of("seg1", 
"seg2")), List.of()));
+    routed.put(_serverTwo, new SegmentsToQuery(List.of("seg3"), List.of()));
+    
when(_routingManager.getRoutingTableWithMissingServerSegments(any(BrokerRequest.class),
 anyLong()))
+        .thenReturn(new RoutingTable(routed, List.of(), 0));
+  }
+
+  @AfterMethod
+  public void tearDown() {
+    // The visitor is a singleton; leave it initialized for other tests.
+    TableScanVisitor.INSTANCE.init(_routingManager, 
mock(TableRouteProvider.class), _tableCache);
+  }
+
+  @Test
+  public void testWithoutCustomizerRoutesAsChosenAndKeepsPlan() {
+    TableScanVisitor.INSTANCE.init(_routingManager, 
mock(TableRouteProvider.class), _tableCache);
+    LeafTimeSeriesPlanNode leaf = leaf("leaf", Map.of("k", "v"));
+    TableScanVisitor.Context context =
+        TableScanVisitor.createContext(1L, Map.of("requestOption", "x"), 
TimeSeriesRoutingCustomizer.NO_OP);
+
+    TableScanVisitor.INSTANCE.assignSegmentsToPlan(leaf, TIME_BUCKETS, 
context);
+
+    assertEquals(context.getLeafIdToSegmentsByInstanceId(),
+        Map.of("Server_1", Map.of("leaf", List.of("seg1", "seg2")), 
"Server_2", Map.of("leaf", List.of("seg3"))));
+    assertTrue(context.getRoutingQueryOptions().isEmpty());
+    assertSame(TableScanVisitor.INSTANCE.addQueryOptionsToPlan(leaf, 
context.getRoutingQueryOptions()), leaf);
+  }
+
+  @Test
+  public void testCustomizerNarrowsSegmentsAndSendsOptionsToEveryLeaf() {
+    List<String> calls = new ArrayList<>();
+    TimeSeriesRoutingCustomizer customizer = (leaf, routingTable, context) -> {
+      // The customizer sees the leaf, the request's options and what earlier 
leaves added.
+      calls.add(leaf.getId() + ":" + leaf.getTableName() + ":" + 
context.getRoutingQueryOptions().get("pinnedVersion"));
+      if (!context.getRoutingQueryOptions().containsKey("pinnedVersion")) {
+        context.putRoutingQueryOption("pinnedVersion",
+            context.getRequestQueryOptions().getOrDefault("pinnedVersion", 
"42"));
+      }
+      context.putRoutingQueryOption("k", "fromCustomizer");
+      Map<ServerInstance, SegmentsToQuery> narrowed = new HashMap<>();
+      routingTable.getServerInstanceToSegmentsMap().forEach((server, segments) 
-> narrowed.put(server,
+          new SegmentsToQuery(segments.getSegments().stream().filter(s -> 
!s.equals("seg2")).toList(), List.of())));
+      return new RoutingTable(narrowed, List.of(), 1);
+    };
+    TableScanVisitor.INSTANCE.init(_routingManager, 
mock(TableRouteProvider.class), _tableCache);
+    LeafTimeSeriesPlanNode leafOne = leaf("leafOne", Map.of("k", "v", "own", 
"kept"));
+    LeafTimeSeriesPlanNode leafTwo = leaf("leafTwo", null);
+    BaseTimeSeriesPlanNode root = new TestPlanNode("root", List.of(leafOne, 
leafTwo));
+    TableScanVisitor.Context context = TableScanVisitor.createContext(1L, 
Map.of("pinnedVersion", "7"), customizer);
+
+    TableScanVisitor.INSTANCE.assignSegmentsToPlan(root, TIME_BUCKETS, 
context);
+    BaseTimeSeriesPlanNode planWithOptions =
+        TableScanVisitor.INSTANCE.addQueryOptionsToPlan(root, 
context.getRoutingQueryOptions());
+
+    // Both leaves read the narrowed segments; the first leaf honored the 
request's pin and the second saw it.
+    assertEquals(context.getLeafIdToSegmentsByInstanceId(), Map.of(
+        "Server_1", Map.of("leafOne", List.of("seg1"), "leafTwo", 
List.of("seg1")),
+        "Server_2", Map.of("leafOne", List.of("seg3"), "leafTwo", 
List.of("seg3"))));
+    assertEquals(calls, List.of("leafOne:" + TABLE + ":null", "leafTwo:" + 
TABLE + ":7"));
+    // Every leaf sends the routing options, which replace a leaf's own option 
with the same key; the leaf keeps its
+    // other options.
+    List<BaseTimeSeriesPlanNode> leaves = planWithOptions.getInputs();
+    assertEquals(leaves.get(0).getId(), "leafOne");
+    assertEquals(((LeafTimeSeriesPlanNode) leaves.get(0)).getQueryOptions(),
+        Map.of("pinnedVersion", "7", "k", "fromCustomizer", "own", "kept"));
+    assertEquals(leaves.get(1).getId(), "leafTwo");
+    assertEquals(((LeafTimeSeriesPlanNode) leaves.get(1)).getQueryOptions(),
+        Map.of("pinnedVersion", "7", "k", "fromCustomizer"));
+  }
+
+  @Test
+  public void testCustomizerCannotReachPlannerState() {
+    TableScanVisitor.Context context =
+        TableScanVisitor.createContext(1L, Map.of("k", "v"), 
TimeSeriesRoutingCustomizer.NO_OP);
+    TimeSeriesRoutingContext view = context.getRoutingContext();
+
+    view.putRoutingQueryOption("added", "x");
+
+    assertEquals(context.getRoutingQueryOptions(), Map.of("added", "x"));
+    assertThrows(UnsupportedOperationException.class, () -> 
view.getRoutingQueryOptions().clear());
+    assertTrue(!(view instanceof TableScanVisitor.Context), "the view must not 
expose the planner's context");
+  }
+
+  @Test
+  public void testServersRequireARequiredSegment() {
+    ServerInstance serverThree = mock(ServerInstance.class);
+    when(serverThree.getInstanceId()).thenReturn("Server_3");
+    Map<ServerInstance, SegmentsToQuery> routed = new HashMap<>();
+    routed.put(_serverOne, new SegmentsToQuery(List.of("seg1"), 
List.of("optional1")));
+    // Newly pushed segments, not yet ONLINE in the external view: only 
optional.
+    routed.put(_serverTwo, new SegmentsToQuery(List.of(), List.of("seg2")));
+    routed.put(serverThree, new SegmentsToQuery(List.of(), List.of()));
+    
when(_routingManager.getRoutingTableWithMissingServerSegments(any(BrokerRequest.class),
 anyLong()))
+        .thenReturn(new RoutingTable(routed, List.of(), 0));
+    TableScanVisitor.INSTANCE.init(_routingManager, 
mock(TableRouteProvider.class), _tableCache);
+    TableScanVisitor.Context context = TableScanVisitor.createContext(1L, 
Map.of(), TimeSeriesRoutingCustomizer.NO_OP);
+
+    TableScanVisitor.INSTANCE.assignSegmentsToPlan(leaf("leaf", Map.of()), 
TIME_BUCKETS, context);
+
+    // Optional-only and empty entries must not require an RPC.
+    assertEquals(context.getLeafIdToSegmentsByInstanceId(), Map.of("Server_1", 
Map.of("leaf", List.of("seg1"))));
+    assertEquals(context.getLeafIdToOptionalSegmentsByInstanceId(),
+        Map.of("Server_1", Map.of("leaf", List.of("optional1"))));
+    assertEquals(context.getQueryServers().size(), 1);
+  }
+
+  @Test
+  public void testUpsertCustomizerCanAddOptionsButCannotNarrowAssignments() {
+    TableConfig tableConfig = mock(TableConfig.class);
+    when(tableConfig.isUpsertEnabled()).thenReturn(true);
+    when(_tableCache.getTableConfig(TABLE)).thenReturn(tableConfig);
+    TableScanVisitor.INSTANCE.init(_routingManager, 
mock(TableRouteProvider.class), _tableCache);
+    LeafTimeSeriesPlanNode leaf = leaf("leaf", Map.of());
+    TableScanVisitor.Context optionsOnly = TableScanVisitor.createContext(1L, 
Map.of(),
+        (leafNode, routingTable, routingContext) -> {
+          routingContext.putRoutingQueryOption("pinnedVersion", "7");
+          return routingTable;
+        });
+    TableScanVisitor.INSTANCE.assignSegmentsToPlan(leaf, TIME_BUCKETS, 
optionsOnly);
+    assertEquals(optionsOnly.getRoutingQueryOptions(), Map.of("pinnedVersion", 
"7"));
+
+    TableScanVisitor.Context narrowed = TableScanVisitor.createContext(1L, 
Map.of(),
+        (leafNode, routingTable, routingContext) -> {
+          
routingTable.getServerInstanceToSegmentsMap().get(_serverOne).getSegments().remove("seg2");
+          return routingTable;
+        });
+    QueryException failure = expectThrows(QueryException.class,
+        () -> TableScanVisitor.INSTANCE.assignSegmentsToPlan(leaf, 
TIME_BUCKETS, narrowed));
+    assertEquals(failure.getErrorCode(), QueryErrorCode.QUERY_VALIDATION);
+  }
+
+  @Test
+  public void testLaterCustomizerCannotChangeEarlierUpsertLeafAssignments() {
+    TableConfig tableConfig = mock(TableConfig.class);
+    when(tableConfig.isUpsertEnabled()).thenReturn(true);
+    when(_tableCache.getTableConfig(TABLE)).thenReturn(tableConfig);
+    List<String> earlierRequired = new ArrayList<>(List.of("seg1"));
+    List<String> earlierOptional = new ArrayList<>(List.of("optional1"));
+    
when(_routingManager.getRoutingTableWithMissingServerSegments(any(BrokerRequest.class),
 anyLong())).thenReturn(
+        new RoutingTable(Map.of(_serverOne, new 
SegmentsToQuery(earlierRequired, earlierOptional)), List.of(), 0),
+        new RoutingTable(Map.of(_serverOne, new 
SegmentsToQuery(List.of("seg2"), List.of())), List.of(), 0));
+    TableScanVisitor.INSTANCE.init(_routingManager, 
mock(TableRouteProvider.class), _tableCache);
+    TableScanVisitor.Context context = TableScanVisitor.createContext(1L, 
Map.of(),
+        (leafNode, routingTable, routingContext) -> {
+          if (leafNode.getId().equals("later")) {
+            earlierRequired.clear();
+            earlierOptional.clear();
+          }
+          return routingTable;
+        });
+
+    BaseTimeSeriesPlanNode root = new TestPlanNode("root", 
List.of(leaf("earlier", Map.of()), leaf("later", Map.of())));
+    TableScanVisitor.INSTANCE.assignSegmentsToPlan(root, TIME_BUCKETS, 
context);
+
+    assertEquals(context.getLeafIdToSegmentsByInstanceId(),
+        Map.of("Server_1", Map.of("earlier", List.of("seg1"), "later", 
List.of("seg2"))));
+    assertEquals(context.getLeafIdToOptionalSegmentsByInstanceId(),
+        Map.of("Server_1", Map.of("earlier", List.of("optional1"))));
+  }
+
+  @Test
+  public void testRequestQueryOptionsAreReadOnly() {
+    Map<String, String> requestQueryOptions = new HashMap<>(Map.of("k", "v"));
+    TableScanVisitor.Context context =
+        TableScanVisitor.createContext(1L, requestQueryOptions, 
TimeSeriesRoutingCustomizer.NO_OP);
+    requestQueryOptions.put("k", "changedAfterwards");
+
+    assertEquals(context.getRequestQueryOptions(), Map.of("k", "v"));
+    assertThrows(UnsupportedOperationException.class, () -> 
context.getRequestQueryOptions().put("k", "x"));
+    assertEquals(TableScanVisitor.createContext(1L, null, 
TimeSeriesRoutingCustomizer.NO_OP).getRequestQueryOptions(),
+        Map.of());
+  }
+
+  private static LeafTimeSeriesPlanNode leaf(String id, Map<String, String> 
queryOptions) {
+    return new LeafTimeSeriesPlanNode(id, List.of(), TABLE, "ts", 
TimeUnit.SECONDS, 0L, "", "value", null, List.of(),
+        100, queryOptions);
+  }
+
+  private static class TestPlanNode extends BaseTimeSeriesPlanNode {
+    TestPlanNode(String id, List<BaseTimeSeriesPlanNode> inputs) {
+      super(id, inputs);
+    }
+
+    @Override
+    public BaseTimeSeriesPlanNode withInputs(List<BaseTimeSeriesPlanNode> 
newInputs) {
+      return new TestPlanNode(_id, newInputs);
+    }
+
+    @Override
+    public String getKlass() {
+      return "";
+    }
+
+    @Override
+    public String getExplainName() {
+      return "";
+    }
+
+    @Override
+    public BaseTimeSeriesOperator run() {
+      return null;
+    }
+  }
+}
diff --git 
a/pinot-timeseries/pinot-timeseries-spi/src/main/java/org/apache/pinot/tsdb/spi/plan/LeafTimeSeriesPlanNode.java
 
b/pinot-timeseries/pinot-timeseries-spi/src/main/java/org/apache/pinot/tsdb/spi/plan/LeafTimeSeriesPlanNode.java
index 5f85ce29c5a..2d7d69ba26d 100644
--- 
a/pinot-timeseries/pinot-timeseries-spi/src/main/java/org/apache/pinot/tsdb/spi/plan/LeafTimeSeriesPlanNode.java
+++ 
b/pinot-timeseries/pinot-timeseries-spi/src/main/java/org/apache/pinot/tsdb/spi/plan/LeafTimeSeriesPlanNode.java
@@ -78,6 +78,11 @@ public class LeafTimeSeriesPlanNode extends 
BaseTimeSeriesPlanNode {
         _filterExpression, _valueExpression, _aggInfo, _groupByExpressions, 
_limit, _queryOptions);
   }
 
+  public LeafTimeSeriesPlanNode withQueryOptions(Map<String, String> 
newQueryOptions) {
+    return new LeafTimeSeriesPlanNode(_id, _inputs, _tableName, _timeColumn, 
_timeUnit, _offsetSeconds,
+        _filterExpression, _valueExpression, _aggInfo, _groupByExpressions, 
_limit, newQueryOptions);
+  }
+
   @Override
   public BaseTimeSeriesPlanNode withInputs(List<BaseTimeSeriesPlanNode> 
newInputs) {
     return new LeafTimeSeriesPlanNode(_id, newInputs, _tableName, _timeColumn, 
_timeUnit, _offsetSeconds,


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

Reply via email to