Skip to content

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

Open
FrankChen021 wants to merge 41 commits into
apache:masterfrom
FrankChen021:codex/native-sys-tasks-mvp
Open

FrankChen021 wants to merge 41 commits into
apache:masterfrom
FrankChen021:codex/native-sys-tasks-mvp

Conversation

@FrankChen021

@FrankChen021 FrankChen021 commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

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

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.
Implementation details and extension points

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.
Authorization
  • 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.
Compatibility and current limitations

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.

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.

Copilot AI lite review requested due to automatic review settings August 28, 2026 15:28

This comment was marked as outdated.

@FrankChen021

Copy link
Copy Markdown
Member 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

This comment was marked as outdated.

@abhishekrb19 abhishekrb19 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread docs/querying/sql-metadata-tables.md Resolved
Comment thread docs/querying/sql-metadata-tables.md Resolved
@FrankChen021

FrankChen021 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member 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.

@gianm

gianm commented Sep 9, 2026

Copy link
Copy Markdown
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

This comment was marked as outdated.

FrankChen021

This comment was marked as outdated.

@FrankChen021 FrankChen021 added this to the 39.0.0 milestone Sep 19, 2026
@FrankChen021 FrankChen021 mentioned this pull request Sep 19, 2026
1 of 10 tasks
…asks-mvp

# Conflicts:
#	server/src/test/java/org/apache/druid/client/DirectDruidClientTest.java
FrankChen021

This comment was marked as outdated.

FrankChen021 added a commit to FrankChen021/druid that referenced this pull request Oct 30, 2026
Port #213 onto apache#20183 so Dart reuses the
native system-table infrastructure instead of carrying its own copy.

- Dart plans supported system tables as SystemTableDataSource inputs:
  the controller locates source nodes and slices them, and workers read
  node-local providers or send node-local native Scans, so later stages
  run on the regular MSQ path. The Broker runs an embedded Dart worker
  so these queries don't need a Historical.
- SqlEngine.supportsSystemTableDataSource lets engines other than native
  opt in per table; Dart supports tables routed to all nodes.
- Authorization: Dart workers read rows with the internal identity, so
  the caller's permissions from SystemTableDescriptor.getResourceActions
  are checked when the statement is authorized and again on the planned
  tree, which covers system tables reached through views and subqueries.
- Shared with the native path: SystemTableNodeLocator, the pushdown
  filter extraction, SystemTableAuthorization.readAuthorizedRows and
  SystemTableNodeFailure, which now treats only 404, 502 and 503
  responses as an unavailable node.

Dart honors druid.query.enableDruidEngineForSystemTables: when it is
off, no system-table bindings are installed and Dart reads system tables
through the Broker's Bindable plan like the native engine.
FrankChen021

This comment was marked as duplicate.

…sks-mvp

# Conflicts:
#	services/pom.xml
#	services/src/test/java/org/apache/druid/cli/MainTest.java
FrankChen021

This comment was marked as duplicate.

@FrankChen021

Copy link
Copy Markdown
Member Author

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

@gianm gianm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On this review pass I focused on simplicity and maintainability. There is a lot of code in this patch and it seems there is a lot more coming, so this was high in my mind. One of the line comments in QueryLifecycle suggests some changes that I think could make system tables much less of a special case in terms of native execution.

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

public static Set<Resource> getDataSourceResources(final DataSource dataSource)
{
final Set<Resource> resources = new LinkedHashSet<>();
if (containsSystemTable(dataSource)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be cleaner and more maintainable to add a method getResources() to DataSource, and use that rather than getTableNames() for authorization.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it would be cleaner. One snag: Resource and ResourceType live in server, while DataSource is in processing. So DataSource#getResources() would mean moving those two classes, and maybe ResourceAction, into processing. Are you OK with that move, in this PR or a separate one? Or would you prefer a server-side visitor over the DataSource tree that maps each leaf to its resources, without changing DataSource?

* 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if there is some way to simplify this file. It seems quite long and `complex.

}

final List<VirtualColumn> virtualColumns = new ArrayList<>(List.of(query.getVirtualColumns().getVirtualColumns()));
if (query instanceof WindowOperatorQuery) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's 5 places in this file where we're checking instanceof WindowOperatorQuery. It suggests to me some kind of problem with the layering of code. Ideally nothing in this file should be specific to the query that is running. Could we avoid this if we refrained from sending down any filters and virtual columns from WindowOperatorQuery?

.resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
.limit(Long.MAX_VALUE)
.filters(nodeFilter)
.virtualColumns(nodeVirtualColumns(dataSource, owningQuery, nodeFilter))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sending down user-written virtual columns can shadow physical columns. I think this may defeat the authorization checks for tables like sys.tasks (imagine a user setting a virtual column called datasource, which the Broker-side filter would see instead of the "real" datsource). Please check if this is a real issue. If it is, it should be fixable with a check that the names do not collide with columns that are present in the tables.

this.startNs = startNs;
}

public QueryLifecycle(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes in this file are extensive and seem to be muddying what QueryLifecycle is responsible for. Rather than always pass queries to the configured QuerySegmentWalker for execution, it sometimes executes them itself using DataSourceQueryHandler. It also has logic that is specific to how queries are routed, mixed into the authorize flow.

I'm trying to think about how this could all be made simpler and smoother. Here is an idea. Please let me know what you think.

Process SystemTableDataSource directly

By making SystemTableDataSource processable we can treat it as less of a special case.

  • Make SystemTableDataSource processable, add a SystemTableSegmentWrangler that creates SystemTableSegment.
  • SystemTableSegment contains the SystemTableDataProvider.
  • SystemTableSegment#as supplies a SystemTableCursorFactory, which pushes down filters and required columns from CursorBuildSpec#getFilter and CursorBuildSpec#getPhysicalColumns.
  • No need for DataSourceQueryHandler since the logic ends up in SystemTableSegmentWrangler.
  • No need for SystemTablePushdownFilter, as that's handled in the SystemTableDataProvider.

Suggestion for a change to SystemTableDataProvider to support this:

public interface SystemTableDataProvider
{
  /** Columns whose filters getRows can use to read fewer rows from storage. */
  default Set<String> getPushdownColumns()
  {
    return Set.of();
  }

  /**
   * Returns the table's rows, in row-signature order, each time it's called.
   * Filters read only pushdown columns. The result must include every row
   * matching all of them, and may include additional rows.
   */
  Iterable<Object[]> getRows(List<Filter> filters);
}

Fan out in SQL only

There is significant complexity in dealing with the local vs fanout mode, not just here but throughout the PR. We could make fanout a SQL-only thing, which would be simpler and I think would be acceptable behavior:

  • NativeQueryMaker resolves system table datasources to inline datasources with SystemTableQueryClient, and then runs the query as normal.
  • The /druid/v2/ routes on each server only need to support local mode.
  • No need for X-Druid-Native-Query-Route.
  • The SQL code in the Broker does need to do a filter to only include authorized objects.

Authorization for /druid/v2/

  • SystemTableCursorFactory applies authorization-based row filtering, such as only showing tasks that the user is supposed to see.
  • A non-serializing authorization object is attached to SystemTableDataSource during QueryLifecycle#authorize (this is one of the sys-table-specific things that would need to remain)
  • The SystemTableSegmentWrangler expects to see that non-serializing authorization object, and bakes it into the SystemTableSegment so it can be passed to the SystemTableCursorFactory.

Suggestion for the authorization object:

record SystemTableAccess(@Nullable Predicate<Object[]> rowPredicate)

@FrankChen021 FrankChen021 Nov 6, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the better path, and it's now implemented in this PR.

When I started this, I was always thinking how can we re-use existing fan-out path. Because for system tables, it should not be treated separately with other user datasources. The problems then were about different segment walker and different authorization model(system table requires per-row authorization), so a separately fan-out path was the first choice.

What changed:

  • QueryLifecycle no longer executes queries itself. DataSourceQueryHandler is removed, and every query goes to the configured QuerySegmentWalker. QueryLifecycle only attaches the caller's row access to system tables during authorization.

  • SystemTableDataSource is read through SystemTableSegmentWrangler, which turns the table's provider into a segment. AND-conjuncts on the provider's pushdown columns are passed to the provider; the full filter and virtual columns are still applied by the cursor factory.

  • Native fan-out goes away. A native /druid/v2/ query on a systemTable datasource returns only the contacted service's rows. Only SQL fans out: NativeQueryMaker marks the system tables of a SQL query with the cluster scope, and the Broker's SystemTableGatheringQuerySegmentWalker gathers their rows from every service before running the query. The scope is never serialized, so a native query can't request a fan-out.

  • Scan-only servers get a walker. NativeQueryEngineModule binds SystemTableQuerySegmentWalker on non-Broker services. It sends system-table queries to a LocalQuerySegmentWalker, which resolves datasources through segment wranglers, and everything else to the service's own walker (NoopQuerySegmentWalker, SegmentMetadataQuerySegmentWalker, ServerManager, and so on). The Router, Coordinator, Overlord and Middle Manager accept only Scan queries on a systemTable datasource and return 501 for other queries.

  • The access object can't get lost. SystemTableAccess isn't serialized, and SystemTableDataSource is processable only when its access is attached, so a query that rebuilt the datasource without it fails instead of returning unfiltered rows. The walkers also reject such queries defensively.

  • Authorization order. The cursor factory applies the row predicate to the provider's raw rows, before the query's virtual columns and filters, so a virtual column can't change which rows pass the check. This also removes the virtual-column shadowing issue, along with SystemTablePushdownFilter. For server_properties, the all-or-nothing STATE READ check stays in authorization, so it needs no row predicate.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also benchmarked the new path against the previous design (807b585) and the SQL interpreter, to check the refactor doesn't cost performance.

Setup: an embedded cluster with six services (Broker, Router, Coordinator, Overlord, Historical, Indexer) in one JVM. Each service had 0, 1,000 or 20,000 extra properties, giving 103, 6,103 or 120,103 rows of sys.server_properties. Each query ran 300 times after 50 warmup runs (100 after 20 at the largest size), in two rounds per branch in alternating order.

Median latency in ms, shown as new design / previous design / SQL interpreter:

Query 103 rows 6.1k rows 120k rows
SELECT COUNT(*) 3.7 / 3.7 / 3.7 5.7 / 6.0 / 8.0 47.8 / 51.4 / 121.8
WHERE server = '<one server>' 3.1 / 3.6 / 5.2 4.4 / 4.3 / 5.9 23.8 / 23.6 / 27.2
GROUP BY service_name 2.6 / 3.1 / 2.6 5.3 / 5.3 / 7.2 55.4 / 54.5 / 126.5
WHERE server IN (SELECT server ... WHERE service_name = ...) 4.5 / 4.4 / 8.2 7.5 / 7.7 / 14.5 69.6 / 72.2 / 152.8
Native Scan sent to the Coordinator's /druid/v2/ 0.24 / 0.25 / – 1.0 / 1.0 / – 16.9 / 16.3 / –
  • The new and previous designs perform the same: the differences are within the variation between two rounds of the same branch, and allocation per query is within about 2%.
  • Both native paths are about 2.2–2.5 times faster than the SQL interpreter for full-table queries at 120k rows, and comparable at about 100 rows.
  • The filter on server is pushed down to each service, so that query reads only one service's rows and is about twice as fast as COUNT(*) at 120k rows.

Because all services run in one JVM over loopback, network cost is understated; the numbers compare code paths, not production latency.

…ry test constructor, add Coordinator/Overlord native auth tests

- Remove /druid/v2 (no trailing slash) from the Coordinator and Overlord redirect LOCAL_PATHS.
- Delete the convenience QueryLifecycleFactory constructor and migrate its test callers.
- Check native system-table authorization on the Coordinator and Overlord too.
- Reword the frame-capacity comment in CursorFactoryRowsAndColumns.
@FrankChen021

Copy link
Copy Markdown
Member 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

This comment was marked as duplicate.

@Fly-Style Fly-Style modified the milestones: 39.0.0, 40.0.0 Nov 6, 2026
…sks-mvp

# Conflicts:
#	server/src/main/java/org/apache/druid/server/QueryResource.java
Master's checkstyle now rejects /// documentation comments.
FrankChen021 added a commit to FrankChen021/druid that referenced this pull request Nov 7, 2026
…only

Rework native system-table execution as proposed in review of apache#20183:

- SystemTableDataSource becomes processable once the authorizing server attaches a non-serialized
  SystemTableAccess (the caller's row predicate). SystemTableSegmentWrangler, SystemTableSegment and
  SystemTableCursorFactory read the provider's rows, push filters on pushdown columns into
  SystemTableDataProvider#getRows(List<Filter>), and authorize raw rows before virtual columns apply.
- QueryLifecycle attaches the access in authorize and no longer special-cases execution. The
  DataSourceQueryHandler path, the X-Druid-Native-Query-Route header and SystemTablePushdownFilter are removed.
- Native /druid/v2/ queries on system tables read the contacted service's rows. Non-Broker services wrap
  their walker in SystemTableQuerySegmentWalker; the Router answers locally when it can run the query.
- SQL marks the system tables it plans as gathered from all services. On the Broker,
  SystemTableGatheringQuerySegmentWalker gathers their rows after the query is authorized and logged,
  filtered by the caller's access. Window-query special cases are gone; union arms resolve separately.
FrankChen021

This comment was marked as duplicate.

…only

Rework native system-table execution as suggested in review:

- SystemTableDataSource is read through SystemTableSegmentWrangler, which turns a table provider into a segment.
  AND-conjuncts on the provider's pushdown columns are passed to the provider; the full filter and virtual columns
  are still applied by the cursor factory.
- A native query on a systemTable datasource reads only the rows of the service that receives it, on every service.
  Only SQL fans out: NativeQueryMaker marks system tables with the cluster scope, and the Broker's
  SystemTableGatheringQuerySegmentWalker gathers their rows from every service before running the query.
- QueryLifecycle attaches the caller's row access (SystemTableAccess) during authorization. The access is never
  serialized, and a system table is processable only once its access is attached.
- The Router, Coordinator, Overlord and Middle Manager serve only Scan queries on a systemTable datasource through
  SystemTableQueryResource; other query types get 501.
- Remove the native-query route header, the gathering flag, leader-only routing and SystemTablePushdownFilter.
…sks-mvp

# Conflicts:
#	docs/configuration/index.md
#	server/src/main/java/org/apache/druid/server/security/AuthConfig.java
FrankChen021 added a commit to FrankChen021/druid that referenced this pull request Nov 10, 2026
Port #213 onto apache#20183 so Dart reuses the
native system-table infrastructure instead of carrying its own copy.

- Dart plans supported system tables as SystemTableDataSource. Before the
  query runs, the Dart controller attaches the caller's SystemTableAccess
  and gathers the rows from every service with SystemTableQueryClient, as
  the Broker does for native SQL, then plans the query over the inline
  rows. This covers both QueryKit planning and stages planned directly
  from logical nodes.
- Queries on system tables run on a Dart worker embedded in the Broker,
  so they don't need a Historical, and can't read other datasources.
- SqlEngine.supportsSystemTableDataSource lets engines other than native
  opt in per table; Dart supports every registered table.
- SystemTableAuthorization.withAccess attaches row access for both
  QueryLifecycle and Dart. Row access is checked on the planned query,
  so system tables reached through views and subqueries are covered.

Dart honors druid.query.enableDruidEngineForSystemTables: when it is
off, no system-table bindings are installed and Dart reads system tables
through the Broker's Bindable plan like the native engine.

@FrankChen021 FrankChen021 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Fix the query-wide maxScatterGatherBytes accounting before merging. Multiple cluster-scoped system-table leaves each receive a fresh response context, allowing the Broker to materialize more remote rows than the configured query-wide budget.

Reviewed 100 of 100 packet-listed changed files; findings in 1 file. This updated-since-review pass started with the incremental diff, then reconciled it against the full diff and prepared worktree, including system-table resolution, routing, authorization, lifecycle, SQL planning, and related tests.

Validation: git diff --check 33a8c5c0242e70bd5cdfdd41049be2f88fbdc657 1bfd0d3713b3a61df1fd92e6cc6ea820f26fdaa9 -- passed. No build, test, dependency-install, or formatter commands were run; this was a static review.

Severity Findings
P0 0
P1 0
P2 1
P3 0
Total 1

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.

final Iterable<Object[]> nodeRows = scanNodeRows(
nodeRunners,
nodeQuery,
DirectDruidClient.makeResponseContextForQuery(),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve byte accounting across system-table leaves

Finding: Each cluster-scoped system-table leaf creates a fresh response context here. DirectDruidClient records remote response bytes in that context, so joins, unions, or nested queries with multiple system-table leaves reset the counter per leaf and can exceed the outer query's maxScatterGatherBytes budget while all gathered rows are materialized in memory.

Suggestion: Share byte accounting across node scans spawned for the outer query while keeping row-scan counters isolated, and add a multi-leaf guardrail test.

@FrankChen021 FrankChen021 Nov 16, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will leave this maxScatterGatherBytes in future

…sks-mvp

# Conflicts:
#	docs/querying/sql-query-context.md
#	processing/src/test/java/org/apache/druid/query/context/docs/ParameterDocumentationGeneratorTest.java
#	server/src/main/java/org/apache/druid/guice/QueryToolChestModule.java
#	server/src/main/java/org/apache/druid/server/QueryResource.java
#	server/src/test/java/org/apache/druid/server/PerSegmentTimeoutInjectionTest.java
#	services/src/main/java/org/apache/druid/cli/CliCoordinator.java
FrankChen021

This comment was marked as duplicate.

@FrankChen021

Copy link
Copy Markdown
Member Author

@gianm let me know if you have more comments

…sks-mvp

# Conflicts:
#	docs/configuration/index.md

@FrankChen021 FrankChen021 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Each cluster-scoped system-table leaf creates a fresh response context, so QUERY_TOTAL_BYTES_GATHERED and maxScatterGatherBytes are tracked independently per leaf. A query with multiple system-table leaves can therefore exceed its query-wide byte budget while the Broker materializes each result into an InlineDataSource, allowing aggregate memory and network usage to exceed the configured limit.

Reviewed 113 of 113 changed files. Static review only; no build, test, or formatter commands were run.

Severity Findings
P0 0
P1 0
P2 1
P3 0
Total 1

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.

final Iterable<Object[]> nodeRows = scanNodeRows(
nodeRunners,
nodeQuery,
DirectDruidClient.makeResponseContextForQuery(),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Fresh response context resets query-wide scatter/gather budget

Finding: Each cluster-scoped system-table leaf calls makeResponseContextForQuery() here, so its remote Scan responses track QUERY_TOTAL_BYTES_GATHERED independently. A join or query with multiple system-table leaves can therefore consume up to maxScatterGatherBytes per leaf while the Broker materializes every leaf into an InlineDataSource, exceeding the configured query-wide cap.

Suggestion: Share one response context across all cluster-wide leaf gathers, or maintain a single query-wide byte counter, and enforce the limit before materializing each leaf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants