Repository navigation
feat(sql): add experimental native query support for system tables - #20183
FrankChen021 wants to merge 41 commits into
Conversation
|
@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 |
abhishekrb19
left a comment
There was a problem hiding this comment.
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.tasksandsys.server_properties, isolating the appropriate wirings, filter pushdown mechanisms and tests to make it work for each table. - Handle
DECOUPLEDplanner support in a separate change, sinceCOUPLEDis the default planner strategy today (andDECOUPLEDis 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:
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. |
Very cool. I will try to have a look soon. |
…asks-mvp # Conflicts: # server/src/test/java/org/apache/druid/client/DirectDruidClientTest.java
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.
…sks-mvp # Conflicts: # services/pom.xml # services/src/test/java/org/apache/druid/cli/MainTest.java
|
@gianm the feature flag you asked for is in. Can you do another round of review? |
gianm
left a comment
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
I think it would be cleaner and more maintainable to add a method getResources() to DataSource, and use that rather than getTableNames() for authorization.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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
SystemTableDataSourceprocessable, add aSystemTableSegmentWranglerthat createsSystemTableSegment. SystemTableSegmentcontains theSystemTableDataProvider.SystemTableSegment#assupplies aSystemTableCursorFactory, which pushes down filters and required columns fromCursorBuildSpec#getFilterandCursorBuildSpec#getPhysicalColumns.- No need for
DataSourceQueryHandlersince the logic ends up inSystemTableSegmentWrangler. - No need for
SystemTablePushdownFilter, as that's handled in theSystemTableDataProvider.
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:
NativeQueryMakerresolves system table datasources to inline datasources withSystemTableQueryClient, and then runs the query as normal.- The
/druid/v2/routes on each server only need to supportlocalmode. - 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/
SystemTableCursorFactoryapplies authorization-based row filtering, such as only showing tasks that the user is supposed to see.- A non-serializing authorization object is attached to
SystemTableDataSourceduringQueryLifecycle#authorize(this is one of the sys-table-specific things that would need to remain) - The
SystemTableSegmentWranglerexpects to see that non-serializing authorization object, and bakes it into theSystemTableSegmentso it can be passed to theSystemTableCursorFactory.
Suggestion for the authorization object:
record SystemTableAccess(@Nullable Predicate<Object[]> rowPredicate)There was a problem hiding this comment.
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:
-
QueryLifecycleno longer executes queries itself.DataSourceQueryHandleris removed, and every query goes to the configuredQuerySegmentWalker.QueryLifecycleonly attaches the caller's row access to system tables during authorization. -
SystemTableDataSourceis read throughSystemTableSegmentWrangler, 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 asystemTabledatasource returns only the contacted service's rows. Only SQL fans out:NativeQueryMakermarks the system tables of a SQL query with the cluster scope, and the Broker'sSystemTableGatheringQuerySegmentWalkergathers 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.
NativeQueryEngineModulebindsSystemTableQuerySegmentWalkeron non-Broker services. It sends system-table queries to aLocalQuerySegmentWalker, 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 asystemTabledatasource and return 501 for other queries. -
The access object can't get lost.
SystemTableAccessisn't serialized, andSystemTableDataSourceis 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. Forserver_properties, the all-or-nothingSTATE READcheck stays in authorization, so it needs no row predicate.
There was a problem hiding this comment.
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
serveris pushed down to each service, so that query reads only one service's rows and is about twice as fast asCOUNT(*)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.
Added. The native system-table auth test now also queries the Coordinator and Overlord on |
…sks-mvp # Conflicts: # server/src/main/java/org/apache/druid/server/QueryResource.java
Master's checkstyle now rejects /// documentation comments.
…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.
…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
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
left a comment
There was a problem hiding this comment.
🟡 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(), |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
|
@gianm let me know if you have more comments |
…sks-mvp # Conflicts: # docs/configuration/index.md
FrankChen021
left a comment
There was a problem hiding this comment.
🟡 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(), |
There was a problem hiding this comment.
[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.
Description
This PR introduces experimental, opt-in native-query execution for supported
sys.*tables and enables it forsys.server_properties. The SQL interpreter (Bindable) path remains the default.Two switches control the feature:
druid.query.enableDruidEngineForSystemTables(defaultfalse), 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.useDruidEngineForSystemTables(defaultfalse), which opts a SQL query in. It applies only when the resolved SQL engine isnativeand 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:
This PR represents supported system tables as a
systemTabledatasource (SystemTableDataSource) that the native engine reads like any other datasource.sys.server_propertiesExecution path
A native query on a
systemTabledatasource reads only the rows of the service that receives it. Only SQL fans out.On every service, a
systemTabledatasource is read throughSystemTableSegmentWrangler, which turns the table'sSystemTableDataProviderinto a segment:How each service serves
/druid/v2/for system tables:SystemTableQueryResource, which accepts only Scan queries on asystemTabledatasource 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 aDruidTablebacked bySystemTableDataSource. Both planner strategies are supported:DruidTableScanRuleconverts the system table directly.DruidBindableTableScanRulerebuilds the native project/filter/scan plan when Calcite has already embedded filters or projections in aBindableTableScan.NativeQueryMakermarks 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
SystemTableDescriptorwith the table name, the node roles that own its rows, the row signature, and aSystemTableRowAuthorizer.SystemTableDataProvideron those nodes. It may declare pushdown columns throughgetPushdownColumns(), whose filters are passed togetRows(List<Filter>).SystemTableDataSourceTable.No new HTTP resource, RPC client or Broker query branch is needed.
ServerPropertiesTableDataProviderdeclaresserverandservice_nameas pushdown columns: a service that doesn't match a filter on them returns no rows before enumerating its properties.Native query module
NativeQueryEngineModuleis 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(...)andwithOverrideModule(...)for role-specific bindings, such as the Coordinator's segment schema cache.withQueryResourceModule(...)for the Broker's and Router's query resources.Authorization
QueryLifecycleauthorizes system tables and attaches the caller's row access through the table'sSystemTableRowAuthorizer. A system table is processable only once its access is attached, so no path can read rows without authorization.druid.auth.authorizeSystemTablesDirectlyauthorizes system tables asSYSTEM_TABLEresources that requireREAD, in SQL on the Broker and in native queries on every service. It replacesdruid.sql.planner.authorizeSystemTablesDirectly, which is deprecated; the Broker honors either.SYSTEM_TABLEWRITE.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=trueCurrent limitations:
QuerySchedulerlanes or capacity, and a cancel during the fan-out does not interrupt node scans that are already running.SYSTEM_TABLEWRITE, even whendruid.auth.authorizeSystemTablesDirectlyis off.Validation
sys.server_propertiesacross all service roles, with the feature disabled, and with basic authentication (SYSTEM_TABLEandSTATEpermissions).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.enableDruidEngineForSystemTableson all services, then set theuseDruidEngineForSystemTablesquery context parameter. The initial implementation supportssys.server_properties. Native queries on asystemTabledatasource sent to a service's/druid/v2/endpoint read that service's rows.druid.auth.authorizeSystemTablesDirectlyreplaces the deprecateddruid.sql.planner.authorizeSystemTablesDirectly.This PR has: