feat(sql): add experimental native query support for system tables #20183
Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.
@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
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)
Are these not needed? Wondering if this is general cleanup, outside the scope of this PR
These javadocs here seem like a repeat of the SQL in the test and the test name. Can be removed.
Same - the javadocs seem redundant here and a few other tests below
I think this web-console query would be a good candidate to benchmark
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.
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.
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.
DECOUPLED planner support in a separate change, since COUPLED is the default planner strategy today (and DECOUPLED is currently undocumented).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.
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.
Thanks for these changes @FrankChen021! Thesys.tables have historically been slow and less performant, especiallysys.segmentsandsys.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 forsys.tasksandsys.server_properties, isolating the appropriate wirings, filter pushdown mechanisms and tests to make it work for each table.
* HandleDECOUPLEDplanner 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:
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.
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.
Addressed on this PR branch: the default and rolling-upgrade guidance now follows the native-planning/fallback explanation, before the route-header paragraph.
Addressed in the stacked sys.tasks PR: the repeated SQL Javadocs in this test were removed. See FrankChen021/druid#198.
Addressed in the stacked sys.tasks PR: the redundant test Javadocs were removed. See FrankChen021/druid#198.
@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.
[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.
| 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)
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 -->
🟢 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)
🟢 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)
🟢 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)
🟡 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.
[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.
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.
[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.
🟡 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.
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.
🟢 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)
🟢 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)
🟡 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.
[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.
[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.
🟡 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.
[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.
🟡 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.
Leave this in a follow up PR, reaons: the case that cancels a query on system table is not common
[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.
🟡 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.
🟢 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)
@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.
IMO useNativeEngineForSystemTables is a better name for this parameter.
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.
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.
This paragraph probably isn't necessary, it seems like it's about an internal detail, not really about SQL.
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:
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.
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.
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:
/druid/v2/ calls properly respecting authorization (including verifying that authorizeSystemTablesDirectly and STATE READ are checked) for all values of X-Druid-Native-Query-Route/druid/v2/ path (similar to test_serverPropertiesTable_hiddenProperties)QueryLifecycle would also be useful. For server_propertiesJoins: 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.
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.
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?
🟢 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)
@gianm Thank you for the review. I replied some questions you raised. For others, I will address them in a new commit.
@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.ServerPropertiesTableDataProviderTest and NativeSysServerPropertiesQueryTest#testHiddenPropertiesAreNotReturnedByNativeQueries (Broker fan-out, Broker-local, Router-local).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.
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.
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.
@FrankChen021 please let me know what you think of my comments, and I can do another round of review.
@gianm Thanks for the comments. The fix is in. And here're my replies:
I requested the system property because to me, adding asystemTabledatasource 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)
@gianm the feature flag you asked for is in. Can you do another round of review?
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.
@gianm let me know if you have more comments
FrankChen021
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.| 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
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.</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 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
1. Register a
SystemTableDescriptorwith the table name, the node roles that own its rows, the row signature, and aSystemTableRowAuthorizer.2. Register a
SystemTableDataProvideron those nodes. It may declare pushdown columns throughgetPushdownColumns(), whose filters are passed togetRows(List<Filter>).3. Make the Calcite table implement
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.</details>
<details>
<summary><strong>Authorization</strong></summary>
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.</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:
Current 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.</details>
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: