← Back to Pull requests

feat(sql): add experimental native query support for system tables #20183

Open
FrankChen021 opened this pull request with 8952 lines diff across 113 files
View on GitHub
FrankChen021 FrankChen021 commented on Aug 28, 2026 15:28 UTC
Author

Description

This PR introduces experimental, opt-in native-query execution for supported sys. tables and enables it for sys.server_properties. The SQL interpreter (Bindable) path remains the default.

Two switches control the feature:

  • The server property druid.query.enableDruidEngineForSystemTables (default false), set in the common runtime properties of all services. When it's off, services don't serve native queries on system tables and the context parameter below has no effect.

  • The query context parameter useDruidEngineForSystemTables (default false), which opts a SQL query in. It applies only when the resolved SQL engine is native and the table supports native execution.
  • This feature is experimental; its behavior and interfaces may change. Tables without native support, and other SQL engines, are unaffected.

    Motivation

    System tables traditionally use Calcite's Bindable execution path and are not represented as native Druid datasources. Consequently, native operators and aggregations are unavailable for these tables. For example:

    SELECT COUNT(DISTINCT server) FROM sys.server_properties;
    

    This PR represents supported system tables as a systemTable datasource (SystemTableDataSource) that the native engine reads like any other datasource.

    | Scope | This PR |
    | --- | --- |
    | Shared native system-table planning and execution | Yes |
    | sys.server_properties | Yes; rows are gathered from every discovered Druid service |

    <details>
    <summary><strong>Execution path</strong></summary>

    A native query on a systemTable datasource reads only the rows of the service that receives it. Only SQL fans out.

    POST /druid/v2/sql  (useDruidEngineForSystemTables=true)
            |
            v
    Broker SQL planner --> native query on SystemTableDataSource (scope = CLUSTER)
            |
            v
    QueryLifecycle: authorize, attach the caller's row access (SystemTableAccess)
            |
            v
    SystemTableGatheringQuerySegmentWalker
            |-- Broker's own rows: local Scan through the segment wrangler
            |-- other services: POST /druid/v2/ with a Scan on the systemTable datasource
            |                   (escalated identity, table-column filters copied into the Scan)
            v
    rows filtered by the caller's access, then the original query runs on the Broker
    

    On every service, a systemTable datasource is read through SystemTableSegmentWrangler, which turns the table's SystemTableDataProvider into a segment:

  • AND-conjuncts of the query filter on the provider's pushdown columns are passed to the provider, so it can read fewer rows.

  • The caller's row access is applied to the provider's rows.

  • The full filter and virtual columns are then applied by the cursor factory, so pushdown is only an optimization.
  • How each service serves /druid/v2/ for system tables:

  • Broker, Historical, Indexer and Peon: the regular query resource; native queries on a system table run locally.

  • Router, Coordinator, Overlord and Middle Manager: SystemTableQueryResource, which accepts only Scan queries on a systemTable datasource and returns 501 for anything else. The Router answers such Scans with its own rows and forwards queries that read a system table through a subquery or a join to a Broker.
  • </details>

    <details>
    <summary><strong>Implementation details and extension points</strong></summary>

    SQL planning

    A Calcite system table that supports native execution implements SystemTableDataSourceTable#asDataSourceTable(), returning a DruidTable backed by SystemTableDataSource. Both planner strategies are supported:

  • In COUPLED mode, DruidTableScanRule converts the system table directly.

  • In DECOUPLED mode, DruidBindableTableScanRule rebuilds the native project/filter/scan plan when Calcite has already embedded filters or projections in a BindableTableScan.
  • NativeQueryMaker marks the system tables of a SQL query with the cluster scope, which is what makes the Broker gather them. The scope and the row access are never serialized, so a native query sent directly to a service can't request a fan-out or carry access.

    Registering another native system table

    1. Register a SystemTableDescriptor with the table name, the node roles that own its rows, the row signature, and a SystemTableRowAuthorizer.
    2. Register a SystemTableDataProvider on those nodes. It may declare pushdown columns through getPushdownColumns(), whose filters are passed to getRows(List<Filter>).
    3. Make the Calcite table implement SystemTableDataSourceTable.

    No new HTTP resource, RPC client or Broker query branch is needed.

    ServerPropertiesTableDataProvider declares server and service_name as pushdown columns: a service that doesn't match a filter on them returns no rows before enumerating its properties.

    Native query module

    NativeQueryEngineModule is a shared facade that installs the queryable, query-runner, segment-wrangler and query-resource modules. Its builder supports:

  • scanOnly() for services that need only local Scan execution, without merge buffers or the full aggregation stack.

  • withQuerySegmentWalker(...) and withOverrideModule(...) for role-specific bindings, such as the Coordinator's segment schema cache.

  • withQueryResourceModule(...) for the Broker's and Router's query resources.
  • </details>

    <details>
    <summary><strong>Authorization</strong></summary>

  • QueryLifecycle authorizes system tables and attaches the caller's row access through the table's SystemTableRowAuthorizer. A system table is processable only once its access is attached, so no path can read rows without authorization.

  • The Broker's node scans use the escalated identity; the gathered rows are filtered with the original caller's access on the Broker.

  • druid.auth.authorizeSystemTablesDirectly authorizes system tables as SYSTEM_TABLE resources that require READ, in SQL on the Broker and in native queries on every service. It replaces druid.sql.planner.authorizeSystemTablesDirectly, which is deprecated; the Broker honors either.

  • Cancelling a query authorizes against the resources the query reads, which for system tables means SYSTEM_TABLE WRITE.
  • </details>

    <details>
    <summary><strong>Compatibility and current limitations</strong></summary>

    During a rolling upgrade, leave the server property and the context parameter disabled until all services are upgraded. The context parameter can then be enabled per query, or as a cluster-wide default on Brokers:

    druid.query.default.context.useDruidEngineForSystemTables=true
    

    Current limitations:

  • Services other than the Broker, Historical, Indexer and Peon execute only Scan queries on a system table. Aggregations, expressions, sorting, limits and window processing run on the Broker after the rows are gathered.

  • The Broker gathers all rows of a table into memory before running the query; it does not stream them.

  • Gathering is not governed by QueryScheduler lanes or capacity, and a cancel during the fan-out does not interrupt node scans that are already running.

  • Cancelling a system-table query requires SYSTEM_TABLE WRITE, even when druid.auth.authorizeSystemTablesDirectly is off.

  • A user cannot cancel a native system-table query that the Router answers itself, and those queries are not counted in the Router's query count metrics.

  • Rows are gathered from every service of the table's node roles; there is no leader-only routing.

  • Pushdown is provider-dependent; filters the provider doesn't use are still applied by the native engine.

  • Tables without a native representation keep the Bindable execution path.
  • </details>

    Validation

  • Unit tests for the datasource, segment wrangler and cursor factory, Broker gathering, row authorization, query resources, Router dispatch, and SQL planning in COUPLED and DECOUPLED modes.

  • Embedded end-to-end tests for sys.server_properties across all service roles, with the feature disabled, and with basic authentication (SYSTEM_TABLE and STATE permissions).

  • An in-process benchmark on a six-service embedded cluster: at 120,000 rows, native execution is about 2.2–2.5 times faster than the SQL interpreter for full-table queries (for example, COUNT() takes 48 ms instead of 122 ms at the median), and at about 100 rows the two are comparable.
  • Release note

    SQL queries against supported system tables can opt into experimental execution on Druid's native query engine. Enable druid.query.enableDruidEngineForSystemTables on all services, then set the useDruidEngineForSystemTables query context parameter. The initial implementation supports sys.server_properties. Native queries on a systemTable datasource sent to a service's /druid/v2/ endpoint read that service's rows. druid.auth.authorizeSystemTablesDirectly replaces the deprecated druid.sql.planner.authorizeSystemTablesDirectly.

    This PR has:

  • been self-reviewed.

  • added documentation for the query context and native system-table behavior.

  • included a release note in the PR description.

  • added Javadocs for the principal new classes and interfaces.

  • added unit and embedded end-to-end tests.

  • been tested in a local Druid cluster.
  • Diff: 8952 lines (+8668 / -284) across 113 files Reviewer: FrankChen021 Review duration: 130507m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.93) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.93 · 8952 lines diff across 113 files
    0.93
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    64 items
    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Aug 28, 2026 15:28 UTC
    Reviewer

    Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

    FrankChen021 FrankChen021 commented on Aug 29, 2026 02:09 UTC
    Author

    @clintropolis @gianm please help review the changes. I hope this can be merged as soon as possible so that we can move on migrating other system tables into native execution path, and push forward for #18087 and #19855

    FrankChen021 FrankChen021 commented on Aug 29, 2026 13:17 UTC
    Reviewer

    Review complete: no high-confidence correctness, security, or reliability issues found in the current changes.

    Reviewed 100 of 100 changed files.

    Validation: focused git diff --no-ext-diff --check passed. Builds and tests were not run.

    The dedicated reviewer timed out; this review was completed by the main agent from the prepared worktree.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    abhishekrb19 abhishekrb19 commented on code on Sep 08, 2026 20:28 UTC
    Code Review
    services/src/main/java/org/apache/druid/cli/CliHistorical.java:1
    @@ -92,30 +86,22 @@ protected List<? extends Module> getModules()
       {
         return ImmutableList.of(
             new DruidProcessingModule(),
    -        new QueryableModule(),
    -        new QueryRunnerFactoryModule(),
    -        new SegmentWranglerModule(),
    -        new JoinableFactoryModule(),

    Are these not needed? Wondering if this is general cleanup, outside the scope of this PR

    abhishekrb19 abhishekrb19 commented on code on Sep 08, 2026 20:37 UTC
    Code Review
    embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/NativeSysTasksQueryTest.java:1
    @@ -0,0 +1,344 @@
    +/*
    + * 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.druid.testing.embedded.query;
    +
    +import org.apache.druid.indexing.common.task.NoopTask;
    +import org.apache.druid.java.util.common.StringUtils;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.sql.calcite.planner.PlannerContext;
    +import org.apache.druid.sql.calcite.run.NativeSqlEngine;
    +import org.apache.druid.testing.embedded.EmbeddedBroker;
    +import org.apache.druid.testing.embedded.EmbeddedCoordinator;
    +import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
    +import org.apache.druid.testing.embedded.EmbeddedIndexer;
    +import org.apache.druid.testing.embedded.EmbeddedOverlord;
    +import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
    +import org.junit.jupiter.api.Assertions;
    +import org.junit.jupiter.api.BeforeAll;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import java.util.Arrays;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +public class NativeSysTasksQueryTest extends EmbeddedClusterTestBase
    +{
    +  private static final String TASK_PREFIX = "native_sys_mvp_";
    +
    +  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
    +  private final EmbeddedBroker broker = new EmbeddedBroker();
    +
    +  @Override
    +  protected EmbeddedDruidCluster createCluster()
    +  {
    +    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
    +                               .useLatchableEmitter()
    +                               .addServer(new EmbeddedCoordinator())
    +                               .addServer(new EmbeddedIndexer()
    +                                              .addProperty("druid.worker.capacity", "5"))
    +                               .addServer(overlord)
    +                               .addServer(broker);
    +  }
    +
    +  @BeforeAll
    +  public void createTasks()
    +  {
    +    createTasks("a", "native_sys_a", 2);
    +    createTasks("b", "native_sys_b", 3);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testGroupByUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT datasource, COUNT(*) "
    +        + "FROM sys.tasks "
    +        + "WHERE task_id = 'native_sys_mvp_a_0' AND datasource = 'native_sys_a' "
    +        + "GROUP BY datasource",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    final Set<String> rows = Arrays.stream(result.split("\\n")).collect(Collectors.toSet());
    +    Assertions.assertEquals(Set.of("native_sys_a,1"), rows);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNativeAggregationsSupportDistinctCount(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*), COUNT(DISTINCT task_id), COUNT(DISTINCT datasource), SUM(1) "
    +        + "FROM sys.tasks "
    +        + "WHERE datasource IN ('native_sys_a', 'native_sys_b')",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5,5,2,5", result);
    +  }
    +
    +  /**
    +   * Verifies execution when native planning represents the inner aggregation as a query datasource.
    +   *
    +   * <pre>{@code
    +   * SELECT COUNT(*)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     task_id,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY task_id
    +   * )
    +   * WHERE task_count > 0
    +   * }</pre>
    +   */

    These javadocs here seem like a repeat of the SQL in the test and the test name. Can be removed.

    abhishekrb19 abhishekrb19 commented on code on Sep 08, 2026 20:37 UTC
    Code Review
    embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/NativeSysTasksQueryTest.java:1
    @@ -0,0 +1,344 @@
    +/*
    + * 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.druid.testing.embedded.query;
    +
    +import org.apache.druid.indexing.common.task.NoopTask;
    +import org.apache.druid.java.util.common.StringUtils;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.sql.calcite.planner.PlannerContext;
    +import org.apache.druid.sql.calcite.run.NativeSqlEngine;
    +import org.apache.druid.testing.embedded.EmbeddedBroker;
    +import org.apache.druid.testing.embedded.EmbeddedCoordinator;
    +import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
    +import org.apache.druid.testing.embedded.EmbeddedIndexer;
    +import org.apache.druid.testing.embedded.EmbeddedOverlord;
    +import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
    +import org.junit.jupiter.api.Assertions;
    +import org.junit.jupiter.api.BeforeAll;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import java.util.Arrays;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +public class NativeSysTasksQueryTest extends EmbeddedClusterTestBase
    +{
    +  private static final String TASK_PREFIX = "native_sys_mvp_";
    +
    +  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
    +  private final EmbeddedBroker broker = new EmbeddedBroker();
    +
    +  @Override
    +  protected EmbeddedDruidCluster createCluster()
    +  {
    +    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
    +                               .useLatchableEmitter()
    +                               .addServer(new EmbeddedCoordinator())
    +                               .addServer(new EmbeddedIndexer()
    +                                              .addProperty("druid.worker.capacity", "5"))
    +                               .addServer(overlord)
    +                               .addServer(broker);
    +  }
    +
    +  @BeforeAll
    +  public void createTasks()
    +  {
    +    createTasks("a", "native_sys_a", 2);
    +    createTasks("b", "native_sys_b", 3);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testGroupByUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT datasource, COUNT(*) "
    +        + "FROM sys.tasks "
    +        + "WHERE task_id = 'native_sys_mvp_a_0' AND datasource = 'native_sys_a' "
    +        + "GROUP BY datasource",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    final Set<String> rows = Arrays.stream(result.split("\\n")).collect(Collectors.toSet());
    +    Assertions.assertEquals(Set.of("native_sys_a,1"), rows);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNativeAggregationsSupportDistinctCount(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*), COUNT(DISTINCT task_id), COUNT(DISTINCT datasource), SUM(1) "
    +        + "FROM sys.tasks "
    +        + "WHERE datasource IN ('native_sys_a', 'native_sys_b')",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5,5,2,5", result);
    +  }
    +
    +  /**
    +   * Verifies execution when native planning represents the inner aggregation as a query datasource.
    +   *
    +   * <pre>{@code
    +   * SELECT COUNT(*)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     task_id,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY task_id
    +   * )
    +   * WHERE task_count > 0
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNestedTaskAggregation(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*) "
    +        + "FROM ("
    +        + "  SELECT task_id, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY task_id"
    +        + ") "
    +        + "WHERE task_count > 0",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  /**
    +   * Verifies that an outer aggregation can consume grouped rows from a native system-table subquery.
    +   *
    +   * <pre>{@code
    +   * SELECT SUM(task_count)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     datasource,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY datasource
    +   * )
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testOuterAggregationOverTaskSubquery(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT SUM(task_count) "
    +        + "FROM ("
    +        + "  SELECT datasource, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY datasource"
    +        + ")",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testInAndOrFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id IN ('native_sys_mvp_a_0', 'native_sys_mvp_b_2') "
    +        + "OR task_id = 'native_sys_mvp_missing'",
    +        Set.of("native_sys_mvp_a_0", "native_sys_mvp_b_2"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testRangeAndLikeFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id >= 'native_sys_mvp_b_0' "
    +        + "AND task_id < 'native_sys_mvp_b_2' "
    +        + "AND task_id LIKE 'native_sys_mvp_b_%'",
    +        Set.of("native_sys_mvp_b_0", "native_sys_mvp_b_1"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  /**
    +   * Verifies that expression virtual columns required by a pushed node filter are preserved.
    +   *
    +   * <pre>{@code
    +   * SELECT task_id
    +   * FROM sys.tasks
    +   * WHERE UPPER(task_id) = 'NATIVE_SYS_MVP_A_0'
    +   * }</pre>
    +   */

    Same - the javadocs seem redundant here and a few other tests below

    abhishekrb19 abhishekrb19 commented on code on Sep 08, 2026 20:42 UTC
    Code Review
    embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/NativeSysTasksQueryTest.java:1
    @@ -0,0 +1,344 @@
    +/*
    + * 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.druid.testing.embedded.query;
    +
    +import org.apache.druid.indexing.common.task.NoopTask;
    +import org.apache.druid.java.util.common.StringUtils;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.sql.calcite.planner.PlannerContext;
    +import org.apache.druid.sql.calcite.run.NativeSqlEngine;
    +import org.apache.druid.testing.embedded.EmbeddedBroker;
    +import org.apache.druid.testing.embedded.EmbeddedCoordinator;
    +import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
    +import org.apache.druid.testing.embedded.EmbeddedIndexer;
    +import org.apache.druid.testing.embedded.EmbeddedOverlord;
    +import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
    +import org.junit.jupiter.api.Assertions;
    +import org.junit.jupiter.api.BeforeAll;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import java.util.Arrays;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +public class NativeSysTasksQueryTest extends EmbeddedClusterTestBase
    +{
    +  private static final String TASK_PREFIX = "native_sys_mvp_";
    +
    +  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
    +  private final EmbeddedBroker broker = new EmbeddedBroker();
    +
    +  @Override
    +  protected EmbeddedDruidCluster createCluster()
    +  {
    +    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
    +                               .useLatchableEmitter()
    +                               .addServer(new EmbeddedCoordinator())
    +                               .addServer(new EmbeddedIndexer()
    +                                              .addProperty("druid.worker.capacity", "5"))
    +                               .addServer(overlord)
    +                               .addServer(broker);
    +  }
    +
    +  @BeforeAll
    +  public void createTasks()
    +  {
    +    createTasks("a", "native_sys_a", 2);
    +    createTasks("b", "native_sys_b", 3);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testGroupByUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT datasource, COUNT(*) "
    +        + "FROM sys.tasks "
    +        + "WHERE task_id = 'native_sys_mvp_a_0' AND datasource = 'native_sys_a' "
    +        + "GROUP BY datasource",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    final Set<String> rows = Arrays.stream(result.split("\\n")).collect(Collectors.toSet());
    +    Assertions.assertEquals(Set.of("native_sys_a,1"), rows);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNativeAggregationsSupportDistinctCount(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*), COUNT(DISTINCT task_id), COUNT(DISTINCT datasource), SUM(1) "
    +        + "FROM sys.tasks "
    +        + "WHERE datasource IN ('native_sys_a', 'native_sys_b')",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5,5,2,5", result);
    +  }
    +
    +  /**
    +   * Verifies execution when native planning represents the inner aggregation as a query datasource.
    +   *
    +   * <pre>{@code
    +   * SELECT COUNT(*)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     task_id,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY task_id
    +   * )
    +   * WHERE task_count > 0
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNestedTaskAggregation(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*) "
    +        + "FROM ("
    +        + "  SELECT task_id, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY task_id"
    +        + ") "
    +        + "WHERE task_count > 0",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  /**
    +   * Verifies that an outer aggregation can consume grouped rows from a native system-table subquery.
    +   *
    +   * <pre>{@code
    +   * SELECT SUM(task_count)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     datasource,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY datasource
    +   * )
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testOuterAggregationOverTaskSubquery(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT SUM(task_count) "
    +        + "FROM ("
    +        + "  SELECT datasource, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY datasource"
    +        + ")",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testInAndOrFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id IN ('native_sys_mvp_a_0', 'native_sys_mvp_b_2') "
    +        + "OR task_id = 'native_sys_mvp_missing'",
    +        Set.of("native_sys_mvp_a_0", "native_sys_mvp_b_2"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testRangeAndLikeFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id >= 'native_sys_mvp_b_0' "
    +        + "AND task_id < 'native_sys_mvp_b_2' "
    +        + "AND task_id LIKE 'native_sys_mvp_b_%'",
    +        Set.of("native_sys_mvp_b_0", "native_sys_mvp_b_1"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  /**
    +   * Verifies that expression virtual columns required by a pushed node filter are preserved.
    +   *
    +   * <pre>{@code
    +   * SELECT task_id
    +   * FROM sys.tasks
    +   * WHERE UPPER(task_id) = 'NATIVE_SYS_MVP_A_0'
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testExpressionFilterPreservesVirtualColumn(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "UPPER(task_id) = 'NATIVE_SYS_MVP_A_0'",
    +        Set.of("native_sys_mvp_a_0"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNegatedLikeFilter(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "datasource = 'native_sys_b' AND task_id NOT LIKE '%b_2'",
    +        Set.of("native_sys_mvp_b_0", "native_sys_mvp_b_1"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testStatusLikeFilterRemainsForResidualEvaluation(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id LIKE 'native_sys_mvp_%' AND status LIKE '%'",
    +        Set.of(
    +            "native_sys_mvp_a_0",
    +            "native_sys_mvp_a_1",
    +            "native_sys_mvp_b_0",
    +            "native_sys_mvp_b_1",
    +            "native_sys_mvp_b_2"
    +        ),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testWebConsoleTasksQueryUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "WITH tasks AS (SELECT\n"
    +        + "  \"task_id\", \"group_id\", \"type\", \"datasource\", \"created_time\", \"location\", "
    +        + "\"duration\", \"error_msg\",\n"
    +        + "  CASE WHEN \"error_msg\" IN ('Shutdown request from user', "
    +        + "'Canceled: Query canceled by user or by task shutdown.') THEN 'CANCELED' "
    +        + "WHEN \"status\" = 'RUNNING' THEN \"runner_status\" ELSE \"status\" END AS \"status\"\n"

    I think this web-console query would be a good candidate to benchmark

    abhishekrb19 abhishekrb19 commented on code on Sep 08, 2026 20:50 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,58 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
     :::
     
    +### Native query execution
    +
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`useNativeQueryForSystemTables` to `true` in the SQL query context:
    +
    +```json
    +{
    +  "query": "SELECT COUNT(DISTINCT task_id) FROM sys.tasks",
    +  "context": {
    +    "useNativeQueryForSystemTables": true
    +  }
    +}
    +```
    +
    +For clients that support setting query context parameters with SQL statements, you can enable native system-table
    +execution with `SET`:
    +
    +```sql
    +SET useNativeQueryForSystemTables = 'true';
    +SELECT COUNT(DISTINCT datasource) FROM sys.tasks;
    +```
    +
    +Native system-table execution is available when the resolved SQL engine is `native`. You don't need to explicitly set
    +the `engine` context parameter when `native` is already the default engine. The following tables support native query
    +execution:
    +
    +|Table|Source of rows|
    +|-----|--------------|
    +|[`sys.tasks`](#tasks-table)|The Overlord that owns task state. Supported filters are pushed into task storage when the configured task storage implementation supports filter pushdown.|
    +|[`sys.server_properties`](#server_properties-table)|The Druid server processes discovered in the cluster. Filters on `server` and `service_name` can avoid reading properties from nodes that don't match.|
    +
    +After Druid retrieves the system-table rows, the native engine applies the remaining filters, expressions,
    +aggregations, sorting, and result processing. A system table that doesn't advertise native query support continues to
    +use its existing SQL-layer execution path, even when `useNativeQueryForSystemTables` is `true`.
    +
    +Native system-table queries sent to the Router use distributed Broker execution by default. To execute a native
    +system-table Scan against only the contacted node, set the HTTP header
    +`X-Druid-Native-Query-Route: local`. Local execution uses the authenticated request identity and applies the table's
    +authorization rules. The Broker uses the same header for remote node fan-out requests. If the Broker itself is
    +one of the selected nodes, it executes that node Scan in-process without an HTTP request. The header
    +controls routing and doesn't grant additional permissions.

    Hmm, is this header required only for the sys.server_properties table? I wonder if there's a better way to achieve this without passing in additional headers.

    abhishekrb19 abhishekrb19 commented on code on Sep 08, 2026 20:52 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,58 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
     :::
     
    +### Native query execution
    +
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`useNativeQueryForSystemTables` to `true` in the SQL query context:
    +
    +```json
    +{
    +  "query": "SELECT COUNT(DISTINCT task_id) FROM sys.tasks",
    +  "context": {
    +    "useNativeQueryForSystemTables": true
    +  }
    +}
    +```
    +
    +For clients that support setting query context parameters with SQL statements, you can enable native system-table
    +execution with `SET`:
    +
    +```sql
    +SET useNativeQueryForSystemTables = 'true';
    +SELECT COUNT(DISTINCT datasource) FROM sys.tasks;
    +```
    +
    +Native system-table execution is available when the resolved SQL engine is `native`. You don't need to explicitly set
    +the `engine` context parameter when `native` is already the default engine. The following tables support native query
    +execution:
    +
    +|Table|Source of rows|
    +|-----|--------------|
    +|[`sys.tasks`](#tasks-table)|The Overlord that owns task state. Supported filters are pushed into task storage when the configured task storage implementation supports filter pushdown.|
    +|[`sys.server_properties`](#server_properties-table)|The Druid server processes discovered in the cluster. Filters on `server` and `service_name` can avoid reading properties from nodes that don't match.|
    +
    +After Druid retrieves the system-table rows, the native engine applies the remaining filters, expressions,
    +aggregations, sorting, and result processing. A system table that doesn't advertise native query support continues to
    +use its existing SQL-layer execution path, even when `useNativeQueryForSystemTables` is `true`.
    +
    +Native system-table queries sent to the Router use distributed Broker execution by default. To execute a native
    +system-table Scan against only the contacted node, set the HTTP header
    +`X-Druid-Native-Query-Route: local`. Local execution uses the authenticated request identity and applies the table's
    +authorization rules. The Broker uses the same header for remote node fan-out requests. If the Broker itself is
    +one of the selected nodes, it executes that node Scan in-process without an HTTP request. The header
    +controls routing and doesn't grant additional permissions.
    +
    +The parameter defaults to `false`. During a rolling upgrade, leave it disabled until the Broker and all nodes
    +that serve the native system tables have been upgraded. After the upgrade, you can enable it by query or set
    +`druid.query.default.context.useNativeQueryForSystemTables=true` on Brokers as the cluster-wide default. For more
    +information, see [SQL query context](sql-query-context.md).

    I believe this is a continuation of two paragraphs above:
    >A system table that doesn't advertise native query support continues to
    use its existing SQL-layer execution path, even when useNativeQueryForSystemTables is true.

    Consider moving this above the paragraph about the additional header.

    abhishekrb19 abhishekrb19 commented on Sep 08, 2026 20:58 UTC
    Reviewer

    Thanks for these changes @FrankChen021! The sys. tables have historically been slow and less performant, especially sys.segments and sys.tasks.

    I wonder if we can benchmark sys.tasks with thousands of tasks to see how these changes perform at scale with the native support + filter pushdown.

    Also, regarding the scope of these changes, I feel it would be helpful to break this into a few more patches for ease of review. Perhaps something like:

    Separate PRs for sys.tasks and sys.server_properties, isolating the appropriate wirings, filter pushdown mechanisms and tests to make it work for each table.

  • Handle DECOUPLED planner support in a separate change, since COUPLED is the default planner strategy today (and DECOUPLED is currently undocumented).
  • FrankChen021 FrankChen021 commented on code on Sep 09, 2026 03:05 UTC
    Code Review
    services/src/main/java/org/apache/druid/cli/CliHistorical.java:1
    @@ -92,30 +86,22 @@ protected List<? extends Module> getModules()
       {
         return ImmutableList.of(
             new DruidProcessingModule(),
    -        new QueryableModule(),
    -        new QueryRunnerFactoryModule(),
    -        new SegmentWranglerModule(),
    -        new JoinableFactoryModule(),

    Not out of the scope. it's a tiny refactoring of how native query related module are installed. otherwise, for overlord, coordinator, middle manager, we will repeate these code. Now we only need the NativeQueryEngineModule installed, all dependencies are enclosed in this new module.

    FrankChen021 FrankChen021 commented on code on Sep 09, 2026 03:09 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,58 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
     :::
     
    +### Native query execution
    +
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`useNativeQueryForSystemTables` to `true` in the SQL query context:
    +
    +```json
    +{
    +  "query": "SELECT COUNT(DISTINCT task_id) FROM sys.tasks",
    +  "context": {
    +    "useNativeQueryForSystemTables": true
    +  }
    +}
    +```
    +
    +For clients that support setting query context parameters with SQL statements, you can enable native system-table
    +execution with `SET`:
    +
    +```sql
    +SET useNativeQueryForSystemTables = 'true';
    +SELECT COUNT(DISTINCT datasource) FROM sys.tasks;
    +```
    +
    +Native system-table execution is available when the resolved SQL engine is `native`. You don't need to explicitly set
    +the `engine` context parameter when `native` is already the default engine. The following tables support native query
    +execution:
    +
    +|Table|Source of rows|
    +|-----|--------------|
    +|[`sys.tasks`](#tasks-table)|The Overlord that owns task state. Supported filters are pushed into task storage when the configured task storage implementation supports filter pushdown.|
    +|[`sys.server_properties`](#server_properties-table)|The Druid server processes discovered in the cluster. Filters on `server` and `service_name` can avoid reading properties from nodes that don't match.|
    +
    +After Druid retrieves the system-table rows, the native engine applies the remaining filters, expressions,
    +aggregations, sorting, and result processing. A system table that doesn't advertise native query support continues to
    +use its existing SQL-layer execution path, even when `useNativeQueryForSystemTables` is `true`.
    +
    +Native system-table queries sent to the Router use distributed Broker execution by default. To execute a native
    +system-table Scan against only the contacted node, set the HTTP header
    +`X-Druid-Native-Query-Route: local`. Local execution uses the authenticated request identity and applies the table's
    +authorization rules. The Broker uses the same header for remote node fan-out requests. If the Broker itself is
    +one of the selected nodes, it executes that node Scan in-process without an HTTP request. The header
    +controls routing and doesn't grant additional permissions.

    it's needed as the broker will send native query to router or itself to retrieve data. for router, we need to tell whether it acts as a proxy or execute the native query.

    another way is by using query context, but I don't think the query context is better way because this value here is just an internal flag, not user-facing context parameter.

    FrankChen021 FrankChen021 commented on Sep 09, 2026 03:18 UTC
    Author

    Thanks for these changes @FrankChen021! The sys. tables have historically been slow and less performant, especially sys.segments and sys.tasks.

    > I wonder if we can benchmark sys.tasks with thousands of tasks to see how these changes perform at scale with the native support + filter pushdown.

    > Also, regarding the scope of these changes, I feel it would be helpful to break this into a few more patches for ease of review. Perhaps something like:

    > Separate PRs for sys.tasks and sys.server_properties, isolating the appropriate wirings, filter pushdown mechanisms and tests to make it work for each table.

    * Handle DECOUPLED planner support in a separate change, since COUPLED is the default planner strategy today (and DECOUPLED is currently undocumented).

    Thanks for reviewing.

    I deliberately chose the sys.tasks and sys.server_properties included in this PR to demonstrate how the native query for system tables are supported.

    These two system tables have different fan-out paths and push down policies:
    1. for sys.server_properties, we need to fan out sub queries to all nodes, while for sys.tasks we need to fan out the query to leader overlord only. This is also why the header X-Druid-Native-Query-Route is introduced to serve the purpose
    2. for sys.tasks, it also demonstrates how filters are pushed down, which is one of the most important goal we need to achieve

    If we move any of these system table out of this PR, we can't have a full picture of the change, and understand how the small framework for the system tables work.

    As for DECOUPLED mode, only a few files are involved, I think it's better to included in this PR.

    To address your concern, I can split the changes for sys.tasks out of this one. But We still need to have a full picture of the core change.

    FrankChen021 FrankChen021 commented on code on Sep 09, 2026 03:54 UTC
    Code Review
    embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/NativeSysTasksQueryTest.java:1
    @@ -0,0 +1,344 @@
    +/*
    + * 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.druid.testing.embedded.query;
    +
    +import org.apache.druid.indexing.common.task.NoopTask;
    +import org.apache.druid.java.util.common.StringUtils;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.sql.calcite.planner.PlannerContext;
    +import org.apache.druid.sql.calcite.run.NativeSqlEngine;
    +import org.apache.druid.testing.embedded.EmbeddedBroker;
    +import org.apache.druid.testing.embedded.EmbeddedCoordinator;
    +import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
    +import org.apache.druid.testing.embedded.EmbeddedIndexer;
    +import org.apache.druid.testing.embedded.EmbeddedOverlord;
    +import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
    +import org.junit.jupiter.api.Assertions;
    +import org.junit.jupiter.api.BeforeAll;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import java.util.Arrays;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +public class NativeSysTasksQueryTest extends EmbeddedClusterTestBase
    +{
    +  private static final String TASK_PREFIX = "native_sys_mvp_";
    +
    +  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
    +  private final EmbeddedBroker broker = new EmbeddedBroker();
    +
    +  @Override
    +  protected EmbeddedDruidCluster createCluster()
    +  {
    +    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
    +                               .useLatchableEmitter()
    +                               .addServer(new EmbeddedCoordinator())
    +                               .addServer(new EmbeddedIndexer()
    +                                              .addProperty("druid.worker.capacity", "5"))
    +                               .addServer(overlord)
    +                               .addServer(broker);
    +  }
    +
    +  @BeforeAll
    +  public void createTasks()
    +  {
    +    createTasks("a", "native_sys_a", 2);
    +    createTasks("b", "native_sys_b", 3);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testGroupByUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT datasource, COUNT(*) "
    +        + "FROM sys.tasks "
    +        + "WHERE task_id = 'native_sys_mvp_a_0' AND datasource = 'native_sys_a' "
    +        + "GROUP BY datasource",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    final Set<String> rows = Arrays.stream(result.split("\\n")).collect(Collectors.toSet());
    +    Assertions.assertEquals(Set.of("native_sys_a,1"), rows);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNativeAggregationsSupportDistinctCount(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*), COUNT(DISTINCT task_id), COUNT(DISTINCT datasource), SUM(1) "
    +        + "FROM sys.tasks "
    +        + "WHERE datasource IN ('native_sys_a', 'native_sys_b')",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5,5,2,5", result);
    +  }
    +
    +  /**
    +   * Verifies execution when native planning represents the inner aggregation as a query datasource.
    +   *
    +   * <pre>{@code
    +   * SELECT COUNT(*)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     task_id,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY task_id
    +   * )
    +   * WHERE task_count > 0
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNestedTaskAggregation(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*) "
    +        + "FROM ("
    +        + "  SELECT task_id, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY task_id"
    +        + ") "
    +        + "WHERE task_count > 0",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  /**
    +   * Verifies that an outer aggregation can consume grouped rows from a native system-table subquery.
    +   *
    +   * <pre>{@code
    +   * SELECT SUM(task_count)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     datasource,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY datasource
    +   * )
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testOuterAggregationOverTaskSubquery(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT SUM(task_count) "
    +        + "FROM ("
    +        + "  SELECT datasource, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY datasource"
    +        + ")",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testInAndOrFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id IN ('native_sys_mvp_a_0', 'native_sys_mvp_b_2') "
    +        + "OR task_id = 'native_sys_mvp_missing'",
    +        Set.of("native_sys_mvp_a_0", "native_sys_mvp_b_2"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testRangeAndLikeFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id >= 'native_sys_mvp_b_0' "
    +        + "AND task_id < 'native_sys_mvp_b_2' "
    +        + "AND task_id LIKE 'native_sys_mvp_b_%'",
    +        Set.of("native_sys_mvp_b_0", "native_sys_mvp_b_1"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  /**
    +   * Verifies that expression virtual columns required by a pushed node filter are preserved.
    +   *
    +   * <pre>{@code
    +   * SELECT task_id
    +   * FROM sys.tasks
    +   * WHERE UPPER(task_id) = 'NATIVE_SYS_MVP_A_0'
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testExpressionFilterPreservesVirtualColumn(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "UPPER(task_id) = 'NATIVE_SYS_MVP_A_0'",
    +        Set.of("native_sys_mvp_a_0"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNegatedLikeFilter(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "datasource = 'native_sys_b' AND task_id NOT LIKE '%b_2'",
    +        Set.of("native_sys_mvp_b_0", "native_sys_mvp_b_1"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testStatusLikeFilterRemainsForResidualEvaluation(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id LIKE 'native_sys_mvp_%' AND status LIKE '%'",
    +        Set.of(
    +            "native_sys_mvp_a_0",
    +            "native_sys_mvp_a_1",
    +            "native_sys_mvp_b_0",
    +            "native_sys_mvp_b_1",
    +            "native_sys_mvp_b_2"
    +        ),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testWebConsoleTasksQueryUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "WITH tasks AS (SELECT\n"
    +        + "  \"task_id\", \"group_id\", \"type\", \"datasource\", \"created_time\", \"location\", "
    +        + "\"duration\", \"error_msg\",\n"
    +        + "  CASE WHEN \"error_msg\" IN ('Shutdown request from user', "
    +        + "'Canceled: Query canceled by user or by task shutdown.') THEN 'CANCELED' "
    +        + "WHEN \"status\" = 'RUNNING' THEN \"runner_status\" ELSE \"status\" END AS \"status\"\n"

    Added a 100,000-task JMH benchmark in FrankChen021/druid#198. The full-list case uses the Web Console query as the representative workload, and the PR description highlights the measured Bindable-versus-native results.

    FrankChen021 FrankChen021 commented on code on Sep 09, 2026 03:54 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,58 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
     :::
     
    +### Native query execution
    +
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`useNativeQueryForSystemTables` to `true` in the SQL query context:
    +
    +```json
    +{
    +  "query": "SELECT COUNT(DISTINCT task_id) FROM sys.tasks",
    +  "context": {
    +    "useNativeQueryForSystemTables": true
    +  }
    +}
    +```
    +
    +For clients that support setting query context parameters with SQL statements, you can enable native system-table
    +execution with `SET`:
    +
    +```sql
    +SET useNativeQueryForSystemTables = 'true';
    +SELECT COUNT(DISTINCT datasource) FROM sys.tasks;
    +```
    +
    +Native system-table execution is available when the resolved SQL engine is `native`. You don't need to explicitly set
    +the `engine` context parameter when `native` is already the default engine. The following tables support native query
    +execution:
    +
    +|Table|Source of rows|
    +|-----|--------------|
    +|[`sys.tasks`](#tasks-table)|The Overlord that owns task state. Supported filters are pushed into task storage when the configured task storage implementation supports filter pushdown.|
    +|[`sys.server_properties`](#server_properties-table)|The Druid server processes discovered in the cluster. Filters on `server` and `service_name` can avoid reading properties from nodes that don't match.|
    +
    +After Druid retrieves the system-table rows, the native engine applies the remaining filters, expressions,
    +aggregations, sorting, and result processing. A system table that doesn't advertise native query support continues to
    +use its existing SQL-layer execution path, even when `useNativeQueryForSystemTables` is `true`.
    +
    +Native system-table queries sent to the Router use distributed Broker execution by default. To execute a native
    +system-table Scan against only the contacted node, set the HTTP header
    +`X-Druid-Native-Query-Route: local`. Local execution uses the authenticated request identity and applies the table's
    +authorization rules. The Broker uses the same header for remote node fan-out requests. If the Broker itself is
    +one of the selected nodes, it executes that node Scan in-process without an HTTP request. The header
    +controls routing and doesn't grant additional permissions.
    +
    +The parameter defaults to `false`. During a rolling upgrade, leave it disabled until the Broker and all nodes
    +that serve the native system tables have been upgraded. After the upgrade, you can enable it by query or set
    +`druid.query.default.context.useNativeQueryForSystemTables=true` on Brokers as the cluster-wide default. For more
    +information, see [SQL query context](sql-query-context.md).

    Addressed on this PR branch: the default and rolling-upgrade guidance now follows the native-planning/fallback explanation, before the route-header paragraph.

    FrankChen021 FrankChen021 commented on code on Sep 09, 2026 03:54 UTC
    Code Review
    embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/NativeSysTasksQueryTest.java:1
    @@ -0,0 +1,344 @@
    +/*
    + * 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.druid.testing.embedded.query;
    +
    +import org.apache.druid.indexing.common.task.NoopTask;
    +import org.apache.druid.java.util.common.StringUtils;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.sql.calcite.planner.PlannerContext;
    +import org.apache.druid.sql.calcite.run.NativeSqlEngine;
    +import org.apache.druid.testing.embedded.EmbeddedBroker;
    +import org.apache.druid.testing.embedded.EmbeddedCoordinator;
    +import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
    +import org.apache.druid.testing.embedded.EmbeddedIndexer;
    +import org.apache.druid.testing.embedded.EmbeddedOverlord;
    +import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
    +import org.junit.jupiter.api.Assertions;
    +import org.junit.jupiter.api.BeforeAll;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import java.util.Arrays;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +public class NativeSysTasksQueryTest extends EmbeddedClusterTestBase
    +{
    +  private static final String TASK_PREFIX = "native_sys_mvp_";
    +
    +  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
    +  private final EmbeddedBroker broker = new EmbeddedBroker();
    +
    +  @Override
    +  protected EmbeddedDruidCluster createCluster()
    +  {
    +    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
    +                               .useLatchableEmitter()
    +                               .addServer(new EmbeddedCoordinator())
    +                               .addServer(new EmbeddedIndexer()
    +                                              .addProperty("druid.worker.capacity", "5"))
    +                               .addServer(overlord)
    +                               .addServer(broker);
    +  }
    +
    +  @BeforeAll
    +  public void createTasks()
    +  {
    +    createTasks("a", "native_sys_a", 2);
    +    createTasks("b", "native_sys_b", 3);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testGroupByUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT datasource, COUNT(*) "
    +        + "FROM sys.tasks "
    +        + "WHERE task_id = 'native_sys_mvp_a_0' AND datasource = 'native_sys_a' "
    +        + "GROUP BY datasource",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    final Set<String> rows = Arrays.stream(result.split("\\n")).collect(Collectors.toSet());
    +    Assertions.assertEquals(Set.of("native_sys_a,1"), rows);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNativeAggregationsSupportDistinctCount(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*), COUNT(DISTINCT task_id), COUNT(DISTINCT datasource), SUM(1) "
    +        + "FROM sys.tasks "
    +        + "WHERE datasource IN ('native_sys_a', 'native_sys_b')",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5,5,2,5", result);
    +  }
    +
    +  /**
    +   * Verifies execution when native planning represents the inner aggregation as a query datasource.
    +   *
    +   * <pre>{@code
    +   * SELECT COUNT(*)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     task_id,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY task_id
    +   * )
    +   * WHERE task_count > 0
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNestedTaskAggregation(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*) "
    +        + "FROM ("
    +        + "  SELECT task_id, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY task_id"
    +        + ") "
    +        + "WHERE task_count > 0",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  /**
    +   * Verifies that an outer aggregation can consume grouped rows from a native system-table subquery.
    +   *
    +   * <pre>{@code
    +   * SELECT SUM(task_count)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     datasource,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY datasource
    +   * )
    +   * }</pre>
    +   */
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testOuterAggregationOverTaskSubquery(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT SUM(task_count) "
    +        + "FROM ("
    +        + "  SELECT datasource, COUNT(*) AS task_count "
    +        + "  FROM sys.tasks "
    +        + "  WHERE datasource IN ('native_sys_a', 'native_sys_b') "
    +        + "  GROUP BY datasource"
    +        + ")",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5", result);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testInAndOrFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id IN ('native_sys_mvp_a_0', 'native_sys_mvp_b_2') "
    +        + "OR task_id = 'native_sys_mvp_missing'",
    +        Set.of("native_sys_mvp_a_0", "native_sys_mvp_b_2"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testRangeAndLikeFilters(final String plannerStrategy)
    +  {
    +    assertTaskFilterQuery(
    +        "task_id >= 'native_sys_mvp_b_0' "
    +        + "AND task_id < 'native_sys_mvp_b_2' "
    +        + "AND task_id LIKE 'native_sys_mvp_b_%'",
    +        Set.of("native_sys_mvp_b_0", "native_sys_mvp_b_1"),
    +        plannerStrategy
    +    );
    +  }
    +
    +  /**
    +   * Verifies that expression virtual columns required by a pushed node filter are preserved.
    +   *
    +   * <pre>{@code
    +   * SELECT task_id
    +   * FROM sys.tasks
    +   * WHERE UPPER(task_id) = 'NATIVE_SYS_MVP_A_0'
    +   * }</pre>
    +   */

    Addressed in the stacked sys.tasks PR: the repeated SQL Javadocs in this test were removed. See FrankChen021/druid#198.

    FrankChen021 FrankChen021 commented on code on Sep 09, 2026 03:54 UTC
    Code Review
    embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/NativeSysTasksQueryTest.java:1
    @@ -0,0 +1,344 @@
    +/*
    + * 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.druid.testing.embedded.query;
    +
    +import org.apache.druid.indexing.common.task.NoopTask;
    +import org.apache.druid.java.util.common.StringUtils;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.sql.calcite.planner.PlannerContext;
    +import org.apache.druid.sql.calcite.run.NativeSqlEngine;
    +import org.apache.druid.testing.embedded.EmbeddedBroker;
    +import org.apache.druid.testing.embedded.EmbeddedCoordinator;
    +import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
    +import org.apache.druid.testing.embedded.EmbeddedIndexer;
    +import org.apache.druid.testing.embedded.EmbeddedOverlord;
    +import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
    +import org.junit.jupiter.api.Assertions;
    +import org.junit.jupiter.api.BeforeAll;
    +import org.junit.jupiter.params.ParameterizedTest;
    +import org.junit.jupiter.params.provider.ValueSource;
    +
    +import java.util.Arrays;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +public class NativeSysTasksQueryTest extends EmbeddedClusterTestBase
    +{
    +  private static final String TASK_PREFIX = "native_sys_mvp_";
    +
    +  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
    +  private final EmbeddedBroker broker = new EmbeddedBroker();
    +
    +  @Override
    +  protected EmbeddedDruidCluster createCluster()
    +  {
    +    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
    +                               .useLatchableEmitter()
    +                               .addServer(new EmbeddedCoordinator())
    +                               .addServer(new EmbeddedIndexer()
    +                                              .addProperty("druid.worker.capacity", "5"))
    +                               .addServer(overlord)
    +                               .addServer(broker);
    +  }
    +
    +  @BeforeAll
    +  public void createTasks()
    +  {
    +    createTasks("a", "native_sys_a", 2);
    +    createTasks("b", "native_sys_b", 3);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testGroupByUsesOverlordProvider(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT datasource, COUNT(*) "
    +        + "FROM sys.tasks "
    +        + "WHERE task_id = 'native_sys_mvp_a_0' AND datasource = 'native_sys_a' "
    +        + "GROUP BY datasource",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    final Set<String> rows = Arrays.stream(result.split("\\n")).collect(Collectors.toSet());
    +    Assertions.assertEquals(Set.of("native_sys_a,1"), rows);
    +  }
    +
    +  @ParameterizedTest(name = "plannerStrategy = {0}")
    +  @ValueSource(strings = {
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_COUPLED,
    +      QueryContexts.NATIVE_QUERY_SQL_PLANNING_MODE_DECOUPLED
    +  })
    +  public void testNativeAggregationsSupportDistinctCount(final String plannerStrategy)
    +  {
    +    final String result = cluster.runSql(
    +        "SELECT COUNT(*), COUNT(DISTINCT task_id), COUNT(DISTINCT datasource), SUM(1) "
    +        + "FROM sys.tasks "
    +        + "WHERE datasource IN ('native_sys_a', 'native_sys_b')",
    +        nativeQueryContext(plannerStrategy)
    +    );
    +
    +    Assertions.assertEquals("5,5,2,5", result);
    +  }
    +
    +  /**
    +   * Verifies execution when native planning represents the inner aggregation as a query datasource.
    +   *
    +   * <pre>{@code
    +   * SELECT COUNT(*)
    +   * FROM
    +   * (
    +   *   SELECT
    +   *     task_id,
    +   *     COUNT(*) AS task_count
    +   *   FROM sys.tasks
    +   *   WHERE datasource IN ('native_sys_a', 'native_sys_b')
    +   *   GROUP BY task_id
    +   * )
    +   * WHERE task_count > 0
    +   * }</pre>
    +   */

    Addressed in the stacked sys.tasks PR: the redundant test Javadocs were removed. See FrankChen021/druid#198.

    gianm gianm commented on Sep 09, 2026 07:27 UTC
    Contributor

    @clintropolis @gianm please help review the changes. I hope this can be merged as soon as possible so that we can move on migrating other system tables into native execution path, and push forward for #18087 and #19855

    Very cool. I will try to have a look soon.

    FrankChen021 FrankChen021 commented on code on Sep 09, 2026 14:01 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/handler/SystemTableQueryHandler.java:1
    @@ -0,0 +1,162 @@
    +/*
    + * 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.druid.server.system.handler;
    +
    +import com.google.inject.Inject;
    +import org.apache.druid.client.DirectDruidClient;
    +import org.apache.druid.java.util.common.IAE;
    +import org.apache.druid.java.util.common.ISE;
    +import org.apache.druid.java.util.common.JodaUtils;
    +import org.apache.druid.java.util.common.guava.Sequence;
    +import org.apache.druid.query.Druids;
    +import org.apache.druid.query.InlineDataSource;
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.QueryPlus;
    +import org.apache.druid.query.QueryRunner;
    +import org.apache.druid.query.SystemTableDataSource;
    +import org.apache.druid.query.context.ResponseContext;
    +import org.apache.druid.query.scan.ScanQuery;
    +import org.apache.druid.query.scan.ScanQueryEngine;
    +import org.apache.druid.segment.InlineSegmentWrangler;
    +import org.apache.druid.segment.Segment;
    +import org.apache.druid.server.DataSourceQueryHandler;
    +import org.apache.druid.server.security.AuthenticationResult;
    +import org.apache.druid.server.security.AuthorizerMapper;
    +import org.apache.druid.server.system.table.SystemTableDataProvider;
    +import org.apache.druid.server.system.table.SystemTableDescriptor;
    +import org.apache.druid.server.system.table.SystemTablePushdownFilter;
    +
    +import java.util.Map;
    +
    +/** Resolves one node-local system table and returns its rows through the standard native Scan stack. */
    +public class SystemTableQueryHandler implements DataSourceQueryHandler
    +{
    +  private final Map<String, SystemTableDataProvider> dataSuppliers;
    +  private final Map<String, SystemTableDescriptor> tableDescriptors;
    +  private final ScanQueryEngine scanQueryEngine;
    +  private final AuthorizerMapper authorizerMapper;
    +
    +  @Inject
    +  public SystemTableQueryHandler(
    +      final Map<String, SystemTableDataProvider> dataSuppliers,
    +      final Map<String, SystemTableDescriptor> tableDescriptors,
    +      final ScanQueryEngine scanQueryEngine,
    +      final AuthorizerMapper authorizerMapper
    +  )
    +  {
    +    this.dataSuppliers = dataSuppliers;
    +    this.tableDescriptors = tableDescriptors;
    +    this.scanQueryEngine = scanQueryEngine;
    +    this.authorizerMapper = authorizerMapper;
    +  }
    +
    +  @Override
    +  public <T> QueryRunner<T> createRunner(
    +      final Query<T> query,
    +      final AuthenticationResult requestAuthenticationResult,
    +      final boolean executeLocally
    +  )
    +  {
    +    if (!(query instanceof ScanQuery)) {
    +      throw new IAE("Local system table queries must be scan queries");
    +    }
    +
    +    final SystemTableDataSource dataSource = (SystemTableDataSource) query.getDataSource();

    [P2] [P2] Handle nested system-table datasources before casting the root

    QueryLifecycle.findDataSourceQueryHandler deliberately selects this handler when a registered datasource appears below the root, and DataSourceQueryHandler documents that the handler receives the complete query. A native ScanQuery such as a join or QueryDataSource containing SystemTableDataSource therefore reaches this method with a composite root and throws ClassCastException at this cast. The Router also forwards a composite query carrying X-Druid-Native-Query-Route: local to the Broker, whose local handler takes this same path. Native system-table joins are advertised as supported; either recursively replace local system-table leaves here or reject/route composite local requests before selecting this handler.

    FrankChen021 FrankChen021 commented on Sep 09, 2026 14:01 UTC
    Reviewer

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 0 |
    | P2 | 1 |
    | P3 | 0 |
    | Total | 1 |

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 0 |
    | P2 | 1 |
    | P3 | 0 |
    | Total | 1 |

    ---

    Reviewed 90 of 90 changed files.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on code on Sep 11, 2026 13:45 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/handler/SystemTableQueryHandler.java:1
    @@ -0,0 +1,162 @@
    +/*
    + * 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.druid.server.system.handler;
    +
    +import com.google.inject.Inject;
    +import org.apache.druid.client.DirectDruidClient;
    +import org.apache.druid.java.util.common.IAE;
    +import org.apache.druid.java.util.common.ISE;
    +import org.apache.druid.java.util.common.JodaUtils;
    +import org.apache.druid.java.util.common.guava.Sequence;
    +import org.apache.druid.query.Druids;
    +import org.apache.druid.query.InlineDataSource;
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.QueryPlus;
    +import org.apache.druid.query.QueryRunner;
    +import org.apache.druid.query.SystemTableDataSource;
    +import org.apache.druid.query.context.ResponseContext;
    +import org.apache.druid.query.scan.ScanQuery;
    +import org.apache.druid.query.scan.ScanQueryEngine;
    +import org.apache.druid.segment.InlineSegmentWrangler;
    +import org.apache.druid.segment.Segment;
    +import org.apache.druid.server.DataSourceQueryHandler;
    +import org.apache.druid.server.security.AuthenticationResult;
    +import org.apache.druid.server.security.AuthorizerMapper;
    +import org.apache.druid.server.system.table.SystemTableDataProvider;
    +import org.apache.druid.server.system.table.SystemTableDescriptor;
    +import org.apache.druid.server.system.table.SystemTablePushdownFilter;
    +
    +import java.util.Map;
    +
    +/** Resolves one node-local system table and returns its rows through the standard native Scan stack. */
    +public class SystemTableQueryHandler implements DataSourceQueryHandler
    +{
    +  private final Map<String, SystemTableDataProvider> dataSuppliers;
    +  private final Map<String, SystemTableDescriptor> tableDescriptors;
    +  private final ScanQueryEngine scanQueryEngine;
    +  private final AuthorizerMapper authorizerMapper;
    +
    +  @Inject
    +  public SystemTableQueryHandler(
    +      final Map<String, SystemTableDataProvider> dataSuppliers,
    +      final Map<String, SystemTableDescriptor> tableDescriptors,
    +      final ScanQueryEngine scanQueryEngine,
    +      final AuthorizerMapper authorizerMapper
    +  )
    +  {
    +    this.dataSuppliers = dataSuppliers;
    +    this.tableDescriptors = tableDescriptors;
    +    this.scanQueryEngine = scanQueryEngine;
    +    this.authorizerMapper = authorizerMapper;
    +  }
    +
    +  @Override
    +  public <T> QueryRunner<T> createRunner(
    +      final Query<T> query,
    +      final AuthenticationResult requestAuthenticationResult,
    +      final boolean executeLocally
    +  )
    +  {
    +    if (!(query instanceof ScanQuery)) {
    +      throw new IAE("Local system table queries must be scan queries");
    +    }
    +
    +    final SystemTableDataSource dataSource = (SystemTableDataSource) query.getDataSource();

    Fixed in 922c82dcdd.

    Local execution now requires a root SystemTableDataSource; a composite query carrying the local-route header is rejected with BadQueryContextException instead of reaching the unsafe cast. SystemTableQueryHandler also validates the datasource shape defensively. Composite queries without the local-route header continue through SystemTableQueryClient, which recursively resolves system-table leaves.

    Added regression coverage in SystemTableBrokerQueryHandlerTest and SystemTableQueryHandlerTest. The focused server run passed all 5 tests.

    <!-- mergelens:review -->

    FrankChen021 FrankChen021 commented on Sep 11, 2026 14:50 UTC
    Reviewer

    🟢 Approval recommended

    Rechecked the updated head against the prior reviewed SHA, beginning with the incremental patch. The prior P2 concerning nested or composite system-table datasources is resolved: local execution now rejects a non-system-table root with BadQueryContextException, and the updated tests cover both broker and node-local handlers. Composite queries without the local route continue through the recursive system-table client path.

    The full current diff and surrounding code were reviewed across all 90 changed files, including SQL planning and authorization, native datasource conversion, node discovery/fanout/recovery, request routing, lifecycle and cancellation, service-module wiring, and regression tests. No additional high-confidence correctness, security, compatibility, data-loss, concurrency, lifecycle, integration, or missing-test finding was identified.

    Validation performed: git diff --check 8c05f05adbe8f7ccf647c135caa948cc083fae8b -- passed. No builds, broad tests, dependency installs, formatters, prepare, fetch, or cleanup were run, per the review scope.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Sep 22, 2026 13:05 UTC
    Reviewer

    🟢 Approval recommended

    Rechecked the current head beginning with the incremental patch. The incremental patch is the merge of current master into the previously reviewed PR head; the PR logic is unchanged since the prior review. The prior P2 about composite or nested system-table datasources remains resolved: local routing rejects a non-system-table root, while non-local Broker execution recursively resolves system-table leaves.

    Reviewed 90 of 90 changed files. The full current diff and relevant surrounding code were reviewed across SQL planner selection and authorization, native datasource conversion, node discovery and leader routing, request forwarding, local and remote execution, failure recovery, cancellation and lifecycle cleanup, service-module wiring, and regression tests. No additional high-confidence correctness, security, compatibility, data-loss, concurrency, lifecycle, integration, or missing-test issue was found.

    Validation: git diff --check cf84e5f1b09ce3b05c2f5c015e5259bf66b7a7e6 -- passed. No builds, broad tests, dependency installs, formatters, prepare, fetch, or cleanup were run.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Oct 02, 2026 12:46 UTC
    Reviewer

    🟢 Approval recommended

    Rechecked the incremental patch first. It is the merge of current master into the previously reviewed PR head, so it contains upstream churn rather than additional PR logic; I then revalidated the full current PR diff and the prior composite/nested system-table routing finding at the current head.

    Reviewed 90 of 90 changed files. Coverage included SQL planner native/bindable selection and authorization, native datasource conversion, system-table descriptors and providers, node discovery and leader routing, Router/Broker/local forwarding, local and remote execution, failure recovery, cancellation and lifecycle cleanup, service-module wiring, and regression and embedded tests.

    Validation: git diff --check 631f05de5d1d05edfbbab3adc8dbbb99745678ee 0e7033010c84ac45dc909e36d843046fd18bb919 -- passed. No broad builds or test suites were run per review scope.

    No actionable PR-caused correctness, security, compatibility, data-loss, concurrency, lifecycle, integration, or high-confidence missing-test issue found. The prior composite/nested system-table routing finding remains resolved by the current root-datasource checks and recursive non-local resolution.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Oct 09, 2026 12:22 UTC
    Reviewer

    🟡 Changes recommended

    Fix virtual-column handling in provider filter pushdown before merging: filters on virtual columns named server or service_name can currently discard matching rows by comparing against physical node metadata. The incremental authorization-plan traversal and recovery simplification introduce no additional confirmed issue.

    Reviewed 90 of 90 changed files, starting with the 6-file incremental diff and then reviewing the full current diff and relevant surrounding code. Rechecked the prior composite/nested system-table routing finding; it remains resolved by the local root checks and recursive Broker resolution. Coverage included SQL planning and authorization, native datasource conversion, node discovery and fanout, request routing, recovery, cancellation and cleanup, module wiring, and regression tests.

    Validation: git diff --check 631f05de5d1d05edfbbab3adc8dbbb99745678ee HEAD -- passed. This was a static review; builds and test suites were not run.

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 0 |
    | P2 | 1 |
    | P3 | 0 |
    | Total | 1 |

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

    FrankChen021 FrankChen021 commented on code on Oct 09, 2026 12:22 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/table/SystemTablePushdownFilter.java:1
    @@ -0,0 +1,248 @@
    +/*
    + * 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.druid.server.system.table;
    +
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.filter.AndDimFilter;
    +import org.apache.druid.query.filter.BoundDimFilter;
    +import org.apache.druid.query.filter.DimFilter;
    +import org.apache.druid.query.filter.EqualityFilter;
    +import org.apache.druid.query.filter.InDimFilter;
    +import org.apache.druid.query.filter.LikeDimFilter;
    +import org.apache.druid.query.filter.NotDimFilter;
    +import org.apache.druid.query.filter.OrDimFilter;
    +import org.apache.druid.query.filter.RangeFilter;
    +import org.apache.druid.query.filter.SelectorDimFilter;
    +import org.apache.druid.query.filter.TypedInFilter;
    +import org.apache.druid.query.operator.OperatorFactory;
    +import org.apache.druid.query.operator.ScanOperatorFactory;
    +import org.apache.druid.query.operator.WindowOperatorQuery;
    +import org.apache.druid.query.ordering.StringComparators;
    +import org.apache.druid.segment.column.ColumnType;
    +
    +import javax.annotation.Nullable;
    +import java.util.ArrayList;
    +import java.util.Collections;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Objects;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +/**
    + * Declares a pushdown-capable system-table column and its optional supplier-side name.
    + */
    +public record SystemTablePushdownFilter(String key, @Nullable String value)
    +{
    +  public static List<DimFilter> extract(
    +      final Query<?> query,
    +      final List<SystemTablePushdownFilter> pushdownFilters
    +  )
    +  {
    +    if (pushdownFilters.isEmpty()) {
    +      return Collections.emptyList();
    +    }
    +    final Map<String, String> columnMappings = pushdownFilters.stream().collect(
    +        Collectors.toMap(
    +            SystemTablePushdownFilter::key,
    +            filter -> filter.value() == null ? filter.key() : filter.value()
    +        )
    +    );
    +
    +    final List<DimFilter> extracted = new ArrayList<>();
    +    extractConjuncts(query.getFilter(), columnMappings, extracted);

    [P2] Exclude virtual columns from provider filter pushdown

    Finding: The extraction checks only the column name and ignores the query's virtual columns. A valid local native Scan of server_properties can define a constant STRING virtual column named server with value alias and filter server = alias. Druid's virtualized selectors give that column precedence over the physical server, so all rows should match, but this method pushes the selector to ServerPropertiesTableDataProvider, which compares alias to the actual host:port and returns no rows before the native filter runs. The same issue affects service_name and Broker fanout when it forwards these virtual columns. This silently changes query results.

    Suggestion: Exclude columns shadowed by query or leaf-scan virtual columns from supplier-side pushdown, and add a regression case for a native Scan that shadows a pushdown column.

    FrankChen021 FrankChen021 commented on code on Oct 10, 2026 04:52 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/table/SystemTablePushdownFilter.java:1
    @@ -0,0 +1,248 @@
    +/*
    + * 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.druid.server.system.table;
    +
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.filter.AndDimFilter;
    +import org.apache.druid.query.filter.BoundDimFilter;
    +import org.apache.druid.query.filter.DimFilter;
    +import org.apache.druid.query.filter.EqualityFilter;
    +import org.apache.druid.query.filter.InDimFilter;
    +import org.apache.druid.query.filter.LikeDimFilter;
    +import org.apache.druid.query.filter.NotDimFilter;
    +import org.apache.druid.query.filter.OrDimFilter;
    +import org.apache.druid.query.filter.RangeFilter;
    +import org.apache.druid.query.filter.SelectorDimFilter;
    +import org.apache.druid.query.filter.TypedInFilter;
    +import org.apache.druid.query.operator.OperatorFactory;
    +import org.apache.druid.query.operator.ScanOperatorFactory;
    +import org.apache.druid.query.operator.WindowOperatorQuery;
    +import org.apache.druid.query.ordering.StringComparators;
    +import org.apache.druid.segment.column.ColumnType;
    +
    +import javax.annotation.Nullable;
    +import java.util.ArrayList;
    +import java.util.Collections;
    +import java.util.HashSet;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Objects;
    +import java.util.Set;
    +import java.util.stream.Collectors;
    +
    +/**
    + * Declares a pushdown-capable system-table column and its optional supplier-side name.
    + */
    +public record SystemTablePushdownFilter(String key, @Nullable String value)
    +{
    +  public static List<DimFilter> extract(
    +      final Query<?> query,
    +      final List<SystemTablePushdownFilter> pushdownFilters
    +  )
    +  {
    +    if (pushdownFilters.isEmpty()) {
    +      return Collections.emptyList();
    +    }
    +    final Map<String, String> columnMappings = pushdownFilters.stream().collect(
    +        Collectors.toMap(
    +            SystemTablePushdownFilter::key,
    +            filter -> filter.value() == null ? filter.key() : filter.value()
    +        )
    +    );
    +
    +    final List<DimFilter> extracted = new ArrayList<>();
    +    extractConjuncts(query.getFilter(), columnMappings, extracted);

    Fixed in 12d36e8233.

    Reproduced first: the new SystemTableQueryHandlerTest#testFilterOnVirtualColumnShadowingPushdownColumnKeepsMatchingRows runs a local server_properties Scan with a constant virtual column server = 'alias' and filter server = 'alias'. On the previous head it returned 0 rows (expected 1) because the provider compared alias against the physical host:port; with the fix it returns the expected row.

    SystemTablePushdownFilter.extract now excludes pushdown columns shadowed by query or window leaf-scan virtual columns, so those filters stay in the native scan. Non-shadowed conjuncts are still pushed down. Broker fanout forwards the virtual columns together with the pushed filter, so the node-side extraction applies the same rule. Also added extraction-level regression tests in SystemTablePushdownFilterTest for the query-level and window leaf-scan cases.

    FrankChen021 FrankChen021 commented on code on Oct 10, 2026 12:54 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/handler/SystemTableQueryClient.java:1
    @@ -0,0 +1,899 @@
    +/*
    + * 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.druid.server.system.handler;
    +
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.Iterables;
    +import com.google.inject.Inject;
    +import io.netty.channel.ChannelException;
    +import org.apache.druid.client.DirectDruidClient;
    +import org.apache.druid.client.DirectDruidClientFactory;
    +import org.apache.druid.client.DruidServer;
    +import org.apache.druid.discovery.DiscoveryDruidNode;
    +import org.apache.druid.guice.annotations.Self;
    +import org.apache.druid.java.util.common.ISE;
    +import org.apache.druid.java.util.common.JodaUtils;
    +import org.apache.druid.java.util.common.guava.BaseSequence;
    +import org.apache.druid.java.util.common.guava.LazySequence;
    +import org.apache.druid.java.util.common.guava.Sequence;
    +import org.apache.druid.java.util.common.guava.Sequences;
    +import org.apache.druid.java.util.common.guava.Yielder;
    +import org.apache.druid.java.util.common.guava.Yielders;
    +import org.apache.druid.query.BaseQuery;
    +import org.apache.druid.query.DataSource;
    +import org.apache.druid.query.Druids;
    +import org.apache.druid.query.InlineDataSource;
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.query.QueryDataSource;
    +import org.apache.druid.query.QueryException;
    +import org.apache.druid.query.QueryInterruptedException;
    +import org.apache.druid.query.QueryPlus;
    +import org.apache.druid.query.QueryRunner;
    +import org.apache.druid.query.QuerySegmentWalker;
    +import org.apache.druid.query.QueryTimeoutException;
    +import org.apache.druid.query.SystemTableDataSource;
    +import org.apache.druid.query.context.ResponseContext;
    +import org.apache.druid.query.filter.AndDimFilter;
    +import org.apache.druid.query.filter.DimFilter;
    +import org.apache.druid.query.operator.OperatorFactory;
    +import org.apache.druid.query.operator.ScanOperatorFactory;
    +import org.apache.druid.query.operator.WindowOperatorQuery;
    +import org.apache.druid.query.scan.ScanQuery;
    +import org.apache.druid.query.scan.ScanResultValue;
    +import org.apache.druid.segment.VirtualColumn;
    +import org.apache.druid.segment.VirtualColumns;
    +import org.apache.druid.server.DataSourceQueryHandler;
    +import org.apache.druid.server.DruidNode;
    +import org.apache.druid.server.QueryScheduler;
    +import org.apache.druid.server.coordination.ServerType;
    +import org.apache.druid.server.security.AuthenticationResult;
    +import org.apache.druid.server.security.AuthorizerMapper;
    +import org.apache.druid.server.security.Escalator;
    +import org.apache.druid.server.system.SystemTableNotLeaderException;
    +import org.apache.druid.server.system.table.SystemTableDescriptor;
    +import org.apache.druid.server.system.table.SystemTableRoutingMode;
    +import org.apache.druid.utils.CloseableUtils;
    +
    +import javax.annotation.Nullable;
    +import java.io.Closeable;
    +import java.io.EOFException;
    +import java.io.IOException;
    +import java.net.SocketException;
    +import java.net.UnknownHostException;
    +import java.nio.channels.ClosedChannelException;
    +import java.util.ArrayList;
    +import java.util.Iterator;
    +import java.util.LinkedHashMap;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.NoSuchElementException;
    +import java.util.Optional;
    +import java.util.UUID;
    +import java.util.function.Supplier;
    +
    +/**
    + * Recursively replaces native system-table datasources with authorized inline rows fetched from nodes, then
    + * executes the rebuilt query through the Broker's normal native-query walker.
    + */
    +public class SystemTableQueryClient implements DataSourceQueryHandler
    +{
    +  private static final String SYSTEM_TABLE_TIER = "_system";
    +
    +  private final SystemTableNodeLocator nodeLocator;
    +  private final DirectDruidClientFactory directDruidClientFactory;
    +  private final QueryScheduler queryScheduler;
    +  private final QuerySegmentWalker querySegmentWalker;
    +  private final Map<String, SystemTableDescriptor> tableDescriptors;
    +  private final AuthorizerMapper authorizerMapper;
    +  private final SystemTableQueryHandler localQueryHandler;
    +  private final AuthenticationResult escalatedAuthenticationResult;
    +  private final DruidNode selfNode;
    +
    +  @Inject
    +  public SystemTableQueryClient(
    +      final SystemTableNodeLocator nodeLocator,
    +      final DirectDruidClientFactory directDruidClientFactory,
    +      final QueryScheduler queryScheduler,
    +      final QuerySegmentWalker querySegmentWalker,
    +      final Map<String, SystemTableDescriptor> tableDescriptors,
    +      final AuthorizerMapper authorizerMapper,
    +      final SystemTableQueryHandler localQueryHandler,
    +      final Escalator escalator,
    +      @Self final DruidNode selfNode
    +  )
    +  {
    +    this.nodeLocator = nodeLocator;
    +    this.directDruidClientFactory = directDruidClientFactory;
    +    this.queryScheduler = queryScheduler;
    +    this.querySegmentWalker = querySegmentWalker;
    +    this.tableDescriptors = tableDescriptors;
    +    this.authorizerMapper = authorizerMapper;
    +    this.localQueryHandler = localQueryHandler;
    +    this.escalatedAuthenticationResult = escalator.createEscalatedAuthenticationResult();
    +    this.selfNode = selfNode;
    +  }
    +
    +  @Override
    +  public <T> QueryRunner<T> createRunner(
    +      final Query<T> query,
    +      final AuthenticationResult authenticationResult,
    +      final boolean executeLocally
    +  )
    +  {
    +    return (queryPlus, responseContext) -> {
    +      final NodeSequencesCloser nodeSequencesCloser = new NodeSequencesCloser(queryScheduler);
    +      try {
    +        final DataSource resolvedDataSource = resolveDataSource(
    +            query.getDataSource(),
    +            query,
    +            authenticationResult,
    +            responseContext,
    +            nodeSequencesCloser
    +        );
    +        final Query<T> resolvedQuery = query.withDataSource(resolvedDataSource).withOverriddenContext(
    +            Map.of(QueryContexts.QUERY_RESOURCE_ID, UUID.randomUUID().toString())
    +        );
    +        final QueryRunner<T> queryRunner = querySegmentWalker.getQueryRunnerForIntervals(
    +            resolvedQuery,
    +            resolvedQuery.getIntervals()
    +        );
    +        return Sequences.withBaggage(
    +            queryRunner.run(queryPlus.withQuery(resolvedQuery), responseContext),
    +            nodeSequencesCloser
    +        );
    +      }
    +      catch (Throwable t) {
    +        throw CloseableUtils.closeAndWrapInCatch(t, nodeSequencesCloser);
    +      }
    +    };
    +  }
    +
    +  private DataSource resolveDataSource(
    +      final DataSource dataSource,
    +      final Query<?> owningQuery,
    +      final AuthenticationResult authenticationResult,
    +      final ResponseContext responseContext,
    +      final NodeSequencesCloser nodeSequencesCloser
    +  )
    +  {
    +    if (dataSource instanceof SystemTableDataSource systemTableDataSource) {
    +      return resolveSystemTableDataSource(
    +          systemTableDataSource,
    +          owningQuery,
    +          authenticationResult,
    +          responseContext,
    +          nodeSequencesCloser
    +      );
    +    }
    +
    +    final Query<?> childOwningQuery = dataSource instanceof QueryDataSource queryDataSource
    +                                      ? queryDataSource.getQuery()
    +                                      : owningQuery;
    +    final List<DataSource> resolvedChildren = new ArrayList<>();
    +    for (final DataSource child : dataSource.getChildren()) {
    +      resolvedChildren.add(
    +          resolveDataSource(
    +              child,
    +              childOwningQuery,
    +              authenticationResult,
    +              responseContext,
    +              nodeSequencesCloser
    +          )
    +      );
    +    }
    +    return dataSource.withChildren(resolvedChildren);
    +  }
    +
    +  private InlineDataSource resolveSystemTableDataSource(
    +      final SystemTableDataSource dataSource,
    +      final Query<?> owningQuery,
    +      final AuthenticationResult authenticationResult,
    +      final ResponseContext responseContext,
    +      final NodeSequencesCloser nodeSequencesCloser
    +  )
    +  {
    +    final SystemTableDescriptor descriptor = tableDescriptors.get(dataSource.getTable());
    +    if (descriptor == null) {
    +      throw new ISE("No routing descriptor is registered for system table[%s]", dataSource.getTable());
    +    }
    +
    +    final ScanQuery nodeQuery = makeNodeQuery(dataSource, descriptor, owningQuery);
    +    final List<QueryRunner<ScanResultValue>> nodeRunners = makeNodeRunners(
    +        nodeQuery,
    +        descriptor,
    +        nodeSequencesCloser
    +    );
    +    if (nodeRunners.isEmpty() && !descriptor.isEmptyDiscoveryAllowed()) {
    +      throw new ISE("No node is available to serve system table[%s]", dataSource.getTable());
    +    }
    +
    +    /*
    +     * Keep the scan result transport lazy. The node response is a Sequence, so this lets the local query
    +     * runner consume and process rows while the HTTP response is still arriving instead of materializing every
    +     * node row in two Broker-side lists. The scan transport is intentionally kept behind this adapter so a
    +     * future node-side aggregation mode can use a different result adapter without changing routing or
    +     * authorization orchestration here.
    +     */
    +    final NodeSequenceCloser nodeSequenceCloser = new NodeSequenceCloser();
    +    nodeSequencesCloser.add(nodeSequenceCloser);
    +    final Iterable<Object[]> nodeRows = scanNodeRows(
    +        nodeRunners,
    +        nodeQuery,
    +        responseContext,
    +        nodeSequenceCloser
    +    );
    +    final Iterable<Object[]> authorizedRows = descriptor.getRowAuthorizer().filterAuthorizedRows(
    +        nodeRows,
    +        authenticationResult,
    +        authorizerMapper
    +    );
    +    final Iterable<Object[]> queryRows = requiresMaterializedRows(owningQuery)
    +                                         ? materializeRows(authorizedRows)
    +                                         : authorizedRows;
    +    return InlineDataSource.fromIterable(queryRows, descriptor.getRowSignature());
    +  }
    +
    +  private ScanQuery makeNodeQuery(
    +      final SystemTableDataSource dataSource,
    +      final SystemTableDescriptor descriptor,
    +      final Query<?> owningQuery
    +  )
    +  {
    +    final Map<String, Object> nodeContext = new LinkedHashMap<>(owningQuery.getContext());
    +    final DimFilter nodeFilter = nodeFilter(dataSource, owningQuery);
    +    nodeContext.put(DirectDruidClient.QUERY_FAIL_TIME, getNodeFailTime(owningQuery));
    +    // The node endpoint always returns plain ScanResultValue objects. bySegment belongs to the user-facing query and
    +    // would make DirectDruidClient deserialize this private transport using an incompatible result type.
    +    nodeContext.put(QueryContexts.BY_SEGMENT_KEY, false);
    +    return Druids.newScanQueryBuilder()
    +                 .dataSource(dataSource)
    +                 .eternityInterval()
    +                 .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
    +                 .limit(Long.MAX_VALUE)
    +                 .filters(nodeFilter)
    +                 .virtualColumns(nodeVirtualColumns(dataSource, owningQuery, nodeFilter))
    +                 .columns(descriptor.getRowSignature())
    +                 .context(nodeContext)
    +                 .build();
    +  }
    +
    +  private List<QueryRunner<ScanResultValue>> makeNodeRunners(
    +      final ScanQuery nodeQuery,
    +      final SystemTableDescriptor descriptor,
    +      final NodeSequencesCloser nodeSequencesCloser
    +  )
    +  {
    +    final List<QueryRunner<ScanResultValue>> nodeRunners = new ArrayList<>();
    +    for (final SystemTableNode node : nodeLocator.locate(descriptor, nodeQuery)) {
    +      nodeRunners.add(
    +          (queryPlus, responseContext) -> recoverNodeFailure(
    +              () -> runNodeQuery(nodeQuery, node, nodeSequencesCloser, queryPlus, responseContext),
    +              node,
    +              descriptor,
    +              descriptor.getRoutingMode() == SystemTableRoutingMode.LEADER_ONLY
    +              ? () -> {
    +                final SystemTableNode currentLeader = Iterables.getOnlyElement(
    +                    nodeLocator.locate(descriptor, nodeQuery)
    +                );
    +                return new NodeQuerySequence(
    +                    currentLeader,
    +                    runNodeQuery(nodeQuery, currentLeader, nodeSequencesCloser, queryPlus, responseContext)
    +                );
    +              }
    +              : null
    +          )
    +      );
    +    }
    +    return nodeRunners;
    +  }
    +
    +  private Sequence<ScanResultValue> runNodeQuery(
    +      final ScanQuery nodeQuery,
    +      final SystemTableNode node,
    +      final NodeSequencesCloser nodeSequencesCloser,
    +      final QueryPlus<ScanResultValue> queryPlus,
    +      final ResponseContext responseContext
    +  )
    +  {
    +    final String nodeResourceId = UUID.randomUUID().toString();
    +    final String nodeQueryId = SystemTableDataSource.NODE_QUERY_ID_PREFIX + UUID.randomUUID();
    +    final ScanQuery subNativeQuery = nodeQuery.withOverriddenContext(
    +        Map.of(
    +            BaseQuery.QUERY_ID,
    +            nodeQueryId,
    +            QueryContexts.QUERY_RESOURCE_ID,
    +            nodeResourceId
    +        )
    +    );
    +    final QueryRunner<ScanResultValue> nodeRunner;
    +    if (SystemTableNodeLocator.sameServer(
    +        selfNode.getUriToUse(),
    +        node.getDiscoveryNode().getDruidNode().getUriToUse()
    +    )) {
    +      // Invoke the raw local handler rather than the Broker handler. This avoids an HTTP request back to this
    +      // Broker and, more importantly, prevents the local request from entering node fanout recursively.
    +      nodeRunner = localQueryHandler.createRunner(subNativeQuery, escalatedAuthenticationResult, true);
    +    } else {
    +      nodeRunner = directDruidClientFactory.makeDirectClient(toDruidServer(node.getDiscoveryNode()));
    +      nodeSequencesCloser.addQueryId(nodeQueryId);
    +    }
    +    return nodeRunner.run(queryPlus.withQuery(subNativeQuery), responseContext);
    +  }
    +
    +  /**
    +   * Window operators consume a {@code RowsAndColumns} view of the segment. The current row-based segment can only
    +   * provide that view when its rows are list-backed, so preserve the existing materialized path for those queries.
    +   */
    +  private static boolean requiresMaterializedRows(final Query<?> query)
    +  {
    +    return query instanceof WindowOperatorQuery;
    +  }
    +
    +  /**
    +   * Eagerly consumes the lazy, single-pass node response into an {@link ArrayList} without changing its rows.
    +   *
    +   * <p>This representation change is required by {@link org.apache.druid.segment.InlineSegmentWrangler}: an inline
    +   * datasource backed specifically by an {@code ArrayList} becomes an {@link org.apache.druid.segment.ArrayListSegment},
    +   * which can provide the {@code RowsAndColumns} view required by window operators. Other query types retain the lazy
    +   * iterable so the Broker can process rows while node responses are still arriving.</p>
    +   */
    +  private static Iterable<Object[]> materializeRows(final Iterable<Object[]> rows)
    +  {
    +    final List<Object[]> materializedRows = new ArrayList<>();
    +    rows.forEach(materializedRows::add);
    +    return materializedRows;
    +  }
    +
    +  /**
    +   * Creates a lazy, single-pass view of the rows returned by the node scan runners.
    +   *
    +   * <p>The view is single-pass because a node response is backed by a live HTTP stream. The normal native query
    +   * path consumes an {@link InlineDataSource} once per query. Re-iterating would otherwise issue duplicate node
    +   * requests or retain all rows to support replay.</p>
    +   */
    +  static Iterable<Object[]> scanNodeRows(
    +      final List<QueryRunner<ScanResultValue>> nodeRunners,
    +      final Query<ScanResultValue> nodeQuery,
    +      final ResponseContext responseContext
    +  )
    +  {
    +    return scanNodeRows(
    +        nodeRunners,
    +        nodeQuery,
    +        responseContext,
    +        new NodeSequenceCloser()
    +    );
    +  }
    +
    +  private static Iterable<Object[]> scanNodeRows(
    +      final List<QueryRunner<ScanResultValue>> nodeRunners,
    +      final Query<ScanResultValue> nodeQuery,
    +      final ResponseContext responseContext,
    +      final NodeSequenceCloser nodeSequenceCloser
    +  )
    +  {
    +    final Sequence<Object[]> rows = new LazySequence<>(() -> {
    +      final List<Sequence<ScanResultValue>> nodeSequences = new ArrayList<>();
    +      for (final QueryRunner<ScanResultValue> nodeRunner : nodeRunners) {
    +        // DirectDruidClient.run starts its asynchronous HTTP request. Start every request before waiting for any
    +        // response so slow nodes do not serialize the entire system-table query.
    +        nodeSequences.add(nodeRunner.run(QueryPlus.wrap(nodeQuery), responseContext));
    +      }
    +      // Node scans have no cross-node ordering. Consume them in discovery order so a ready node can yield rows without
    +      // MergeSequence first initializing every other node sequence. The HTTP requests were all started above.
    +      return Sequences.concat(nodeSequences).flatMap(SystemTableQueryClient::rowsFromScanResult);
    +    });
    +    return sequenceAsIterable(rows, nodeSequenceCloser);
    +  }
    +
    +  private static Sequence<ScanResultValue> recoverNodeFailure(
    +      final Supplier<Sequence<ScanResultValue>> sequenceSupplier,
    +      final SystemTableNode node,
    +      final SystemTableDescriptor descriptor,
    +      @Nullable final Supplier<NodeQuerySequence> leaderRetrySupplier
    +  )
    +  {
    +    final Sequence<ScanResultValue> sequence;
    +    try {
    +      sequence = sequenceSupplier.get();
    +    }
    +    catch (Exception failure) {
    +      if (leaderRetrySupplier != null && isLeaderChangeFailure(failure)) {
    +        try {
    +          final NodeQuerySequence retry = leaderRetrySupplier.get();
    +          return recoveringSequence(retry, descriptor, null);
    +        }
    +        catch (Exception retryFailure) {
    +          return failureSequence(retryFailure, node, descriptor);
    +        }
    +      }
    +      return failureSequence(failure, node, descriptor);
    +    }
    +    return recoveringSequence(new NodeQuerySequence(node, sequence), descriptor, leaderRetrySupplier);
    +  }
    +
    +  private static Sequence<ScanResultValue> recoveringSequence(
    +      final NodeQuerySequence nodeQuerySequence,
    +      final SystemTableDescriptor descriptor,
    +      @Nullable final Supplier<NodeQuerySequence> leaderRetrySupplier
    +  )
    +  {
    +    return new BaseSequence<>(
    +        new BaseSequence.IteratorMaker<ScanResultValue, RecoveringNodeIterator>()
    +        {
    +          @Override
    +          public RecoveringNodeIterator make()
    +          {
    +            return new RecoveringNodeIterator(nodeQuerySequence, descriptor, leaderRetrySupplier);
    +          }
    +
    +          @Override
    +          public void cleanup(final RecoveringNodeIterator iterator)
    +          {
    +            CloseableUtils.closeAndWrapExceptions(iterator);
    +          }
    +        }
    +    );
    +  }
    +
    +  private static Sequence<ScanResultValue> failureSequence(
    +      final Exception failure,
    +      final SystemTableNode node,
    +      final SystemTableDescriptor descriptor
    +  )
    +  {
    +    if (!isNodeAvailabilityFailure(failure)) {
    +      throw propagate(failure);
    +    }
    +    return descriptor.getNodeFailureRow(
    +        node.getDiscoveryNode().getDruidNode(),
    +        node.getNodeRoles(),
    +        failure
    +    ).map(
    +        row -> Sequences.simple(
    +            List.of(
    +                new ScanResultValue(
    +                    null,
    +                    descriptor.getRowSignature().getColumnNames(),
    +                    List.of((Object) row)
    +                )
    +            )
    +        )
    +    ).orElseThrow(() -> QueryInterruptedException.wrapIfNeeded(failure));
    +  }
    +
    +  private static boolean isNodeAvailabilityFailure(final Throwable failure)
    +  {
    +    Throwable cause = failure;
    +    while (cause != null) {
    +      if (cause instanceof SocketException
    +          || cause instanceof UnknownHostException
    +          || cause instanceof EOFException
    +          || cause instanceof ClosedChannelException
    +          || cause instanceof ChannelException) {
    +        return true;
    +      }
    +      cause = cause.getCause();
    +    }
    +    return false;
    +  }
    +
    +  private static boolean isLeaderChangeFailure(final Throwable failure)
    +  {
    +    Throwable cause = failure;
    +    while (cause != null) {
    +      if (cause instanceof SystemTableNotLeaderException
    +          || cause instanceof QueryException
    +             && SystemTableNotLeaderException.class.getName().equals(((QueryException) cause).getErrorClass())) {
    +        return true;
    +      }
    +      cause = cause.getCause();
    +    }
    +    return false;
    +  }
    +
    +  private static RuntimeException propagate(final Exception failure)
    +  {
    +    if (failure instanceof RuntimeException runtimeException) {
    +      return runtimeException;
    +    } else if (failure instanceof java.util.concurrent.TimeoutException) {
    +      return new QueryTimeoutException(failure.getMessage());
    +    } else {
    +      if (failure instanceof InterruptedException) {
    +        Thread.currentThread().interrupt();
    +      }
    +      return QueryInterruptedException.wrapIfNeeded(failure);
    +    }
    +  }
    +
    +  private static Sequence<Object[]> rowsFromScanResult(final ScanResultValue scanResult)
    +  {
    +    return Sequences.simple((List<?>) scanResult.getEvents())
    +                    .map(event -> event instanceof Object[] ? (Object[]) event : ((List<?>) event).toArray());
    +  }
    +
    +  private static long getNodeFailTime(final Query<?> query)
    +  {
    +    final long existingFailTime = query.context().getLong(DirectDruidClient.QUERY_FAIL_TIME, -1L);
    +    if (existingFailTime > 0) {
    +      return existingFailTime;
    +    } else if (query.context().hasTimeout()) {
    +      return System.currentTimeMillis() + query.context().getTimeout();
    +    } else {
    +      return JodaUtils.MAX_INSTANT;
    +    }
    +  }
    +
    +  /**
    +   * Adapts a Druid {@link Sequence} to the lazy {@link Iterable} accepted by {@link InlineDataSource}.
    +   *
    +   * <p>The iterator owns the sequence yielder and closes it when the sequence is exhausted. This is important for
    +   * direct node clients because closing the yielder closes the underlying response stream and allows an early
    +   * terminating Broker query to cancel the node request.</p>
    +   */
    +  private static <T> Iterable<T> sequenceAsIterable(
    +      final Sequence<T> sequence,
    +      final NodeSequenceCloser nodeSequenceCloser
    +  )
    +  {
    +    return new Iterable<>()
    +    {
    +      private boolean iterated;
    +
    +      @Override
    +      public Iterator<T> iterator()
    +      {
    +        if (iterated) {
    +          throw new ISE("A native system table result sequence can only be consumed once");
    +        }
    +        iterated = true;
    +
    +        return new Iterator<>()
    +        {
    +          @Nullable
    +          private Yielder<T> yielder = Yielders.each(sequence);
    +          private boolean closed;
    +
    +          {
    +            nodeSequenceCloser.setYielder(yielder);
    +          }
    +
    +          @Override
    +          public boolean hasNext()
    +          {
    +            if (yielder == null) {
    +              return false;
    +            }
    +            if (yielder.isDone()) {
    +              close();
    +              return false;
    +            }
    +            return true;
    +          }
    +
    +          @Override
    +          public T next()
    +          {
    +            if (!hasNext()) {
    +              throw new NoSuchElementException();
    +            }
    +            final Yielder<T> currentYielder = Preconditions.checkNotNull(yielder);
    +            final T value = currentYielder.get();
    +            yielder = currentYielder.next(null);
    +            nodeSequenceCloser.setYielder(yielder);
    +            return value;
    +          }
    +
    +          private void close()
    +          {
    +            if (!closed) {
    +              closed = true;
    +              yielder = null;
    +              nodeSequenceCloser.close();
    +            }
    +          }
    +        };
    +      }
    +    };
    +  }
    +
    +  private static class NodeSequenceCloser implements Closeable
    +  {
    +    @Nullable
    +    private Yielder<?> yielder;
    +    private boolean closed;
    +
    +    synchronized void setYielder(final Yielder<?> newYielder)
    +    {
    +      if (closed) {
    +        CloseableUtils.closeAndWrapExceptions(newYielder);
    +      } else {
    +        yielder = newYielder;
    +      }
    +    }
    +
    +    @Override
    +    public synchronized void close()
    +    {
    +      if (!closed) {
    +        closed = true;
    +        final Yielder<?> currentYielder = yielder;
    +        yielder = null;
    +        CloseableUtils.closeAndWrapExceptions(currentYielder);
    +      }
    +    }
    +  }
    +
    +  private static class NodeSequencesCloser implements Closeable
    +  {
    +    private final List<NodeSequenceCloser> nodeSequenceClosers = new ArrayList<>();
    +    private final List<String> nodeQueryIds = new ArrayList<>();
    +    private final QueryScheduler queryScheduler;
    +    private boolean closed;
    +
    +    private NodeSequencesCloser(final QueryScheduler queryScheduler)
    +    {
    +      this.queryScheduler = queryScheduler;
    +    }
    +
    +    synchronized void addQueryId(final String nodeQueryId)
    +    {
    +      if (closed) {
    +        queryScheduler.cancelQuery(nodeQueryId);
    +      } else {
    +        nodeQueryIds.add(nodeQueryId);
    +      }
    +    }
    +
    +    synchronized void add(final NodeSequenceCloser nodeSequenceCloser)
    +    {
    +      if (closed) {
    +        CloseableUtils.closeAndWrapExceptions(nodeSequenceCloser);
    +      } else {
    +        nodeSequenceClosers.add(nodeSequenceCloser);
    +      }
    +    }
    +
    +    @Override
    +    public synchronized void close() throws IOException
    +    {
    +      if (!closed) {
    +        closed = true;
    +        try {
    +          CloseableUtils.closeAll(nodeSequenceClosers);
    +        }
    +        finally {
    +          nodeSequenceClosers.clear();
    +          nodeQueryIds.forEach(queryScheduler::cancelQuery);
    +          nodeQueryIds.clear();
    +        }
    +      }
    +    }
    +  }
    +
    +  private static class RecoveringNodeIterator implements Iterator<ScanResultValue>, Closeable
    +  {
    +    private final SystemTableDescriptor descriptor;
    +    @Nullable
    +    private final Supplier<NodeQuerySequence> leaderRetrySupplier;
    +
    +    private NodeQuerySequence nodeQuerySequence;
    +
    +    @Nullable
    +    private Yielder<ScanResultValue> yielder;
    +    @Nullable
    +    private ScanResultValue failureResult;
    +    private boolean started;
    +    private boolean finished;
    +    private boolean retriedLeader;
    +    private boolean emittedResult;
    +
    +    private RecoveringNodeIterator(
    +        final NodeQuerySequence nodeQuerySequence,
    +        final SystemTableDescriptor descriptor,
    +        @Nullable final Supplier<NodeQuerySequence> leaderRetrySupplier
    +    )
    +    {
    +      this.nodeQuerySequence = nodeQuerySequence;
    +      this.descriptor = descriptor;
    +      this.leaderRetrySupplier = leaderRetrySupplier;
    +    }
    +
    +    @Override
    +    public boolean hasNext()
    +    {
    +      if (failureResult != null) {
    +        return true;
    +      }
    +      if (finished) {
    +        return false;
    +      }
    +
    +      try {
    +        if (!started) {
    +          started = true;
    +          yielder = Yielders.each(nodeQuerySequence.sequence());
    +        }
    +        if (Preconditions.checkNotNull(yielder).isDone()) {
    +          finished = true;
    +          close();
    +          return false;
    +        }
    +        return true;
    +      }
    +      catch (Exception e) {
    +        return recoverOrThrow(e) ? hasNext() : true;
    +      }
    +    }
    +
    +    @Override
    +    public ScanResultValue next()
    +    {
    +      if (!hasNext()) {
    +        throw new NoSuchElementException();
    +      }
    +      if (failureResult != null) {
    +        final ScanResultValue result = failureResult;
    +        failureResult = null;
    +        finished = true;
    +        return result;
    +      }
    +
    +      final Yielder<ScanResultValue> currentYielder = Preconditions.checkNotNull(yielder);
    +      final ScanResultValue result;
    +      try {
    +        result = currentYielder.get();
    +        emittedResult = true;
    +      }
    +      catch (Exception e) {
    +        // Either the leader retry restarted the sequence or a failure row is pending; next() serves both.
    +        recoverOrThrow(e);
    +        return next();
    +      }
    +      try {
    +        yielder = currentYielder.next(null);
    +      }
    +      catch (Exception e) {
    +        recoverOrThrow(e);
    +      }
    +      return result;
    +    }
    +
    +    private boolean recoverOrThrow(final Exception originalFailure)
    +    {
    +      Exception failure = originalFailure;
    +      if (!emittedResult && !retriedLeader && leaderRetrySupplier != null && isLeaderChangeFailure(failure)) {
    +        retriedLeader = true;
    +        try {
    +          close();
    +          nodeQuerySequence = leaderRetrySupplier.get();
    +          started = false;
    +          finished = false;
    +          return true;
    +        }
    +        catch (Exception retryFailure) {
    +          failure = retryFailure;
    +        }
    +      }
    +      if (!isNodeAvailabilityFailure(failure)) {
    +        throw CloseableUtils.closeAndWrapInCatch(failure, this);
    +      }
    +      final Optional<Object[]> failureRow = descriptor.getNodeFailureRow(
    +          nodeQuerySequence.node().getDiscoveryNode().getDruidNode(),
    +          nodeQuerySequence.node().getNodeRoles(),
    +          failure
    +      );
    +      if (failureRow.isEmpty()) {
    +        throw CloseableUtils.closeAndWrapInCatch(failure, this);
    +      }
    +      try {
    +        close();
    +      }
    +      catch (RuntimeException closeException) {
    +        failure.addSuppressed(closeException);
    +      }
    +      failureResult = new ScanResultValue(
    +          null,
    +          descriptor.getRowSignature().getColumnNames(),
    +          List.of((Object) failureRow.get())
    +      );
    +      return false;
    +    }
    +
    +    @Override
    +    public void close()
    +    {
    +      final Yielder<ScanResultValue> currentYielder = yielder;
    +      yielder = null;
    +      CloseableUtils.closeAndWrapExceptions(currentYielder);
    +    }
    +  }
    +
    +  private record NodeQuerySequence(SystemTableNode node, Sequence<ScanResultValue> sequence)
    +  {
    +  }
    +
    +  @Nullable
    +  private static DimFilter nodeFilter(final SystemTableDataSource dataSource, final Query<?> query)
    +  {
    +    // Push into the remote scan only when this query directly owns the system table. A join or other composite filter
    +    // remains on the resolved Broker query, where the normal native query machinery can apply it with full datasource
    +    // semantics; it cannot safely be attributed to an individual remote leaf here.
    +    if (!dataSource.equals(query.getDataSource())) {
    +      return null;
    +    }
    +
    +    final List<DimFilter> filters = new ArrayList<>();
    +    if (query.getFilter() != null) {
    +      filters.add(query.getFilter());
    +    }
    +    if (query instanceof WindowOperatorQuery) {
    +      for (final OperatorFactory operator : ((WindowOperatorQuery) query).getLeafOperators()) {
    +        if (operator instanceof ScanOperatorFactory && ((ScanOperatorFactory) operator).getFilter() != null) {
    +          filters.add(((ScanOperatorFactory) operator).getFilter());
    +        }
    +      }
    +    }
    +    if (filters.isEmpty()) {
    +      return null;
    +    } else if (filters.size() == 1) {
    +      return filters.get(0);
    +    } else {
    +      return new AndDimFilter(filters);
    +    }
    +  }
    +
    +  private static VirtualColumns nodeVirtualColumns(
    +      final SystemTableDataSource dataSource,
    +      final Query<?> query,
    +      @Nullable final DimFilter nodeFilter
    +  )
    +  {
    +    if (!dataSource.equals(query.getDataSource()) || nodeFilter == null) {
    +      return VirtualColumns.EMPTY;
    +    }
    +
    +    final List<VirtualColumn> virtualColumns = new ArrayList<>(List.of(query.getVirtualColumns().getVirtualColumns()));
    +    if (query instanceof WindowOperatorQuery) {
    +      for (final OperatorFactory operator : ((WindowOperatorQuery) query).getLeafOperators()) {
    +        if (operator instanceof ScanOperatorFactory) {
    +          virtualColumns.addAll(List.of(((ScanOperatorFactory) operator).getVirtualColumns().getVirtualColumns()));

    [P1] Handle null window-leaf virtual columns

    Finding: WindowOperatorQuery intentionally stores null in ScanOperatorFactory when a leaf has no virtual columns. When the owning window query has a pushed-down filter, nodeFilter is non-null, so this expression dereferences that null value for any empty leaf and fails with an NPE before the node query executes.

    Suggestion: Treat null leaf virtual columns as empty before adding them, and add regression coverage for a filtered window query with a leaf that has no virtual columns.

    FrankChen021 FrankChen021 commented on Oct 10, 2026 12:54 UTC
    Reviewer

    🟡 Changes recommended

    SystemTableQueryClient can throw an NPE when constructing a filtered WindowOperatorQuery whose scan leaf has no virtual columns. Fix this before merging.

    Reviewed 90 of 90 changed files. The prior virtual-column shadowing issue is resolved.

    Validation: git diff --check passed; no tests or builds were run.

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 1 |
    | P2 | 0 |
    | P3 | 0 |
    | Total | 1 |

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

    FrankChen021 FrankChen021 commented on code on Oct 10, 2026 13:18 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/handler/SystemTableQueryClient.java:1
    @@ -0,0 +1,899 @@
    +/*
    + * 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.druid.server.system.handler;
    +
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.Iterables;
    +import com.google.inject.Inject;
    +import io.netty.channel.ChannelException;
    +import org.apache.druid.client.DirectDruidClient;
    +import org.apache.druid.client.DirectDruidClientFactory;
    +import org.apache.druid.client.DruidServer;
    +import org.apache.druid.discovery.DiscoveryDruidNode;
    +import org.apache.druid.guice.annotations.Self;
    +import org.apache.druid.java.util.common.ISE;
    +import org.apache.druid.java.util.common.JodaUtils;
    +import org.apache.druid.java.util.common.guava.BaseSequence;
    +import org.apache.druid.java.util.common.guava.LazySequence;
    +import org.apache.druid.java.util.common.guava.Sequence;
    +import org.apache.druid.java.util.common.guava.Sequences;
    +import org.apache.druid.java.util.common.guava.Yielder;
    +import org.apache.druid.java.util.common.guava.Yielders;
    +import org.apache.druid.query.BaseQuery;
    +import org.apache.druid.query.DataSource;
    +import org.apache.druid.query.Druids;
    +import org.apache.druid.query.InlineDataSource;
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.QueryContexts;
    +import org.apache.druid.query.QueryDataSource;
    +import org.apache.druid.query.QueryException;
    +import org.apache.druid.query.QueryInterruptedException;
    +import org.apache.druid.query.QueryPlus;
    +import org.apache.druid.query.QueryRunner;
    +import org.apache.druid.query.QuerySegmentWalker;
    +import org.apache.druid.query.QueryTimeoutException;
    +import org.apache.druid.query.SystemTableDataSource;
    +import org.apache.druid.query.context.ResponseContext;
    +import org.apache.druid.query.filter.AndDimFilter;
    +import org.apache.druid.query.filter.DimFilter;
    +import org.apache.druid.query.operator.OperatorFactory;
    +import org.apache.druid.query.operator.ScanOperatorFactory;
    +import org.apache.druid.query.operator.WindowOperatorQuery;
    +import org.apache.druid.query.scan.ScanQuery;
    +import org.apache.druid.query.scan.ScanResultValue;
    +import org.apache.druid.segment.VirtualColumn;
    +import org.apache.druid.segment.VirtualColumns;
    +import org.apache.druid.server.DataSourceQueryHandler;
    +import org.apache.druid.server.DruidNode;
    +import org.apache.druid.server.QueryScheduler;
    +import org.apache.druid.server.coordination.ServerType;
    +import org.apache.druid.server.security.AuthenticationResult;
    +import org.apache.druid.server.security.AuthorizerMapper;
    +import org.apache.druid.server.security.Escalator;
    +import org.apache.druid.server.system.SystemTableNotLeaderException;
    +import org.apache.druid.server.system.table.SystemTableDescriptor;
    +import org.apache.druid.server.system.table.SystemTableRoutingMode;
    +import org.apache.druid.utils.CloseableUtils;
    +
    +import javax.annotation.Nullable;
    +import java.io.Closeable;
    +import java.io.EOFException;
    +import java.io.IOException;
    +import java.net.SocketException;
    +import java.net.UnknownHostException;
    +import java.nio.channels.ClosedChannelException;
    +import java.util.ArrayList;
    +import java.util.Iterator;
    +import java.util.LinkedHashMap;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.NoSuchElementException;
    +import java.util.Optional;
    +import java.util.UUID;
    +import java.util.function.Supplier;
    +
    +/**
    + * Recursively replaces native system-table datasources with authorized inline rows fetched from nodes, then
    + * executes the rebuilt query through the Broker's normal native-query walker.
    + */
    +public class SystemTableQueryClient implements DataSourceQueryHandler
    +{
    +  private static final String SYSTEM_TABLE_TIER = "_system";
    +
    +  private final SystemTableNodeLocator nodeLocator;
    +  private final DirectDruidClientFactory directDruidClientFactory;
    +  private final QueryScheduler queryScheduler;
    +  private final QuerySegmentWalker querySegmentWalker;
    +  private final Map<String, SystemTableDescriptor> tableDescriptors;
    +  private final AuthorizerMapper authorizerMapper;
    +  private final SystemTableQueryHandler localQueryHandler;
    +  private final AuthenticationResult escalatedAuthenticationResult;
    +  private final DruidNode selfNode;
    +
    +  @Inject
    +  public SystemTableQueryClient(
    +      final SystemTableNodeLocator nodeLocator,
    +      final DirectDruidClientFactory directDruidClientFactory,
    +      final QueryScheduler queryScheduler,
    +      final QuerySegmentWalker querySegmentWalker,
    +      final Map<String, SystemTableDescriptor> tableDescriptors,
    +      final AuthorizerMapper authorizerMapper,
    +      final SystemTableQueryHandler localQueryHandler,
    +      final Escalator escalator,
    +      @Self final DruidNode selfNode
    +  )
    +  {
    +    this.nodeLocator = nodeLocator;
    +    this.directDruidClientFactory = directDruidClientFactory;
    +    this.queryScheduler = queryScheduler;
    +    this.querySegmentWalker = querySegmentWalker;
    +    this.tableDescriptors = tableDescriptors;
    +    this.authorizerMapper = authorizerMapper;
    +    this.localQueryHandler = localQueryHandler;
    +    this.escalatedAuthenticationResult = escalator.createEscalatedAuthenticationResult();
    +    this.selfNode = selfNode;
    +  }
    +
    +  @Override
    +  public <T> QueryRunner<T> createRunner(
    +      final Query<T> query,
    +      final AuthenticationResult authenticationResult,
    +      final boolean executeLocally
    +  )
    +  {
    +    return (queryPlus, responseContext) -> {
    +      final NodeSequencesCloser nodeSequencesCloser = new NodeSequencesCloser(queryScheduler);
    +      try {
    +        final DataSource resolvedDataSource = resolveDataSource(
    +            query.getDataSource(),
    +            query,
    +            authenticationResult,
    +            responseContext,
    +            nodeSequencesCloser
    +        );
    +        final Query<T> resolvedQuery = query.withDataSource(resolvedDataSource).withOverriddenContext(
    +            Map.of(QueryContexts.QUERY_RESOURCE_ID, UUID.randomUUID().toString())
    +        );
    +        final QueryRunner<T> queryRunner = querySegmentWalker.getQueryRunnerForIntervals(
    +            resolvedQuery,
    +            resolvedQuery.getIntervals()
    +        );
    +        return Sequences.withBaggage(
    +            queryRunner.run(queryPlus.withQuery(resolvedQuery), responseContext),
    +            nodeSequencesCloser
    +        );
    +      }
    +      catch (Throwable t) {
    +        throw CloseableUtils.closeAndWrapInCatch(t, nodeSequencesCloser);
    +      }
    +    };
    +  }
    +
    +  private DataSource resolveDataSource(
    +      final DataSource dataSource,
    +      final Query<?> owningQuery,
    +      final AuthenticationResult authenticationResult,
    +      final ResponseContext responseContext,
    +      final NodeSequencesCloser nodeSequencesCloser
    +  )
    +  {
    +    if (dataSource instanceof SystemTableDataSource systemTableDataSource) {
    +      return resolveSystemTableDataSource(
    +          systemTableDataSource,
    +          owningQuery,
    +          authenticationResult,
    +          responseContext,
    +          nodeSequencesCloser
    +      );
    +    }
    +
    +    final Query<?> childOwningQuery = dataSource instanceof QueryDataSource queryDataSource
    +                                      ? queryDataSource.getQuery()
    +                                      : owningQuery;
    +    final List<DataSource> resolvedChildren = new ArrayList<>();
    +    for (final DataSource child : dataSource.getChildren()) {
    +      resolvedChildren.add(
    +          resolveDataSource(
    +              child,
    +              childOwningQuery,
    +              authenticationResult,
    +              responseContext,
    +              nodeSequencesCloser
    +          )
    +      );
    +    }
    +    return dataSource.withChildren(resolvedChildren);
    +  }
    +
    +  private InlineDataSource resolveSystemTableDataSource(
    +      final SystemTableDataSource dataSource,
    +      final Query<?> owningQuery,
    +      final AuthenticationResult authenticationResult,
    +      final ResponseContext responseContext,
    +      final NodeSequencesCloser nodeSequencesCloser
    +  )
    +  {
    +    final SystemTableDescriptor descriptor = tableDescriptors.get(dataSource.getTable());
    +    if (descriptor == null) {
    +      throw new ISE("No routing descriptor is registered for system table[%s]", dataSource.getTable());
    +    }
    +
    +    final ScanQuery nodeQuery = makeNodeQuery(dataSource, descriptor, owningQuery);
    +    final List<QueryRunner<ScanResultValue>> nodeRunners = makeNodeRunners(
    +        nodeQuery,
    +        descriptor,
    +        nodeSequencesCloser
    +    );
    +    if (nodeRunners.isEmpty() && !descriptor.isEmptyDiscoveryAllowed()) {
    +      throw new ISE("No node is available to serve system table[%s]", dataSource.getTable());
    +    }
    +
    +    /*
    +     * Keep the scan result transport lazy. The node response is a Sequence, so this lets the local query
    +     * runner consume and process rows while the HTTP response is still arriving instead of materializing every
    +     * node row in two Broker-side lists. The scan transport is intentionally kept behind this adapter so a
    +     * future node-side aggregation mode can use a different result adapter without changing routing or
    +     * authorization orchestration here.
    +     */
    +    final NodeSequenceCloser nodeSequenceCloser = new NodeSequenceCloser();
    +    nodeSequencesCloser.add(nodeSequenceCloser);
    +    final Iterable<Object[]> nodeRows = scanNodeRows(
    +        nodeRunners,
    +        nodeQuery,
    +        responseContext,
    +        nodeSequenceCloser
    +    );
    +    final Iterable<Object[]> authorizedRows = descriptor.getRowAuthorizer().filterAuthorizedRows(
    +        nodeRows,
    +        authenticationResult,
    +        authorizerMapper
    +    );
    +    final Iterable<Object[]> queryRows = requiresMaterializedRows(owningQuery)
    +                                         ? materializeRows(authorizedRows)
    +                                         : authorizedRows;
    +    return InlineDataSource.fromIterable(queryRows, descriptor.getRowSignature());
    +  }
    +
    +  private ScanQuery makeNodeQuery(
    +      final SystemTableDataSource dataSource,
    +      final SystemTableDescriptor descriptor,
    +      final Query<?> owningQuery
    +  )
    +  {
    +    final Map<String, Object> nodeContext = new LinkedHashMap<>(owningQuery.getContext());
    +    final DimFilter nodeFilter = nodeFilter(dataSource, owningQuery);
    +    nodeContext.put(DirectDruidClient.QUERY_FAIL_TIME, getNodeFailTime(owningQuery));
    +    // The node endpoint always returns plain ScanResultValue objects. bySegment belongs to the user-facing query and
    +    // would make DirectDruidClient deserialize this private transport using an incompatible result type.
    +    nodeContext.put(QueryContexts.BY_SEGMENT_KEY, false);
    +    return Druids.newScanQueryBuilder()
    +                 .dataSource(dataSource)
    +                 .eternityInterval()
    +                 .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
    +                 .limit(Long.MAX_VALUE)
    +                 .filters(nodeFilter)
    +                 .virtualColumns(nodeVirtualColumns(dataSource, owningQuery, nodeFilter))
    +                 .columns(descriptor.getRowSignature())
    +                 .context(nodeContext)
    +                 .build();
    +  }
    +
    +  private List<QueryRunner<ScanResultValue>> makeNodeRunners(
    +      final ScanQuery nodeQuery,
    +      final SystemTableDescriptor descriptor,
    +      final NodeSequencesCloser nodeSequencesCloser
    +  )
    +  {
    +    final List<QueryRunner<ScanResultValue>> nodeRunners = new ArrayList<>();
    +    for (final SystemTableNode node : nodeLocator.locate(descriptor, nodeQuery)) {
    +      nodeRunners.add(
    +          (queryPlus, responseContext) -> recoverNodeFailure(
    +              () -> runNodeQuery(nodeQuery, node, nodeSequencesCloser, queryPlus, responseContext),
    +              node,
    +              descriptor,
    +              descriptor.getRoutingMode() == SystemTableRoutingMode.LEADER_ONLY
    +              ? () -> {
    +                final SystemTableNode currentLeader = Iterables.getOnlyElement(
    +                    nodeLocator.locate(descriptor, nodeQuery)
    +                );
    +                return new NodeQuerySequence(
    +                    currentLeader,
    +                    runNodeQuery(nodeQuery, currentLeader, nodeSequencesCloser, queryPlus, responseContext)
    +                );
    +              }
    +              : null
    +          )
    +      );
    +    }
    +    return nodeRunners;
    +  }
    +
    +  private Sequence<ScanResultValue> runNodeQuery(
    +      final ScanQuery nodeQuery,
    +      final SystemTableNode node,
    +      final NodeSequencesCloser nodeSequencesCloser,
    +      final QueryPlus<ScanResultValue> queryPlus,
    +      final ResponseContext responseContext
    +  )
    +  {
    +    final String nodeResourceId = UUID.randomUUID().toString();
    +    final String nodeQueryId = SystemTableDataSource.NODE_QUERY_ID_PREFIX + UUID.randomUUID();
    +    final ScanQuery subNativeQuery = nodeQuery.withOverriddenContext(
    +        Map.of(
    +            BaseQuery.QUERY_ID,
    +            nodeQueryId,
    +            QueryContexts.QUERY_RESOURCE_ID,
    +            nodeResourceId
    +        )
    +    );
    +    final QueryRunner<ScanResultValue> nodeRunner;
    +    if (SystemTableNodeLocator.sameServer(
    +        selfNode.getUriToUse(),
    +        node.getDiscoveryNode().getDruidNode().getUriToUse()
    +    )) {
    +      // Invoke the raw local handler rather than the Broker handler. This avoids an HTTP request back to this
    +      // Broker and, more importantly, prevents the local request from entering node fanout recursively.
    +      nodeRunner = localQueryHandler.createRunner(subNativeQuery, escalatedAuthenticationResult, true);
    +    } else {
    +      nodeRunner = directDruidClientFactory.makeDirectClient(toDruidServer(node.getDiscoveryNode()));
    +      nodeSequencesCloser.addQueryId(nodeQueryId);
    +    }
    +    return nodeRunner.run(queryPlus.withQuery(subNativeQuery), responseContext);
    +  }
    +
    +  /**
    +   * Window operators consume a {@code RowsAndColumns} view of the segment. The current row-based segment can only
    +   * provide that view when its rows are list-backed, so preserve the existing materialized path for those queries.
    +   */
    +  private static boolean requiresMaterializedRows(final Query<?> query)
    +  {
    +    return query instanceof WindowOperatorQuery;
    +  }
    +
    +  /**
    +   * Eagerly consumes the lazy, single-pass node response into an {@link ArrayList} without changing its rows.
    +   *
    +   * <p>This representation change is required by {@link org.apache.druid.segment.InlineSegmentWrangler}: an inline
    +   * datasource backed specifically by an {@code ArrayList} becomes an {@link org.apache.druid.segment.ArrayListSegment},
    +   * which can provide the {@code RowsAndColumns} view required by window operators. Other query types retain the lazy
    +   * iterable so the Broker can process rows while node responses are still arriving.</p>
    +   */
    +  private static Iterable<Object[]> materializeRows(final Iterable<Object[]> rows)
    +  {
    +    final List<Object[]> materializedRows = new ArrayList<>();
    +    rows.forEach(materializedRows::add);
    +    return materializedRows;
    +  }
    +
    +  /**
    +   * Creates a lazy, single-pass view of the rows returned by the node scan runners.
    +   *
    +   * <p>The view is single-pass because a node response is backed by a live HTTP stream. The normal native query
    +   * path consumes an {@link InlineDataSource} once per query. Re-iterating would otherwise issue duplicate node
    +   * requests or retain all rows to support replay.</p>
    +   */
    +  static Iterable<Object[]> scanNodeRows(
    +      final List<QueryRunner<ScanResultValue>> nodeRunners,
    +      final Query<ScanResultValue> nodeQuery,
    +      final ResponseContext responseContext
    +  )
    +  {
    +    return scanNodeRows(
    +        nodeRunners,
    +        nodeQuery,
    +        responseContext,
    +        new NodeSequenceCloser()
    +    );
    +  }
    +
    +  private static Iterable<Object[]> scanNodeRows(
    +      final List<QueryRunner<ScanResultValue>> nodeRunners,
    +      final Query<ScanResultValue> nodeQuery,
    +      final ResponseContext responseContext,
    +      final NodeSequenceCloser nodeSequenceCloser
    +  )
    +  {
    +    final Sequence<Object[]> rows = new LazySequence<>(() -> {
    +      final List<Sequence<ScanResultValue>> nodeSequences = new ArrayList<>();
    +      for (final QueryRunner<ScanResultValue> nodeRunner : nodeRunners) {
    +        // DirectDruidClient.run starts its asynchronous HTTP request. Start every request before waiting for any
    +        // response so slow nodes do not serialize the entire system-table query.
    +        nodeSequences.add(nodeRunner.run(QueryPlus.wrap(nodeQuery), responseContext));
    +      }
    +      // Node scans have no cross-node ordering. Consume them in discovery order so a ready node can yield rows without
    +      // MergeSequence first initializing every other node sequence. The HTTP requests were all started above.
    +      return Sequences.concat(nodeSequences).flatMap(SystemTableQueryClient::rowsFromScanResult);
    +    });
    +    return sequenceAsIterable(rows, nodeSequenceCloser);
    +  }
    +
    +  private static Sequence<ScanResultValue> recoverNodeFailure(
    +      final Supplier<Sequence<ScanResultValue>> sequenceSupplier,
    +      final SystemTableNode node,
    +      final SystemTableDescriptor descriptor,
    +      @Nullable final Supplier<NodeQuerySequence> leaderRetrySupplier
    +  )
    +  {
    +    final Sequence<ScanResultValue> sequence;
    +    try {
    +      sequence = sequenceSupplier.get();
    +    }
    +    catch (Exception failure) {
    +      if (leaderRetrySupplier != null && isLeaderChangeFailure(failure)) {
    +        try {
    +          final NodeQuerySequence retry = leaderRetrySupplier.get();
    +          return recoveringSequence(retry, descriptor, null);
    +        }
    +        catch (Exception retryFailure) {
    +          return failureSequence(retryFailure, node, descriptor);
    +        }
    +      }
    +      return failureSequence(failure, node, descriptor);
    +    }
    +    return recoveringSequence(new NodeQuerySequence(node, sequence), descriptor, leaderRetrySupplier);
    +  }
    +
    +  private static Sequence<ScanResultValue> recoveringSequence(
    +      final NodeQuerySequence nodeQuerySequence,
    +      final SystemTableDescriptor descriptor,
    +      @Nullable final Supplier<NodeQuerySequence> leaderRetrySupplier
    +  )
    +  {
    +    return new BaseSequence<>(
    +        new BaseSequence.IteratorMaker<ScanResultValue, RecoveringNodeIterator>()
    +        {
    +          @Override
    +          public RecoveringNodeIterator make()
    +          {
    +            return new RecoveringNodeIterator(nodeQuerySequence, descriptor, leaderRetrySupplier);
    +          }
    +
    +          @Override
    +          public void cleanup(final RecoveringNodeIterator iterator)
    +          {
    +            CloseableUtils.closeAndWrapExceptions(iterator);
    +          }
    +        }
    +    );
    +  }
    +
    +  private static Sequence<ScanResultValue> failureSequence(
    +      final Exception failure,
    +      final SystemTableNode node,
    +      final SystemTableDescriptor descriptor
    +  )
    +  {
    +    if (!isNodeAvailabilityFailure(failure)) {
    +      throw propagate(failure);
    +    }
    +    return descriptor.getNodeFailureRow(
    +        node.getDiscoveryNode().getDruidNode(),
    +        node.getNodeRoles(),
    +        failure
    +    ).map(
    +        row -> Sequences.simple(
    +            List.of(
    +                new ScanResultValue(
    +                    null,
    +                    descriptor.getRowSignature().getColumnNames(),
    +                    List.of((Object) row)
    +                )
    +            )
    +        )
    +    ).orElseThrow(() -> QueryInterruptedException.wrapIfNeeded(failure));
    +  }
    +
    +  private static boolean isNodeAvailabilityFailure(final Throwable failure)
    +  {
    +    Throwable cause = failure;
    +    while (cause != null) {
    +      if (cause instanceof SocketException
    +          || cause instanceof UnknownHostException
    +          || cause instanceof EOFException
    +          || cause instanceof ClosedChannelException
    +          || cause instanceof ChannelException) {
    +        return true;
    +      }
    +      cause = cause.getCause();
    +    }
    +    return false;
    +  }
    +
    +  private static boolean isLeaderChangeFailure(final Throwable failure)
    +  {
    +    Throwable cause = failure;
    +    while (cause != null) {
    +      if (cause instanceof SystemTableNotLeaderException
    +          || cause instanceof QueryException
    +             && SystemTableNotLeaderException.class.getName().equals(((QueryException) cause).getErrorClass())) {
    +        return true;
    +      }
    +      cause = cause.getCause();
    +    }
    +    return false;
    +  }
    +
    +  private static RuntimeException propagate(final Exception failure)
    +  {
    +    if (failure instanceof RuntimeException runtimeException) {
    +      return runtimeException;
    +    } else if (failure instanceof java.util.concurrent.TimeoutException) {
    +      return new QueryTimeoutException(failure.getMessage());
    +    } else {
    +      if (failure instanceof InterruptedException) {
    +        Thread.currentThread().interrupt();
    +      }
    +      return QueryInterruptedException.wrapIfNeeded(failure);
    +    }
    +  }
    +
    +  private static Sequence<Object[]> rowsFromScanResult(final ScanResultValue scanResult)
    +  {
    +    return Sequences.simple((List<?>) scanResult.getEvents())
    +                    .map(event -> event instanceof Object[] ? (Object[]) event : ((List<?>) event).toArray());
    +  }
    +
    +  private static long getNodeFailTime(final Query<?> query)
    +  {
    +    final long existingFailTime = query.context().getLong(DirectDruidClient.QUERY_FAIL_TIME, -1L);
    +    if (existingFailTime > 0) {
    +      return existingFailTime;
    +    } else if (query.context().hasTimeout()) {
    +      return System.currentTimeMillis() + query.context().getTimeout();
    +    } else {
    +      return JodaUtils.MAX_INSTANT;
    +    }
    +  }
    +
    +  /**
    +   * Adapts a Druid {@link Sequence} to the lazy {@link Iterable} accepted by {@link InlineDataSource}.
    +   *
    +   * <p>The iterator owns the sequence yielder and closes it when the sequence is exhausted. This is important for
    +   * direct node clients because closing the yielder closes the underlying response stream and allows an early
    +   * terminating Broker query to cancel the node request.</p>
    +   */
    +  private static <T> Iterable<T> sequenceAsIterable(
    +      final Sequence<T> sequence,
    +      final NodeSequenceCloser nodeSequenceCloser
    +  )
    +  {
    +    return new Iterable<>()
    +    {
    +      private boolean iterated;
    +
    +      @Override
    +      public Iterator<T> iterator()
    +      {
    +        if (iterated) {
    +          throw new ISE("A native system table result sequence can only be consumed once");
    +        }
    +        iterated = true;
    +
    +        return new Iterator<>()
    +        {
    +          @Nullable
    +          private Yielder<T> yielder = Yielders.each(sequence);
    +          private boolean closed;
    +
    +          {
    +            nodeSequenceCloser.setYielder(yielder);
    +          }
    +
    +          @Override
    +          public boolean hasNext()
    +          {
    +            if (yielder == null) {
    +              return false;
    +            }
    +            if (yielder.isDone()) {
    +              close();
    +              return false;
    +            }
    +            return true;
    +          }
    +
    +          @Override
    +          public T next()
    +          {
    +            if (!hasNext()) {
    +              throw new NoSuchElementException();
    +            }
    +            final Yielder<T> currentYielder = Preconditions.checkNotNull(yielder);
    +            final T value = currentYielder.get();
    +            yielder = currentYielder.next(null);
    +            nodeSequenceCloser.setYielder(yielder);
    +            return value;
    +          }
    +
    +          private void close()
    +          {
    +            if (!closed) {
    +              closed = true;
    +              yielder = null;
    +              nodeSequenceCloser.close();
    +            }
    +          }
    +        };
    +      }
    +    };
    +  }
    +
    +  private static class NodeSequenceCloser implements Closeable
    +  {
    +    @Nullable
    +    private Yielder<?> yielder;
    +    private boolean closed;
    +
    +    synchronized void setYielder(final Yielder<?> newYielder)
    +    {
    +      if (closed) {
    +        CloseableUtils.closeAndWrapExceptions(newYielder);
    +      } else {
    +        yielder = newYielder;
    +      }
    +    }
    +
    +    @Override
    +    public synchronized void close()
    +    {
    +      if (!closed) {
    +        closed = true;
    +        final Yielder<?> currentYielder = yielder;
    +        yielder = null;
    +        CloseableUtils.closeAndWrapExceptions(currentYielder);
    +      }
    +    }
    +  }
    +
    +  private static class NodeSequencesCloser implements Closeable
    +  {
    +    private final List<NodeSequenceCloser> nodeSequenceClosers = new ArrayList<>();
    +    private final List<String> nodeQueryIds = new ArrayList<>();
    +    private final QueryScheduler queryScheduler;
    +    private boolean closed;
    +
    +    private NodeSequencesCloser(final QueryScheduler queryScheduler)
    +    {
    +      this.queryScheduler = queryScheduler;
    +    }
    +
    +    synchronized void addQueryId(final String nodeQueryId)
    +    {
    +      if (closed) {
    +        queryScheduler.cancelQuery(nodeQueryId);
    +      } else {
    +        nodeQueryIds.add(nodeQueryId);
    +      }
    +    }
    +
    +    synchronized void add(final NodeSequenceCloser nodeSequenceCloser)
    +    {
    +      if (closed) {
    +        CloseableUtils.closeAndWrapExceptions(nodeSequenceCloser);
    +      } else {
    +        nodeSequenceClosers.add(nodeSequenceCloser);
    +      }
    +    }
    +
    +    @Override
    +    public synchronized void close() throws IOException
    +    {
    +      if (!closed) {
    +        closed = true;
    +        try {
    +          CloseableUtils.closeAll(nodeSequenceClosers);
    +        }
    +        finally {
    +          nodeSequenceClosers.clear();
    +          nodeQueryIds.forEach(queryScheduler::cancelQuery);
    +          nodeQueryIds.clear();
    +        }
    +      }
    +    }
    +  }
    +
    +  private static class RecoveringNodeIterator implements Iterator<ScanResultValue>, Closeable
    +  {
    +    private final SystemTableDescriptor descriptor;
    +    @Nullable
    +    private final Supplier<NodeQuerySequence> leaderRetrySupplier;
    +
    +    private NodeQuerySequence nodeQuerySequence;
    +
    +    @Nullable
    +    private Yielder<ScanResultValue> yielder;
    +    @Nullable
    +    private ScanResultValue failureResult;
    +    private boolean started;
    +    private boolean finished;
    +    private boolean retriedLeader;
    +    private boolean emittedResult;
    +
    +    private RecoveringNodeIterator(
    +        final NodeQuerySequence nodeQuerySequence,
    +        final SystemTableDescriptor descriptor,
    +        @Nullable final Supplier<NodeQuerySequence> leaderRetrySupplier
    +    )
    +    {
    +      this.nodeQuerySequence = nodeQuerySequence;
    +      this.descriptor = descriptor;
    +      this.leaderRetrySupplier = leaderRetrySupplier;
    +    }
    +
    +    @Override
    +    public boolean hasNext()
    +    {
    +      if (failureResult != null) {
    +        return true;
    +      }
    +      if (finished) {
    +        return false;
    +      }
    +
    +      try {
    +        if (!started) {
    +          started = true;
    +          yielder = Yielders.each(nodeQuerySequence.sequence());
    +        }
    +        if (Preconditions.checkNotNull(yielder).isDone()) {
    +          finished = true;
    +          close();
    +          return false;
    +        }
    +        return true;
    +      }
    +      catch (Exception e) {
    +        return recoverOrThrow(e) ? hasNext() : true;
    +      }
    +    }
    +
    +    @Override
    +    public ScanResultValue next()
    +    {
    +      if (!hasNext()) {
    +        throw new NoSuchElementException();
    +      }
    +      if (failureResult != null) {
    +        final ScanResultValue result = failureResult;
    +        failureResult = null;
    +        finished = true;
    +        return result;
    +      }
    +
    +      final Yielder<ScanResultValue> currentYielder = Preconditions.checkNotNull(yielder);
    +      final ScanResultValue result;
    +      try {
    +        result = currentYielder.get();
    +        emittedResult = true;
    +      }
    +      catch (Exception e) {
    +        // Either the leader retry restarted the sequence or a failure row is pending; next() serves both.
    +        recoverOrThrow(e);
    +        return next();
    +      }
    +      try {
    +        yielder = currentYielder.next(null);
    +      }
    +      catch (Exception e) {
    +        recoverOrThrow(e);
    +      }
    +      return result;
    +    }
    +
    +    private boolean recoverOrThrow(final Exception originalFailure)
    +    {
    +      Exception failure = originalFailure;
    +      if (!emittedResult && !retriedLeader && leaderRetrySupplier != null && isLeaderChangeFailure(failure)) {
    +        retriedLeader = true;
    +        try {
    +          close();
    +          nodeQuerySequence = leaderRetrySupplier.get();
    +          started = false;
    +          finished = false;
    +          return true;
    +        }
    +        catch (Exception retryFailure) {
    +          failure = retryFailure;
    +        }
    +      }
    +      if (!isNodeAvailabilityFailure(failure)) {
    +        throw CloseableUtils.closeAndWrapInCatch(failure, this);
    +      }
    +      final Optional<Object[]> failureRow = descriptor.getNodeFailureRow(
    +          nodeQuerySequence.node().getDiscoveryNode().getDruidNode(),
    +          nodeQuerySequence.node().getNodeRoles(),
    +          failure
    +      );
    +      if (failureRow.isEmpty()) {
    +        throw CloseableUtils.closeAndWrapInCatch(failure, this);
    +      }
    +      try {
    +        close();
    +      }
    +      catch (RuntimeException closeException) {
    +        failure.addSuppressed(closeException);
    +      }
    +      failureResult = new ScanResultValue(
    +          null,
    +          descriptor.getRowSignature().getColumnNames(),
    +          List.of((Object) failureRow.get())
    +      );
    +      return false;
    +    }
    +
    +    @Override
    +    public void close()
    +    {
    +      final Yielder<ScanResultValue> currentYielder = yielder;
    +      yielder = null;
    +      CloseableUtils.closeAndWrapExceptions(currentYielder);
    +    }
    +  }
    +
    +  private record NodeQuerySequence(SystemTableNode node, Sequence<ScanResultValue> sequence)
    +  {
    +  }
    +
    +  @Nullable
    +  private static DimFilter nodeFilter(final SystemTableDataSource dataSource, final Query<?> query)
    +  {
    +    // Push into the remote scan only when this query directly owns the system table. A join or other composite filter
    +    // remains on the resolved Broker query, where the normal native query machinery can apply it with full datasource
    +    // semantics; it cannot safely be attributed to an individual remote leaf here.
    +    if (!dataSource.equals(query.getDataSource())) {
    +      return null;
    +    }
    +
    +    final List<DimFilter> filters = new ArrayList<>();
    +    if (query.getFilter() != null) {
    +      filters.add(query.getFilter());
    +    }
    +    if (query instanceof WindowOperatorQuery) {
    +      for (final OperatorFactory operator : ((WindowOperatorQuery) query).getLeafOperators()) {
    +        if (operator instanceof ScanOperatorFactory && ((ScanOperatorFactory) operator).getFilter() != null) {
    +          filters.add(((ScanOperatorFactory) operator).getFilter());
    +        }
    +      }
    +    }
    +    if (filters.isEmpty()) {
    +      return null;
    +    } else if (filters.size() == 1) {
    +      return filters.get(0);
    +    } else {
    +      return new AndDimFilter(filters);
    +    }
    +  }
    +
    +  private static VirtualColumns nodeVirtualColumns(
    +      final SystemTableDataSource dataSource,
    +      final Query<?> query,
    +      @Nullable final DimFilter nodeFilter
    +  )
    +  {
    +    if (!dataSource.equals(query.getDataSource()) || nodeFilter == null) {
    +      return VirtualColumns.EMPTY;
    +    }
    +
    +    final List<VirtualColumn> virtualColumns = new ArrayList<>(List.of(query.getVirtualColumns().getVirtualColumns()));
    +    if (query instanceof WindowOperatorQuery) {
    +      for (final OperatorFactory operator : ((WindowOperatorQuery) query).getLeafOperators()) {
    +        if (operator instanceof ScanOperatorFactory) {
    +          virtualColumns.addAll(List.of(((ScanOperatorFactory) operator).getVirtualColumns().getVirtualColumns()));

    Fixed in d4ddcf9e31.

    Reproduced first: the new SystemTableQueryClientTest#testWindowLeafFilterWithoutVirtualColumns builds the window query the way production does (a filtered Scan subquery with leafOperators left for the WindowOperatorQuery constructor, which stores null virtual columns) and failed with the reported NPE at nodeVirtualColumns. nodeVirtualColumns now skips leaves whose virtual columns are null; the test asserts the filter is still pushed to the node scan with no virtual columns.

    This path is reachable through a native windowOperator query without leafOperators; SQL planning does not produce it today. While adding SQL-level coverage (NativeSysServerPropertiesQueryTest#testNativeWindowFunction, both planners), a separate DECOUPLED bug surfaced: the window query is planned directly over filter(systemTable) and failed with Segment [filtered->ArrayListSegment] cannot shapeshift, because FilteredSegment never provided a CloseableShapeshifter. Fixed generally in 24dee021a5: FilteredSegment now returns CursorFactoryRowsAndColumns over its filtered cursor factory, the same way HashJoinSegment does, with a new FilteredSegmentTest. The window, DECOUPLED and Drill window SQL suites still pass.

    FrankChen021 FrankChen021 commented on Oct 11, 2026 12:45 UTC
    Reviewer

    🟢 Approval recommended

    No actionable issues found in the current head. The updated changes address the prior window-query null virtual-column failure and add the filtered-segment RowsAndColumns bridge required by native window queries.

    Reviewed 92 of 92 changed files, starting with the incremental five-file delta and then covering the complete current PR diff and surrounding native system-table, window-query, filtered-segment, and SQL planning code.

    Validation: git diff --check 631f05de5d1d05edfbbab3adc8dbbb99745678ee..HEAD -- passed. No broad tests or builds were run per review scope.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Oct 13, 2026 13:51 UTC
    Reviewer

    🟢 Approval recommended

    No actionable P0–P3 defects were found in this static review. The current changes remain mergeable across SQL planning/schema, native system-table execution, Broker/Router routing, authorization, role wiring, documentation, and tests.

    Reviewed 95 of 95 changed files, including the full merge-base diff and incremental changes since 24dee021a549d0c46e3919fbdceb62d8facda740.

    No builds, tests, installs, formatters, or long validation checks were run.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Oct 14, 2026 14:03 UTC
    Reviewer

    🟡 Changes recommended

    Native system-table handler dispatch bypasses standard timeout normalization, allowing configured timeout limits to be ignored. Fix this before merging.

    Reviewed 95 of 95 changed files. Started with the incremental diff from bc4976c9e40ff3d306b9302b390ce914e7630691, then reconciled the full current diff against merge base 7c89096bd1faefb14a4efef1cbd684719bf2aa83 and surrounding code. No review threads were supplied.

    Validation: full-diff git diff --check passed. No tests were run; this was a static review.

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 1 |
    | P2 | 0 |
    | P3 | 0 |
    | Total | 1 |

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

    FrankChen021 FrankChen021 commented on code on Oct 14, 2026 14:03 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/QueryLifecycle.java:1
    @@ -420,13 +460,49 @@ public <T> QueryResponse<T> execute()
         final ResponseContext responseContext = DirectDruidClient.makeResponseContextForQuery();
     
         @SuppressWarnings("unchecked")
    -    final Sequence<T> res = QueryPlus.wrap((Query<T>) baseQuery)
    -                                     .withIdentity(authenticationResult.getIdentity())
    -                                     .run(texasRanger, responseContext);
    +    final Query<T> query = (Query<T>) baseQuery;
    +    final DataSourceQueryHandler dataSourceQueryHandler = findDataSourceQueryHandler(query.getDataSource());
    +    final QueryRunner<T> queryRunner = dataSourceQueryHandler == null
    +                                       ? query.getRunner(texasRanger)
    +                                       : dataSourceQueryHandler.createRunner(

    [P1] Preserve server timeout enforcement for handler-backed queries

    Finding: Handler-backed queries skip the normal SetAndVerifyContextQueryRunner path, which applies ServerConfig default and maximum timeouts and writes DirectDruidClient.QUERY_FAIL_TIME. The system-table handlers instead derive deadlines from the raw query context: omitted timeouts use the query-context fallback rather than druid.server.http.defaultQueryTimeout, timeout: 0 becomes JodaUtils.MAX_INSTANT instead of the server maximum, and values above maxQueryTimeout are not rejected. Since node fanout begins before the later normal walker call, a stalled node request can outlive or bypass the configured query deadline.

    Suggestion: Normalize handler-backed queries with the same server timeout/max-timeout policy before invoking the handler, and pass the normalized deadline into both local and fanout execution paths.

    FrankChen021 FrankChen021 commented on code on Oct 17, 2026 13:02 UTC
    Code Review
    processing/src/main/java/org/apache/druid/segment/FilteredSegment.java:1
    @@ -44,6 +45,8 @@ public <T> T as(@Nonnull Class<T> clazz)
       {
         if (CursorFactory.class.equals(clazz)) {
           return (T) new FilteredCursorFactory(delegate.as(CursorFactory.class), filter);
    +    } else if (CloseableShapeshifter.class.equals(clazz)) {
    +      return (T) new CursorFactoryRowsAndColumns(as(CursorFactory.class));

    [P2] Prevent silent truncation of large filtered windows

    Finding: This new path routes FilteredDataSource window queries through CursorFactoryRowsAndColumns.materialize(). That loop ignores the boolean returned by FrameWriter.addSelection(); once its fixed 200 MB allocator is exhausted, it still advances the cursor and serializes only the rows already written, allowing an oversized filtered window query to succeed with incomplete results.

    Suggestion: Check addSelection() before advancing and fail with ResourceLimitExceededException, or use a bounded multi-frame materialization path, with a regression test for an oversized filtered window result.

    FrankChen021 FrankChen021 commented on Oct 17, 2026 13:02 UTC
    Reviewer

    🟡 Changes recommended

    The new FilteredSegment shapeshift path can silently truncate filtered window results above the 200 MB frame capacity because its materializer ignores FrameWriter.addSelection() failure. This correctness issue should be fixed before merging.

    I rechecked the prior timeout-normalization, composite-datasource, virtual-column-shadowing, and null-window-virtual-column findings and found them resolved. I reviewed 96 of 96 changed files, starting with the incremental diff and then covering the complete current diff, native system-table execution, authorization and cleanup, service wiring, forwarding, coupled and decoupled SQL planning, RowsAndColumns/window integration, documentation, and regression tests.

    Validation: git diff --check passed; no builds, tests, formatters, dependency installs, or runtime validation were run.

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 0 |
    | P2 | 1 |
    | P3 | 0 |
    | Total | 1 |

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

    FrankChen021 FrankChen021 commented on code on Oct 18, 2026 07:07 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/QueryLifecycle.java:1
    @@ -420,13 +465,58 @@ public <T> QueryResponse<T> execute()
         final ResponseContext responseContext = DirectDruidClient.makeResponseContextForQuery();
     
         @SuppressWarnings("unchecked")
    -    final Sequence<T> res = QueryPlus.wrap((Query<T>) baseQuery)
    -                                     .withIdentity(authenticationResult.getIdentity())
    -                                     .run(texasRanger, responseContext);
    +    final Query<T> originalQuery = (Query<T>) baseQuery;
    +    final DataSourceQueryHandler dataSourceQueryHandler = findDataSourceQueryHandler(originalQuery.getDataSource());
    +    // Handlers can start fanout or provider work before reaching a segment walker, or bypass it entirely.
    +    // Apply the same server guardrails first, and pass the normalized query to both runner creation and execution.
    +    final Query<T> query = dataSourceQueryHandler == null
    +                           ? originalQuery
    +                           : SetAndVerifyContextQueryRunner.withTimeoutAndMaxScatterGatherBytes(
    +                               originalQuery,
    +                               serverConfig,
    +                               System.currentTimeMillis()
    +                           );
    +    final QueryRunner<T> queryRunner = dataSourceQueryHandler == null

    [P2] System-table queries cannot be cancelled by query ID

    Finding: The new DataSourceQueryHandler branch invokes createRunner directly instead of registering the outer query with the QueryScheduler/query-watcher path used by normal native execution. When DELETE targets the user-facing system-table query ID, QueryResource finds no registered future or datasource and returns without cancelling the generated native-system-node-* requests, so long-running or fanout queries continue until timeout or stream cleanup.

    Suggestion: Add an explicit scheduler/cancellation bridge for handler execution that associates the outer query ID with the handler and all child requests, and cover DELETE cancellation for broker and node-local system-table queries.

    FrankChen021 FrankChen021 commented on Oct 18, 2026 07:07 UTC
    Reviewer

    🟡 Changes recommended

    The handler-based system-table execution path bypasses query scheduler registration, so DELETE by the user-facing query ID cannot cancel the handler or its generated native-system-node-* child requests. The previous frame-capacity finding is resolved in the current head.

    Reviewed 96 of 96 changed files, beginning with the incremental diff and reconciling it with the full current diff and surrounding code.

    Validation: git diff --check passed. No tests were run.

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 0 |
    | P2 | 1 |
    | P3 | 0 |
    | Total | 1 |

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

    FrankChen021 FrankChen021 commented on code on Oct 19, 2026 14:14 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/QueryLifecycle.java:1
    @@ -420,13 +465,58 @@ public <T> QueryResponse<T> execute()
         final ResponseContext responseContext = DirectDruidClient.makeResponseContextForQuery();
     
         @SuppressWarnings("unchecked")
    -    final Sequence<T> res = QueryPlus.wrap((Query<T>) baseQuery)
    -                                     .withIdentity(authenticationResult.getIdentity())
    -                                     .run(texasRanger, responseContext);
    +    final Query<T> originalQuery = (Query<T>) baseQuery;
    +    final DataSourceQueryHandler dataSourceQueryHandler = findDataSourceQueryHandler(originalQuery.getDataSource());
    +    // Handlers can start fanout or provider work before reaching a segment walker, or bypass it entirely.
    +    // Apply the same server guardrails first, and pass the normalized query to both runner creation and execution.
    +    final Query<T> query = dataSourceQueryHandler == null
    +                           ? originalQuery
    +                           : SetAndVerifyContextQueryRunner.withTimeoutAndMaxScatterGatherBytes(
    +                               originalQuery,
    +                               serverConfig,
    +                               System.currentTimeMillis()
    +                           );
    +    final QueryRunner<T> queryRunner = dataSourceQueryHandler == null

    Leave this in a follow up PR, reaons: the case that cancels a query on system table is not common

    FrankChen021 FrankChen021 commented on code on Oct 20, 2026 12:54 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/QueryLifecycle.java:1
    @@ -420,13 +465,58 @@ public <T> QueryResponse<T> execute()
         final ResponseContext responseContext = DirectDruidClient.makeResponseContextForQuery();
     
         @SuppressWarnings("unchecked")
    -    final Sequence<T> res = QueryPlus.wrap((Query<T>) baseQuery)
    -                                     .withIdentity(authenticationResult.getIdentity())
    -                                     .run(texasRanger, responseContext);
    +    final Query<T> originalQuery = (Query<T>) baseQuery;
    +    final DataSourceQueryHandler dataSourceQueryHandler = findDataSourceQueryHandler(originalQuery.getDataSource());
    +    // Handlers can start fanout or provider work before reaching a segment walker, or bypass it entirely.
    +    // Apply the same server guardrails first, and pass the normalized query to both runner creation and execution.
    +    final Query<T> query = dataSourceQueryHandler == null
    +                           ? originalQuery
    +                           : SetAndVerifyContextQueryRunner.withTimeoutAndMaxScatterGatherBytes(
    +                               originalQuery,
    +                               serverConfig,
    +                               System.currentTimeMillis()
    +                           );
    +    final QueryRunner<T> queryRunner = dataSourceQueryHandler == null
    +                                       ? query.getRunner(texasRanger)
    +                                       : dataSourceQueryHandler.createRunner(

    [P2] Register handler queries for cancellation

    Finding: Handler-backed native system-table queries bypass QueryScheduler registration. QueryResource cancellation therefore cannot resolve the user-facing query ID, while generated child requests and local provider work continue independently.

    Suggestion: Register the handler's top-level execution or an equivalent parent cancellation handle with QueryScheduler using the user query ID, and ensure cancellation closes NodeSequencesCloser, local/provider work, and generated child futures.

    FrankChen021 FrankChen021 commented on Oct 20, 2026 12:54 UTC
    Reviewer

    🟡 Changes recommended

    The top-level native system-table query is executed directly through DataSourceQueryHandler from QueryLifecycle, so the user-facing query ID is never registered with QueryScheduler. Consequently, QueryResource.cancelQuery can find no datasource or future for that ID and return 202 without canceling the Broker handler. The generated native-system-node-* requests use separate child IDs, while local provider work is not represented by a scheduler future, so cancellation by the user-facing ID does not reliably stop fanout or provider work.

    Register the handler's top-level execution, or an equivalent parent cancellation handle, with QueryScheduler using the user query ID. Cancellation should close NodeSequencesCloser, local provider work, and generated child futures while retaining existing child-ID cancellation for remote requests.

    The previously reported frame-capacity/truncation issue is resolved in this head.

    Reviewed 96 of 96 changed files; finding in 1 file.

    Validation: git diff --check 38a15334565f0c304f2a0d934567aec17fdab3df HEAD passed. No tests or builds run during this static review.

    | Severity | Findings |
    | --- | ---: |
    | P0 | 0 |
    | P1 | 0 |
    | P2 | 1 |
    | P3 | 0 |
    | Total | 1 |

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

    FrankChen021 FrankChen021 commented on Oct 20, 2026 13:43 UTC
    Reviewer

    🟢 Approval recommended

    Correction to the earlier review: the system-table cancellation finding duplicated the prior review thread and is excluded from this final assessment. The author's reply asked that it be deferred to a follow-up. No new actionable issues remain in the reviewed changes.

    Reviewed 96 of 96 changed files.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Oct 21, 2026 03:39 UTC
    Author

    @gianm @GWphua @abhishekrb19 any comments for this one?

    While the change is wide, but it has little impact over existing logic as most of the newly added code is activated via the new context paramterer allowNativeFunctionsForSystemTables which is also mark as experimental.

    As the AI has performed multiple rounds of review, I think the risk is low to us to include it into the master.

    gianm gianm commented on code on Oct 23, 2026 11:15 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,61 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + experimental [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
    +:::
    +
    +### Native query execution
    +
    +:::caution Experimental
    +Native query execution for system tables is an experimental, opt-in feature. Its behavior and interfaces may change.
     :::
     
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`allowNativeFunctionsForSystemTables` to `true` in the SQL query context:

    IMO useNativeEngineForSystemTables is a better name for this parameter.

    gianm gianm commented on code on Oct 23, 2026 11:18 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,61 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable

    Hmm, instead of "use the SQL-layer execution path" how about "use a SQL interpreter on the Broker"? I'm not sure if it's better, tbh. I just thought "SQL-layer execution path" wasn't clear.

    gianm gianm commented on code on Oct 23, 2026 11:20 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,61 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + experimental [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
    +:::
    +
    +### Native query execution
    +
    +:::caution Experimental
    +Native query execution for system tables is an experimental, opt-in feature. Its behavior and interfaces may change.
     :::
     
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`allowNativeFunctionsForSystemTables` to `true` in the SQL query context:
    +
    +```json
    +{
    +  "query": "SELECT COUNT(DISTINCT server) FROM sys.server_properties",
    +  "context": {
    +    "allowNativeFunctionsForSystemTables": true
    +  }
    +}
    +```
    +
    +For clients that support setting query context parameters with SQL statements, you can enable native system-table
    +execution with `SET`:
    +
    +```sql
    +SET allowNativeFunctionsForSystemTables = 'true';
    +SELECT COUNT(DISTINCT server) FROM sys.server_properties;
    +```
    +
    +Native system-table execution is available when the resolved SQL engine is `native`. You don't need to explicitly set
    +the `engine` context parameter when `native` is already the default engine. The following tables support native query
    +execution:
    +
    +|Table|Source of rows|
    +|-----|--------------|
    +|[`sys.server_properties`](#server_properties-table)|The Druid server processes discovered in the cluster. Filters on `server` and `service_name` can avoid reading properties from nodes that don't match.|
    +
    +After Druid retrieves the system-table rows, the native engine applies the remaining filters, expressions,
    +aggregations, sorting, and result processing. A system table that doesn't advertise native query support continues to
    +use its existing SQL-layer execution path, even when `allowNativeFunctionsForSystemTables` is `true`.
    +
    +The parameter defaults to `false`. During a rolling upgrade, leave it disabled until the Broker and all nodes
    +that serve the native system tables have been upgraded. After the upgrade, you can enable it by query or set
    +`druid.query.default.context.allowNativeFunctionsForSystemTables=true` on Brokers as the cluster-wide default. For more
    +information, see [SQL query context](sql-query-context.md).
    +
    +Native system-table queries sent to the Router use distributed Broker execution by default. To execute a native
    +system-table Scan against only the contacted node, set the HTTP header
    +`X-Druid-Native-Query-Route: local`. Local execution uses the authenticated request identity and applies the table's

    What authorization rules are used when the header is not present? The sentence as written implies that it's something other than "the table's authorization rules", but hopefully they _are_ still applied.

    gianm gianm commented on code on Oct 23, 2026 11:20 UTC
    Code Review
    docs/querying/sql-metadata-tables.md:1
    @@ -135,10 +135,61 @@ WHERE "IS_AGGREGATOR" = 'YES'
     The "sys" schema provides visibility into Druid segments, servers and tasks.
     
     :::info
    - Note: "sys" tables do not currently support Druid-specific functions like `TIME_PARSE` and
    - `APPROX_QUANTILE_DS`. Only standard SQL functions can be used.
    + By default, "sys" tables use the SQL-layer execution path and support only standard SQL functions. You can enable
    + experimental [native query execution](#native-query-execution) for supported system tables, which enables expressions and
    + aggregations that the native SQL engine can translate.
    +:::
    +
    +### Native query execution
    +
    +:::caution Experimental
    +Native query execution for system tables is an experimental, opt-in feature. Its behavior and interfaces may change.
     :::
     
    +The native SQL engine can plan supported system tables as native datasources. To enable this behavior for a query, set
    +`allowNativeFunctionsForSystemTables` to `true` in the SQL query context:
    +
    +```json
    +{
    +  "query": "SELECT COUNT(DISTINCT server) FROM sys.server_properties",
    +  "context": {
    +    "allowNativeFunctionsForSystemTables": true
    +  }
    +}
    +```
    +
    +For clients that support setting query context parameters with SQL statements, you can enable native system-table
    +execution with `SET`:
    +
    +```sql
    +SET allowNativeFunctionsForSystemTables = 'true';
    +SELECT COUNT(DISTINCT server) FROM sys.server_properties;
    +```
    +
    +Native system-table execution is available when the resolved SQL engine is `native`. You don't need to explicitly set
    +the `engine` context parameter when `native` is already the default engine. The following tables support native query
    +execution:
    +
    +|Table|Source of rows|
    +|-----|--------------|
    +|[`sys.server_properties`](#server_properties-table)|The Druid server processes discovered in the cluster. Filters on `server` and `service_name` can avoid reading properties from nodes that don't match.|
    +
    +After Druid retrieves the system-table rows, the native engine applies the remaining filters, expressions,
    +aggregations, sorting, and result processing. A system table that doesn't advertise native query support continues to
    +use its existing SQL-layer execution path, even when `allowNativeFunctionsForSystemTables` is `true`.
    +
    +The parameter defaults to `false`. During a rolling upgrade, leave it disabled until the Broker and all nodes
    +that serve the native system tables have been upgraded. After the upgrade, you can enable it by query or set
    +`druid.query.default.context.allowNativeFunctionsForSystemTables=true` on Brokers as the cluster-wide default. For more
    +information, see [SQL query context](sql-query-context.md).
    +
    +Native system-table queries sent to the Router use distributed Broker execution by default. To execute a native

    This paragraph probably isn't necessary, it seems like it's about an internal detail, not really about SQL.

    gianm gianm commented on code on Oct 23, 2026 11:25 UTC
    Code Review
    server/src/main/java/org/apache/druid/client/DirectDruidClient.java:1
    @@ -785,7 +785,8 @@ private void checkTotalBytesLimit(long bytes)
                  .setHeader(
                      HttpHeaders.Names.CONTENT_TYPE,
                      isSmile ? SmileMediaTypes.APPLICATION_JACKSON_SMILE : MediaType.APPLICATION_JSON
    -             ),
    +             )
    +             .setHeader(QueryResource.HEADER_NATIVE_QUERY_ROUTE, QueryResource.NATIVE_QUERY_ROUTE_LOCAL),

    This appears to be getting set unconditionally. It would be nice to only set it for the requests that need it, for a few reasons:

  • to make it clear it's only needed for certain requests

  • cleanliness

  • to save the bytes
  • gianm gianm commented on code on Oct 23, 2026 11:27 UTC
    Code Review
    server/src/main/java/org/apache/druid/server/system/handler/SystemTableNodeLocator.java:1
    @@ -0,0 +1,150 @@
    +/*
    + * 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.druid.server.system.handler;
    +
    +import com.google.common.collect.Iterables;
    +import com.google.common.util.concurrent.ListenableFuture;
    +import com.google.inject.Inject;
    +import org.apache.druid.client.DirectDruidClient;
    +import org.apache.druid.client.coordinator.CoordinatorClient;
    +import org.apache.druid.discovery.DiscoveryDruidNode;
    +import org.apache.druid.discovery.DruidNodeDiscoveryProvider;
    +import org.apache.druid.discovery.NodeRole;
    +import org.apache.druid.java.util.common.ISE;
    +import org.apache.druid.query.Query;
    +import org.apache.druid.query.QueryInterruptedException;
    +import org.apache.druid.query.QueryTimeoutException;
    +import org.apache.druid.rpc.indexing.OverlordClient;
    +import org.apache.druid.server.system.table.SystemTableDescriptor;
    +import org.apache.druid.server.system.table.SystemTableRoutingMode;
    +
    +import java.net.URI;
    +import java.util.ArrayList;
    +import java.util.LinkedHashMap;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.concurrent.ExecutionException;
    +import java.util.concurrent.TimeUnit;
    +import java.util.concurrent.TimeoutException;
    +
    +/** Resolves a descriptor's logical routing policy to concrete Druid processes. */
    +public class SystemTableNodeLocator
    +{
    +  private final DruidNodeDiscoveryProvider discoveryProvider;
    +  private final Map<NodeRole, SystemTableLeaderLocator> leaderLocators;
    +
    +  @Inject
    +  public SystemTableNodeLocator(
    +      final DruidNodeDiscoveryProvider discoveryProvider,
    +      final CoordinatorClient coordinatorClient,
    +      final OverlordClient overlordClient
    +  )
    +  {
    +    this.discoveryProvider = discoveryProvider;
    +    this.leaderLocators = Map.of(
    +        NodeRole.COORDINATOR,
    +        coordinatorClient::findCurrentLeader,
    +        NodeRole.OVERLORD,
    +        overlordClient::findCurrentLeader
    +    );
    +  }
    +
    +  List<SystemTableNode> locate(final SystemTableDescriptor descriptor, final Query<?> query)

    This method appears to be ignoring the query filter, which is a regression in efficiency. The Bindable implementation can prune the set of servers to query based on server and service_name.

    gianm gianm commented on code on Oct 23, 2026 11:57 UTC
    Code Review
    processing/src/main/java/org/apache/druid/query/SystemTableDataSource.java:1
    @@ -0,0 +1,110 @@
    +/*
    + * 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.druid.query;
    +
    +import com.fasterxml.jackson.annotation.JsonCreator;
    +import com.fasterxml.jackson.annotation.JsonProperty;
    +import com.google.common.base.Preconditions;
    +
    +import java.util.Collections;
    +import java.util.Objects;
    +import java.util.Set;
    +
    +/**
    + * Identifies a Druid system table whose rows are supplied by a service rather than by segments.
    + */
    +public class SystemTableDataSource extends LeafDataSource

    This doesn't override withPolicies but it should, because it has table names (getTableNames). I raised https://github.com/apache/druid/pull/20705 which would throw from withPolicies for this class.

    gianm gianm commented on Oct 23, 2026 12:15 UTC
    Reviewer

    Sorry it took so long to review this PR. At a high level the approach looks OK, although I wonder why you used /druid/v2/ for fanout rather than the existing APIs? It seems like it adds a layer of complexity to the PR that doesn't necessarily need to be there. It does have a certain tidiness to it; I'm wondering if that's the only reason or if there are other, more practical reasons.

    Some other high-level comments:

    Server-level opt-in: There should be a common.runtime.properties server property to enable this feature, off by default. When it's off, don't bind the new stuff or accept systemTable datasources. Also, the context key should do nothing if the property is off (it can't override the server property). This helps operators control the rollout.

    Permissions: Now that the /druid/v2/ path is really equivalent to system tables, it should include opt-in authorization for the SYSTEM_TABLE resource. Currently the SQL planner enforces this if druid.sql.planner.authorizeSystemTablesDirectly is set. I don't think we want this sql property to apply to the /druid/v2/ path, so instead, I suggest deprecating it, introducing druid.auth.authorizeSystemTablesDirectly, and respecting that property on all servers. On the Broker, if both happen to be set, use the logical OR of them, and also warn if the "sql" one is set but the "auth" one is not.

    Security tests: More security tests would be appreciated. For example:

  • tests for the Broker and other nodes' /druid/v2/ calls properly respecting authorization (including verifying that authorizeSystemTablesDirectly and STATE READ are checked) for all values of X-Druid-Native-Query-Route

  • tests for masking in the /druid/v2/ path (similar to test_serverPropertiesTable_hiddenProperties)

  • at least one embedded test verifying such permissions, to make sure it works end to end. Unit tests for QueryLifecycle would also be useful. For server_properties
  • Joins: There appears to be a bug with joins, such as: SELECT property FROM sys.server_properties WHERE server IN (SELECT server FROM sys.server_properties WHERE service_name = 'druid/broker') LIMIT 5. I tried it out and and got 0 rows, but should have got at least a few.

    FrankChen021 FrankChen021 commented on Oct 23, 2026 12:39 UTC
    Author

    At a high level the approach looks OK, although I wonder why you used /druid/v2/ for fanout rather than the existing APIs? I

    What do you mean by existing APIs here? do you mean the API for the server properties like /status/properties ?

    The reason is that I would like the internal data fetching from different servers to be unified like how we execute sub queries on different nodes. By this way, in future, there's any new table(like the sys.stack_trace table) added, we don't add new APIs.

    Currently SCAN query is fan out from broker to different nodes, and I was planning to push down aggregation queries in a later stage. So the /druid/v2 is the best place to serve the need.

    However, for the native engine, I will not do the aggregation query push down, because I found that the the dart engine already does this, so the long term evolution here is to use the dart engine to fan out sub queries.

    FrankChen021 FrankChen021 commented on Oct 23, 2026 12:47 UTC
    Author

    Server-level opt-in: There should be a common.runtime.properties server property to enable this feature, off by default. When it's off, don't bind the new stuff or accept systemTable datasources. Also, the context key should do nothing if the property is off (it can't override the server property). This helps operators control the rollout.

    Currently I use the query context parameter to control the new path. The query context parameter is not enabled by default. If a system property is introduced, will it be a little bit complex?

    FrankChen021 FrankChen021 commented on Oct 23, 2026 12:53 UTC
    Reviewer

    🟢 Approval recommended

    The incremental patch is an upstream-master merge; overlapping changes contain no new PR-caused defects. Prior timeout, frame-capacity, composite-datasource, virtual-column, and null-window findings remain resolved. No new high-confidence issue was found.

    Reviewed 96 of 96 changed files.

    Validation: git diff --check passed; no builds, tests, dependency installation, or formatters were run.

    <!-- mergelens:review -->

    ---

    This is an automated review by Codex GPT-5.6-Luna(max)

    FrankChen021 FrankChen021 commented on Oct 23, 2026 13:01 UTC
    Author

    @gianm Thank you for the review. I replied some questions you raised. For others, I will address them in a new commit.

    FrankChen021 FrankChen021 commented on Oct 23, 2026 15:28 UTC
    Author

    @gianm Thanks for the review. Addressed:

    Permissions: Added druid.auth.authorizeSystemTablesDirectly, respected on all servers: native queries then authorize system tables as SYSTEM_TABLE resources (also used for cancellation). The Broker uses the OR of it and druid.sql.planner.authorizeSystemTablesDirectly (now deprecated), and warns if only the sql one is set.

    Security tests:

  • QueryLifecycleTest: authorization for every X-Druid-Native-Query-Route value, with and without authorizeSystemTablesDirectly.

  • SystemTableQueryClientTest / SystemTableQueryHandlerTest: STATE READ is checked against the caller on Broker fan-out and on node-local execution.

  • Masking: ServerPropertiesTableDataProviderTest and NativeSysServerPropertiesQueryTest#testHiddenPropertiesAreNotReturnedByNativeQueries (Broker fan-out, Broker-local, Router-local).

  • Embedded: BasicAuthConfigurationTest#test_nativeSystemTableQuery_requiresSystemTableAndStateRead on the Broker and Router for every route value.
  • Joins: Node scans shared the caller's ResponseContext, so the right side's scanned-row counts made the outer limited Scan return no rows. Each system-table leaf now gets its own response context. Tests: NativeSysServerPropertiesQueryTest#testInSubqueryOnSameSystemTable (your query, both planners) and SystemTableQueryClientTest#testNodeScansDoNotShareCallerResponseContext.

    gianm gianm commented on Oct 30, 2026 06:39 UTC
    Contributor

    What do you mean by existing APIs here? do you mean the API for the server properties like /status/properties ?

    Yes, I meant the existing APIs like /status/properties.

    The reason is that I would like the internal data fetching from different servers to be unified like how we execute sub queries on different nodes. By this way, in future, there's any new table(like the sys.stack_trace table) added, we don't add new APIs.

    > Currently SCAN query is fan out from broker to different nodes, and I was planning to push down aggregation queries in a later stage. So the /druid/v2 is the best place to serve the need.

    I suppose using /druid/v2/ for just scan is OK and it's nice to not need new APIs for every table. However I have concerns about using query types beyond scan. The aggregating query types generally require processing buffers, which means extra memory footprint on the servers that don't currently handle queries, which I think we should avoid.

    However, for the native engine, I will not do the aggregation query push down, because I found that the the dart engine already does this, so the long term evolution here is to use the dart engine to fan out sub queries.

    Hmm, how much of what's in this PR would change if things used Dart instead? The protocol with Dart is more complex than /druid/v2/ due to being async: there's the outboxes and message relays and stuff. Would we need those on every server type? Seems like a lot of stuff to set up on servers that don't currently handle queries.

    gianm gianm commented on Oct 30, 2026 06:43 UTC
    Contributor

    Currently I use the query context parameter to control the new path. The query context parameter is not enabled by default. If a system property is introduced, will it be a little bit complex?

    I requested the system property because to me, adding a systemTable datasource type, adding /druid/v2/ to servers that don't currently handle queries, and the local header for Routers are all major changes. I think some people would like to have those things switched off in production environments until they have been evaluated in staging environments.

    gianm gianm commented on Oct 30, 2026 06:49 UTC
    Contributor

    @FrankChen021 please let me know what you think of my comments, and I can do another round of review.

    FrankChen021 FrankChen021 commented on Oct 30, 2026 07:00 UTC
    Author

    @gianm Thanks for the comments. The fix is in. And here're my replies:

    I requested the system property because to me, adding a systemTable datasource type and adding /druid/v2/ to servers that don't currently handle queries are major changes. I think some people (perhaps even me) would like to have those things switched off in production environments until they have been evaluated in staging environments.

    druid.query.enableDruidEngineForSystemTables is added to serve the need.

    I suppose using /druid/v2/ for just scan is OK and it's nice to not need new APIs for every table. However I have concerns about using query types beyond scan. The aggregating query types generally require processing buffers, which means extra memory footprint on the servers that don't currently handle queries, which I think we should avoid.

    You are right, pushing down aggregation queries to each node requires merge buffers. And I don't plan to do so.
    My plan is to use dart engine for such purpose.

    Hmm, how much of what's in this PR would change if things used Dart instead? The protocol with Dart is more complex than /druid/v2/ due to being async: there's the outboxes and message relays and stuff. Would we need those on every server type? Seems like a lot of stuff to set up on servers that don't currently handle queries.

    All shared changes that supports dart engine are already in this PR. If dart is used, only the fan-out path in this PR is not needed. And under dart, scan queries are sending to coordinator/overlord/peon, but scan/aggregation queries can go to historical/broker. The execution path is as:

    SQL request (engine = msq-dart)
      -> Calcite plans sys.server_properties as SystemTableDataSource
      -> the Dart controller locates source nodes and creates input slices
      -> a worker reads its node-local provider when possible,
         or sends a node-local native Scan to the source node's /druid/v2 endpoint
      -> ordinary MSQ worker stages apply filters, aggregation, windows,
         shuffle and final result processing
    

    We don't install more modules or introduce more dependencies on every service type. The impl is already done here: https://github.com/FrankChen021/druid/pull/235 (number of changes is large, but no large changes, and most of changes are test cases)

    FrankChen021 FrankChen021 commented on Nov 05, 2026 13:59 UTC
    Author

    @gianm the feature flag you asked for is in. Can you do another round of review?

    FrankChen021 FrankChen021 commented on Nov 06, 2026 11:50 UTC
    Author

    About testing, I didn't see tests here for /druid/v2/ authorization on the Coordinator and Overlord. Please add those.

    Added. The native system-table auth test now also queries the Coordinator and Overlord on /druid/v2/, both for SYSTEM_TABLE READ and for the STATE READ row check.

    FrankChen021 FrankChen021 commented on Nov 19, 2026 13:51 UTC
    Author

    @gianm let me know if you have more comments

    Reviewers
    Assignees
    FrankChen021 FrankChen021
    Labels
    risk: low confidence: 81.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 92.5% (HIGH) · Higher = larger blast radius
    92.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 81.3% · Lower = rushed or shallow review
    81.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.3% · Safe to merge
    17.3%
    Repository