Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/api-reference/json-querying-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,19 @@ Content-Length: 817
```
</details>

## Observe running queries

While a native query is running, you can find it in the list of running queries, `GET /druid/v2/sql/queries`. The list
is served by the Broker and covers every query that the Broker is executing, including the native queries submitted to
`/druid/v2`. Native queries have `"engine": "native"` and a `queryId`, but no `sqlQueryId`.

If the Broker is configured with `druid.server.http.enableRunningQueryText`, you can retrieve the text of a running
query by its `queryId` from `GET /druid/v2/sql/queries/{queryId}/reports`. Query text is not captured by default
because it can include sensitive information.

For the full API description, see [List running queries](sql-api.md#list-running-queries) and
[Get running query details](sql-api.md#get-running-query-details).

## Get segment information for query

Retrieves an array that contains objects with segment information, including the server locations associated with the query provided in the request body.
Expand Down
114 changes: 114 additions & 0 deletions docs/api-reference/sql-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,120 @@ Host: http://ROUTER_IP:ROUTER_PORT

A successful response results in an `HTTP 202` message code and an empty response body.

### List running queries

Returns the queries that are currently running on the server, for each query engine that supports listing its queries.
The native engine and the Dart engine support this API.

Although this API is served under `/druid/v2/sql/`, it is not limited to queries that were submitted with SQL. The
native engine entry includes native queries that were submitted directly to `/druid/v2`, as well as the native queries
that execute SQL statements. Use the `engine` field of each entry to tell which engine reported the query.

For the native engine, the list contains the queries that are running on the server that receives the request. The
native engine runs a single native query per SQL statement, so each SQL query appears as a single entry. The list also
includes native queries that were submitted directly to the native query endpoint, `/druid/v2/`, and queries that the
server runs internally, such as segment metadata queries.

Users with READ permission on the `STATE` resource see all running queries. Other users see only their own queries.

#### URL

`GET` `/druid/v2/sql/queries`

#### Query parameters

* `selfOnly`: If present, returns only queries that are running on this server. If absent, each engine may contact other
servers to build a complete list. The native engine always returns queries that are local to the server.
* `includeComplete`: If present, includes completed queries in the response. The number of completed queries returned is
determined by engine-specific retention settings. The native engine does not retain completed queries.

For the native engine, the response does not include query text. To get the text of a running native query, use its
`sqlQueryId` or `queryId` with the [get running query details](#get-running-query-details) API. Native query text is
only captured when `druid.server.http.enableRunningQueryText` is enabled, because it can include sensitive information.
Entries from the Dart engine include the masked SQL text of the query.

#### Sample request

```shell
curl "http://ROUTER_IP:ROUTER_PORT/druid/v2/sql/queries"
```

#### Sample response

The response contains one entry per running query. Engine-specific fields are included for each engine. For the native
engine, `queryId` is the ID to use with the cancel API for native queries, and `sqlQueryId` is the ID to use with the
cancel API for SQL queries.

```json
{
"queries": [
{
"engine": "native",
"queryId": "b3a4a4a1-4e39-4a01-a4d7-66f5e2f49c54",
"sqlQueryId": "request01",
"queryType": "timeseries",
"datasources": ["wikipedia"],
"identity": "user",
"authenticator": "basic",
"startTime": "2026-11-26T06:11:46.887Z",
"state": "RUNNING"
}
]
}
```

### Get running query details

Returns the details of a single query, including its query text, for each SQL engine that supports query reports. The
native engine and the Dart engine support this API.

For the native engine, the query can be looked up by its `sqlQueryId` or by its `queryId`, as returned by the
[list running queries](#list-running-queries) API. This also works for native queries that were submitted directly to
`/druid/v2`, which have a `queryId` but no `sqlQueryId`. The query text is only included when
`druid.server.http.enableRunningQueryText` is enabled on the server. Queries that are no longer running cannot be
looked up with this API.

Users with READ permission on the `STATE` resource see any query. Other users can only look up their own queries, and
get `404` for other users' queries.

#### URL

`GET` `/druid/v2/sql/queries/{queryId}/reports`

#### Query parameters

* `selfOnly`: If present, checks this server only. The native engine always answers from the local server.

#### Sample request

```shell
curl "http://ROUTER_IP:ROUTER_PORT/druid/v2/sql/queries/b3a4a4a1-4e39-4a01-a4d7-66f5e2f49c54/reports"
```

#### Sample response

For the native engine, the response contains the query details in `query`, including `sql` and `nativeQuery` when
captured, and an empty `report`.

```json
{
"query": {
"engine": "native",
"queryId": "b3a4a4a1-4e39-4a01-a4d7-66f5e2f49c54",
"sqlQueryId": "request01",
"queryType": "timeseries",
"datasources": ["wikipedia"],
"identity": "user",
"authenticator": "basic",
"sql": "SELECT COUNT(*) AS c FROM wikipedia",
"nativeQuery": "{\"queryType\":\"timeseries\",...}",
"startTime": "2026-11-26T06:11:46.887Z",
"state": "RUNNING"
},
"report": {}
}
```

### Query output format

The following table shows examples of how Druid returns the column names and data types based on the result format and the type request.
Expand Down
3 changes: 2 additions & 1 deletion docs/configuration/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1638,6 +1638,7 @@ Druid uses Jetty to serve HTTP requests.
|`druid.server.http.maxRequestHeaderSize`|Maximum size of a request header in bytes. Larger headers consume more memory and can make a server more vulnerable to denial of service attacks.|8 * 1024|
|`druid.server.http.headerCacheSize`|Size of the cache Jetty keeps on each client connection to avoid re-parsing request headers that repeat across requests on that connection. Disabled (0) by default because the parsing it saves is negligible compared to the work of serving a Druid request, and each connection that uses the cache holds extra heap for as long as it stays open. Most deployments should leave this at 0.|0|
|`druid.server.http.contentSecurityPolicy`|Content-Security-Policy header value to set on each non-POST response. Setting this property to an empty string, or omitting it, both result in the default `frame-ancestors: none` being set.|`frame-ancestors 'none'`|
|`druid.server.http.enableRunningQueryText`|Whether to capture the text of running queries, so that it can be returned by the [get running query details](../api-reference/sql-api.md#get-running-query-details) API. When enabled, each process keeps the native query, and the SQL text when the query came in through the SQL layer, of the queries that are running on it. The API is served by the Broker, so this exposes the query text of the queries that are running on the Broker. Query text can include sensitive information, so enable this only when needed.|false|

##### Processing

Expand Down Expand Up @@ -1956,7 +1957,7 @@ The Druid SQL server is configured through the following properties on the Broke
|`druid.sql.planner.useNativeQueryExplain`|If true, `EXPLAIN PLAN FOR` will return the explain plan as a JSON representation of equivalent native query(s), else it will return the original version of explain plan generated by Calcite. It can be overridden per query with `useNativeQueryExplain` context key.|true|
|`druid.sql.planner.maxNumericInFilters`|Max limit for the amount of numeric values that can be compared for a string type dimension when the entire SQL WHERE clause of a query translates to an [OR](../querying/filters.md#or) of [Bound filter](../querying/filters.md#bound-filter). By default, Druid does not restrict the amount of numeric Bound Filters on String columns, although this situation may block other queries from running. Set this property to a smaller value to prevent Druid from running queries that have prohibitively long segment processing times. The optimal limit requires some trial and error; we recommend starting with 100. Users who submit a query that exceeds the limit of `maxNumericInFilters` should instead rewrite their queries to use strings in the `WHERE` clause instead of numbers. For example, `WHERE someString IN (‘123’, ‘456’)`. If this value is disabled, `maxNumericInFilters` set through query context is ignored.|`-1` (disabled)|
|`druid.sql.approxCountDistinct.function`|Implementation to use for the [`APPROX_COUNT_DISTINCT` function](../querying/sql-aggregations.md). Without extensions loaded, the only valid value is `APPROX_COUNT_DISTINCT_BUILTIN` (a HyperLogLog, or HLL, based implementation). If the [DataSketches extension](../development/extensions-core/datasketches-extension.md) is loaded, this can also be `APPROX_COUNT_DISTINCT_DS_HLL` (alternative HLL implementation) or `APPROX_COUNT_DISTINCT_DS_THETA`.<br /><br />Theta sketches use significantly more memory than HLL sketches, so you should prefer one of the two HLL implementations.|`APPROX_COUNT_DISTINCT_BUILTIN`|
|`druid.sql.planner.enableSysQueriesTable`|**Experimental.** Whether to enable the [`sys.queries` table](../querying/sql-metadata-tables.md#queries-table), which provides information about currently running and recently completed SQL queries. Currently only queries from the Dart (MSQ) engine are shown.|false|
|`druid.sql.planner.enableSysQueriesTable`|**Experimental.** Whether to enable the [`sys.queries` table](../querying/sql-metadata-tables.md#queries-table), which provides information about currently running and recently completed SQL queries. Queries from the Dart (MSQ) engine and the native engine are shown. The native engine only shows queries that are currently running on the Broker.|false|

:::info
Previous versions of Druid had properties named `druid.sql.planner.maxQueryCount` and `druid.sql.planner.maxSemiJoinRowsInMemory`.
Expand Down
45 changes: 40 additions & 5 deletions docs/querying/sql-metadata-tables.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,18 +381,19 @@ WHERE deprecation IS NOT NULL

:::info
The `sys.queries` table is an experimental feature. You must enable it by setting the runtime property
`druid.sql.planner.enableSysQueriesTable=true` on Broker processes. The main reason this table is experimental
is that it only shows queries from the [Dart](dart.md) engine, which is also experimental.
`druid.sql.planner.enableSysQueriesTable=true` on Broker processes. The table only shows queries from SQL engines
that support listing their queries: the [Dart](dart.md) engine (`msq-dart`) and the native engine (`native`).
Dart is also experimental.
:::

The queries table provides information about currently running and recently completed SQL queries.

|Column|Type|Notes|
|------|-----|-----|
|id|VARCHAR|Execution ID for the query. For Dart queries, this is the `dartQueryId`.|
|engine|VARCHAR|SQL engine that executed the query, e.g., `msq-dart`|
|id|VARCHAR|Execution ID for the query. For Dart queries, this is the `dartQueryId`. For native engine queries, this is the native query ID.|
|engine|VARCHAR|SQL engine that executed the query, e.g., `msq-dart` or `native`|
|state|VARCHAR|Query status: `ACCEPTED`, `RUNNING`, `SUCCESS`, `FAILED`, or `CANCELED`|
|info|VARCHAR|JSON-serialized query information including `sqlQueryId`, `sql`, `identity`, `startTime`, and other engine-specific details|
|info|VARCHAR|JSON-serialized query information including `sqlQueryId`, `identity`, `startTime`, and other engine-specific details. Dart engine entries also include `sql`; native engine entries do not include query text.|

For example, to retrieve all recently completed Dart queries:

Expand All @@ -409,3 +410,37 @@ WHERE
See `druid.msq.dart.controller.maxRetainedReportCount` and `druid.msq.dart.controller.maxRetainedReportDuration`
for details on how long completed queries are retained.
:::

#### Native engine queries

For the native engine, the queries table lists the queries that are currently executing on the Broker that runs the
query. Completed queries are not retained, so `state` is always `RUNNING` for native engine queries. The `info` column
contains the following fields:

|Field|Notes|
|-----|-----|
|`engine`|Engine that is running the query, always `native`.|
|`state`|State of the query, always `RUNNING`.|
|`queryId`|Native query ID. This is the ID to use with the cancel API, `DELETE /druid/v2/{queryId}`.|
|`sqlQueryId`|`sqlQueryId` of the SQL query that this native query belongs to, when the query came in through the SQL layer. This is the ID to use with the cancel API, `DELETE /druid/v2/sql/{sqlQueryId}`.|
|`queryType`|Native query type, such as `timeseries`, `topN`, or `groupBy`.|
|`datasources`|Names of the datasources queried by this native query.|
|`identity`|Identity of the user that submitted the query. Only included when the user has READ permission on the `STATE` resource.|
|`authenticator`|Authenticator that authenticated `identity`. Only included when the user has READ permission on the `STATE` resource.|
|`startTime`|Time at which the query started executing on this Broker.|

The `info` column does not include query text. To get the text of a running native query, use its `queryId` or
`sqlQueryId` with the [get running query details](../api-reference/sql-api.md#get-running-query-details) API. Query
text is only captured when `druid.server.http.enableRunningQueryText` is enabled.

The native engine runs a single native query per SQL statement, so a SQL query that uses the native engine appears as a
single row. Native queries that were submitted directly to `/druid/v2/`, and queries that the server runs internally,
also appear in the table, and have no `sqlQueryId`.

For example, to retrieve all native engine queries that are currently running:

```sql
SELECT id, "info"
FROM sys.queries
WHERE engine = 'native'
```
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,9 @@ public GetQueryReportResponse getQueryReport(
);

for (final GetQueryReportResponse otherReport : otherReports) {
// Check for non-null report with non-null content (a 404 response returns GetReportResponse with null fields)
if (otherReport != null && otherReport.getQueryInfo() != null) {
// Check for non-null report with non-null content (a 404 response returns GetReportResponse with null fields).
// Another engine, such as the native engine, may answer for the same query ID, so check the type.
if (otherReport != null && otherReport.getQueryInfo() instanceof DartQueryInfo) {
infoAndReport = new QueryInfoAndReport(
(DartQueryInfo) otherReport.getQueryInfo(),
otherReport.getReportMap(),
Expand Down
30 changes: 30 additions & 0 deletions server/src/main/java/org/apache/druid/server/QueryLifecycle.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ public class QueryLifecycle
private final AuthConfig authConfig;
private final PolicyEnforcer policyEnforcer;
private final QueryConfigSnapshot configSnapshot;
private final RunningQueryRegistry runningQueryRegistry;
private final long startMs;
private final long startNs;

Expand All @@ -108,6 +109,13 @@ public class QueryLifecycle

@MonotonicNonNull
private Query<?> baseQuery;

/**
* SQL text of this query, when it came in through the SQL layer. Null for native queries.
*/
@Nullable
private String sqlText;

/**
* Context keys as received, i.e. the candidate set for {@link AuthConfig#contextKeysToAuthorize}.
*/
Expand All @@ -124,6 +132,7 @@ public QueryLifecycle(
final AuthConfig authConfig,
final PolicyEnforcer policyEnforcer,
final QueryConfigSnapshot configSnapshot,
final RunningQueryRegistry runningQueryRegistry,
final long startMs,
final long startNs
)
Expand All @@ -137,6 +146,7 @@ public QueryLifecycle(
this.authConfig = authConfig;
this.policyEnforcer = policyEnforcer;
this.configSnapshot = configSnapshot;
this.runningQueryRegistry = runningQueryRegistry;
this.startMs = startMs;
this.startNs = startNs;
}
Expand Down Expand Up @@ -174,6 +184,22 @@ public <T> QueryResponse<T> runSimple(
@Nullable final Set<String> clientProvidedQueryContextKeys
)
{
return runSimple(query, authenticationResult, authorizationResult, clientProvidedQueryContextKeys, null);
}

/**
* As {@link #runSimple(Query, AuthenticationResult, AuthorizationResult, Set)}, but also takes the SQL text of the
* query, for the running query registry. See {@link RunningQueryRegistry}.
*/
public <T> QueryResponse<T> runSimple(
final Query<T> query,
final AuthenticationResult authenticationResult,
final AuthorizationResult authorizationResult,
@Nullable final Set<String> clientProvidedQueryContextKeys,
@Nullable final String sqlText
)
{
this.sqlText = sqlText;
initialize(query, clientProvidedQueryContextKeys);

final Sequence<T> results;
Expand Down Expand Up @@ -417,6 +443,8 @@ public <T> QueryResponse<T> execute()
{
transition(State.AUTHORIZED, State.EXECUTING);

runningQueryRegistry.register(baseQuery, sqlText, authenticationResult);

final ResponseContext responseContext = DirectDruidClient.makeResponseContextForQuery();

@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -450,6 +478,8 @@ public void emitLogsAndMetrics(
return;
}

runningQueryRegistry.unregister(baseQuery.getId());

if (state == State.DONE) {
log.warn("Tried to emit logs and metrics twice for query[%s]!", baseQuery.getId());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.apache.druid.server;

import com.google.common.annotations.VisibleForTesting;
import com.google.inject.Inject;
import org.apache.druid.client.BrokerViewOfBrokerConfig;
import org.apache.druid.guice.LazySingleton;
Expand Down Expand Up @@ -48,6 +49,7 @@ public class QueryLifecycleFactory
private final AuthConfig authConfig;
private final PolicyEnforcer policyEnforcer;
private final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig;
private final RunningQueryRegistry runningQueryRegistry;

@Inject
public QueryLifecycleFactory(
Expand All @@ -60,7 +62,8 @@ public QueryLifecycleFactory(
final PolicyEnforcer policyEnforcer,
final AuthorizerMapper authorizerMapper,
final QueryConfigProvider queryConfigProvider,
@Nullable final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig
@Nullable final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig,
final RunningQueryRegistry runningQueryRegistry
)
{
this.conglomerate = conglomerate;
Expand All @@ -73,6 +76,39 @@ public QueryLifecycleFactory(
this.authConfig = authConfig;
this.policyEnforcer = policyEnforcer;
this.brokerViewOfBrokerConfig = brokerViewOfBrokerConfig;
this.runningQueryRegistry = runningQueryRegistry;
}

/**
* Constructor used by tests, which do not need a running-query registry.
*/
@VisibleForTesting
public QueryLifecycleFactory(
final QueryRunnerFactoryConglomerate conglomerate,
final QuerySegmentWalker texasRanger,
final GenericQueryMetricsFactory queryMetricsFactory,
final ServiceEmitter emitter,
final RequestLogger requestLogger,
final AuthConfig authConfig,
final PolicyEnforcer policyEnforcer,
final AuthorizerMapper authorizerMapper,
final QueryConfigProvider queryConfigProvider,
@Nullable final BrokerViewOfBrokerConfig brokerViewOfBrokerConfig
)
{
this(
conglomerate,
texasRanger,
queryMetricsFactory,
emitter,
requestLogger,
authConfig,
policyEnforcer,
authorizerMapper,
queryConfigProvider,
brokerViewOfBrokerConfig,
new RunningQueryRegistry()
);
}

public QueryLifecycle factorize()
Expand All @@ -93,6 +129,7 @@ public QueryLifecycle factorize()
authConfig,
policyEnforcer,
configSnapshot,
runningQueryRegistry,
System.currentTimeMillis(),
System.nanoTime()
);
Expand Down
Loading