Skip to content

feat: add native engine queries to the running queries API - #20973

Draft
dkhwangbo wants to merge 12 commits into
apache:masterfrom
dkhwangbo:list-running-native-queries
Draft

dkhwangbo wants to merge 12 commits into
apache:masterfrom
dkhwangbo:list-running-native-queries

Conversation

@dkhwangbo

@dkhwangbo dkhwangbo commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Related to #18047.

Description

GET /druid/v2/sql/queries and the sys.queries table already report currently running queries, but only for the Dart engine (#17140, #18923). The native engine has no registry of in-flight queries, so SqlEngine#getQueries returns an empty list for it.

This patch adds native engine support.

Added RunningQueryRegistry

A new server-module singleton tracks the queries that are executing on a process: query ID, sqlQueryId (when the query came in through SQL), query type, datasources, identity, authenticator, and start time.

Registered and unregistered by QueryLifecycle

Queries are added in execute() and removed in emitLogsAndMetrics(). Every completion path goes through emitLogsAndMetrics: the streaming response pusher (success, error, and 304) and the runSimple sequence wrapper. Queries that fail authorization or blocklisting never start, so they are never registered.

Query text is fetched per query, not in the list

The list API returns only query metadata. When druid.server.http.enableRunningQueryText is enabled, the text of a running query (its SQL text when it came in through SQL, and its native query) can be fetched by sqlQueryId or queryId from the existing query report API, GET /druid/v2/sql/queries/{queryId}/reports. That endpoint already serves Dart reports and is engine-pluggable through SqlEngine#getQueryReport, so native support is a matter of implementing that method. The setting is disabled by default because query text can include sensitive information, and the native query is serialized only when a report is requested.

Implemented NativeSqlEngine#getQueries

Registry entries are mapped to NativeQueryInfo. Users with READ permission on the STATE resource see all running queries, including identity details. Other users see only their own queries, with identity and authenticator omitted. This follows the same rules as DartSqlEngine#isOwnQuery.

SqlModule registers the NativeQueryInfo Jackson subtype ("engine": "native").

The list is per-process: the native engine does not contact other servers, so selfOnly has no effect, and completed queries are not retained, so includeComplete has no effect. Both behaviors are documented.

Scope and API location

The list and report APIs live under /druid/v2/sql/ because they are served by SqlResource and shared by all query
engines (SqlEngine#getQueries, SqlEngine#getQueryReport). The native engine reports the native queries that execute
SQL statements and the native queries submitted directly to /druid/v2/; those entries have a queryId but no
sqlQueryId. The docs now say this explicitly, the native query API docs link to these endpoints, and the SqlResource
javadoc notes that the API is not limited to SQL. Keeping the existing paths avoids duplicating or moving an API that
the Dart engine and the console already use.

Public API, configuration, and endpoints

  • Endpoint behavior: GET /druid/v2/sql/queries keeps the same response shape (GetQueriesResponse) and now also
    contains entries from the native engine. Native entries use the existing QueryInfo shape with a new subtype
    (NativeQueryInfo) and a new engine value, native.
  • Endpoint behavior: GET /druid/v2/sql/queries/{queryId}/reports is an existing endpoint that now also answers for
    native engine queries. For native queries, {queryId} can be the sqlQueryId or the native queryId, and the
    response is {"query": {...}, "report": {}}.
  • Configuration: new runtime property druid.server.http.enableRunningQueryText, default false. When true, the
    per-query report includes sql and nativeQuery for native queries. The list API never includes query text.
  • Metrics: none added.
  • Extension APIs: no new or changed @PublicApi or @ExtensionPoint. SqlEngine#getQueryReport is implemented for
    the native engine; the default implementation and the Dart implementation are unchanged except for a type check on
    peer responses.

Compatibility and rolling updates

  • No on-wire protocol or metadata format changes. The new fields are additive JSON, and existing clients ignore them.
  • Rolling updates are safe. During a mixed-version rollout, old Brokers simply do not report native queries, and the
    report endpoint keeps returning 404 for native queries there, since the previous behavior was to return the Dart
    engine's answer only.
  • No change to query execution, scheduling, or results.

Concurrency

RunningQueryRegistry is used by two kinds of threads: query execution threads call register when a query starts and
unregister when it finishes, and HTTP threads call getAll to build the API response. All state lives in a single
ConcurrentHashMap; there is no additional locking, no shared mutable state outside the map, and no ordering
requirement between readers and writers. getAll takes a snapshot of the map and returns immutable entries, so a slow
API call never blocks query execution, and a query that finishes while the list is being built simply disappears from
the next call. NativeSqlEngine#getQueryReport serializes a query only when a report is requested; the query object it
reads is not mutated after execution starts.

Design notes

  • Why not use QueryScheduler? It already tracks query IDs in queryFutures and queryDatasources, but those maps are documented as racy, are only populated on some code paths (CachingClusteredClient registers only in the parallel-merge branch), and are cleared when the last result future completes, which can happen before the response has been fully written. They also carry no identity or start time. A registry driven by QueryLifecycle gives one complete lifecycle for every query that actually starts executing.
  • Why is query text a separate lookup? Putting text in the list would make every poll return the full text of every running query, which can be very large for native queries with big filters. Fetching it per query keeps the list small and only pays the serialization cost when a client asks for one query. Users still need permission to see the query: without READ permission on the STATE resource, other users' queries return 404.

Release note

GET /druid/v2/sql/queries and sys.queries now include queries that are running on the native engine, with their query type, datasources, identity, and start time. Previously, both only reported Dart queries. Operators who enable the new druid.server.http.enableRunningQueryText property can fetch the SQL text and the native query of a running native query from GET /druid/v2/sql/queries/{queryId}/reports.

Testing

  • Unit tests: RunningQueryRegistryTest (including query text capture and serialization failure), NativeSqlEngineTest (mapping, authorization filtering, JSON serialization through SqlModule), QueryLifecycleTest#testRunSimple_registersRunningQuery.
  • Resource-level test: SqlResourceTest#testListRunningQueries (STATE READ users see all queries; other users see only their own).
  • End-to-end test: NativeSqlEngineRunningQueriesTest runs a real SQL query through SqlResource with the real planner and segment walker, and verifies that the query is listed without text while it executes, that its SQL text and native query are available from the report API, and that it is gone afterwards.
  • Full affected test sets pass:
    • druid-server: RunningQueryRegistryTest, QueryLifecycleTest, QueryResourceTest, PerSegmentTimeoutInjectionTest, ServerConfigTest (82 tests).
    • druid-sql: NativeSqlEngineTest, NativeSqlEngineRunningQueriesTest, SqlResourceTest (79 tests).
    • druid-msq: DartSqlEngineTest, DartSqlResourceTest (22 tests).
  • Checkstyle, forbidden-apis, spotbugs, and -DstrictCompile (ErrorProne) are clean for the changed modules.
  • Manual verification on a local cluster built from this branch: a native query submitted to /druid/v2/ appears in GET /druid/v2/sql/queries without sqlQueryId, its text is returned by the report API when druid.server.http.enableRunningQueryText is enabled, and it appears in sys.queries; unknown query IDs return 404.

Reviewer notes

  • This PR adds HTTP endpoint behavior and a runtime configuration property, so it likely needs the Design Review
    label. It also has user-visible impact, so it likely needs the Release Notes label. The author does not have label
    permissions, so a committer will need to add them.
  • Tracking issue: Support listing running queries for native/MSQ #18047 was closed as not planned. If a new issue is required for the feature/change process, I can
    file one and link it here.
Key changed/added classes in this PR
  • server/src/main/java/org/apache/druid/server/RunningQueryRegistry.java (new)
  • server/src/main/java/org/apache/druid/server/QueryLifecycle.java
  • server/src/main/java/org/apache/druid/server/QueryLifecycleFactory.java
  • server/src/main/java/org/apache/druid/server/initialization/ServerConfig.java
  • sql/src/main/java/org/apache/druid/sql/calcite/run/NativeSqlEngine.java
  • sql/src/main/java/org/apache/druid/sql/http/NativeQueryInfo.java (new)

Self-review checklist

  • been self-reviewed.
    • using the concurrency checklist. The registry documents its threading
      model, and readers never block writers.
  • added documentation for new or modified features or behaviors.
  • a release note entry in the PR description.
  • added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
  • added or updated version, license, or notice information in licenses.yaml. No dependencies
    were added or changed.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar
    reader.
  • added unit tests or modified existing tests to cover new code paths, ensuring the threshold for
    code coverage is met.
  • added integration tests. The end-to-end test in NativeSqlEngineRunningQueriesTest runs a real SQL query through
    SqlResource with the real planner and segment walker, which covers the API behavior without a separate integration
    test module.
  • been tested in a test Druid cluster. Verified on a local cluster built from this branch: a native query submitted
    to /druid/v2/ appears in the list without sqlQueryId, its text is returned by the report API, and it appears in
    sys.queries.

Add RunningQueryRegistry, which tracks the queries that are executing on a
process along with their identity, start time, and datasources. Queries are
registered when execution starts, and removed when logs and metrics are
emitted, in QueryLifecycle.

Implement SqlEngine#getQueries for the native engine, so that
GET /druid/v2/sql/queries and sys.queries report queries that are running on
the native engine. Users without READ permission on the STATE resource only
see their own queries, without identity details.

Register the NativeQueryInfo Jackson subtype in SqlModule, and document the
GET /druid/v2/sql/queries endpoint and the native engine rows of sys.queries.
@dkhwangbo dkhwangbo changed the title Add native engine queries to the running queries API feat: add native engine queries to the running queries API Nov 26, 2026
QueryLifecycle-driven identity filtering now follows the same shape as
DartSqlEngine: build the full list, then filter it for callers without READ
permission on the STATE resource.
Remove equals, hashCode, and toString from RunningQueryRegistry.Entry and
NativeQueryInfo, which are not needed by the API, and use a Comparator for
the registry snapshot. Add tests for a query without an ID, for unregistering
unknown IDs, and for callers that have no identity or no authenticator.
@dkhwangbo
dkhwangbo force-pushed the list-running-native-queries branch from 1888148 to 0bd2b95 Compare November 26, 2026 08:31
Add druid.server.http.enableRunningQueryText, which makes the running query
registry keep the SQL text and the native query of each running query, and
return them from the running queries API and sys.queries. The setting is
disabled by default because query text can include sensitive information.

The SQL layer passes the SQL text to QueryLifecycle, and the native query is
serialized when the query is registered. Use generic test identities instead
of personal ones.
@dkhwangbo
dkhwangbo force-pushed the list-running-native-queries branch from e55553b to ec1910c Compare November 26, 2026 08:57
Include enableRunningQueryText in ServerConfig equals, hashCode, and toString,
and thread it through the all-args constructor and the copies that
CliIndexerServerModule makes, so that EqualsVerifier and config dumps see it.

Stop serializing native queries when they are registered. The registry now
keeps a reference to the running query and NativeSqlEngine serializes it when
the list is read, so processes that do not serve the API do no extra work.

Clarify in the configuration docs that the list is served by the Broker and
that SQL text is captured only for queries submitted through the SQL layer.
The list running queries API now returns only query metadata. When
druid.server.http.enableRunningQueryText is enabled, the text of a running query
can be fetched by its sqlQueryId or queryId from the existing query report API,
GET /druid/v2/sql/queries/{queryId}/reports, which already serves Dart reports.

NativeSqlEngine implements getQueryReport by looking the query up in the running
query registry, with the same STATE READ rules as the list API.
Look up the query and check whether the caller may see it in the same loop, so
that a collision on a user-provided ID does not return another query or hide
the caller's own query.

DartSqlEngine now checks the type of the query info in a peer response, since
the native engine can also answer for the same query ID.

Document that Dart entries include SQL text in the list, and that native entries
do not include query text in sys.queries.
@github-actions github-actions Bot added Area - Batch Ingestion Area - MSQ For multi stage queries - https://github.com/apache/druid/issues/12262 labels Nov 30, 2026
The endpoint lives under /druid/v2/sql/ because it is served by SqlResource and
shared by all engines, but the native engine also reports native queries
submitted directly to /druid/v2/. Say so in the API docs, in the native query
API docs, and in the SqlResource javadoc, so that the endpoint is not mistaken
for a SQL-only API.
Record that the registry is used by query execution threads and HTTP threads, that
all state lives in a ConcurrentHashMap, and that the returned entries are immutable.
This is what the repository's concurrency checklist asks for.
CodeQL flagged the previous shape, where the ownership check and the redacted
view were only computed for some queries depending on the caller's permission.
Compute both for every query and only make the selection conditional, so the
visibility decision does not depend on which queries the caller owns.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area - Batch Ingestion Area - Documentation Area - MSQ For multi stage queries - https://github.com/apache/druid/issues/12262 Area - Querying

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants