Skip to content

Commit 9204af9

Browse files
feat(ppl): Report completed PPL queries to Query Insights Top N (#5760)
--------- Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
1 parent 6a87e96 commit 9204af9

32 files changed

Lines changed: 3175 additions & 106 deletions
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.executor;
7+
8+
/**
9+
* Per-query accounting of the CPU and memory a query uses on the SQL plugin's own threads.
10+
*
11+
* <p>OpenSearch's task resource tracking only brackets threads on its task-aware pools, which a
12+
* plugin pool cannot opt into, so the engine brackets its own threads instead. It does so through
13+
* this interface rather than calling core directly: whether and how a stretch of work is measured
14+
* is the task's decision, not the engine's.
15+
*
16+
* <p>It lives in core although only the opensearch module calls it ({@code OpenSearchQueryManager},
17+
* {@code ThreadPoolExecutionDispatcher} and {@code BackgroundSearchScanner}), because {@code
18+
* PPLQueryTask} implements it and must not reference opensearch module types: plugins such as
19+
* alerting load that task with only core, ppl and protocol (#5923, checked by {@code
20+
* ThinJarClassesTest}). The plugin module, where the task lives, is not visible to the opensearch
21+
* module either.
22+
*/
23+
public interface ThreadResourceAccounting {
24+
25+
/**
26+
* Starts measuring the current thread for this query. The returned scope must be closed on the
27+
* same thread when the thread's work for the query ends.
28+
*/
29+
Scope enterThread();
30+
31+
/** Opens a scope for {@code task}, or a no-op scope if the task does no accounting. */
32+
static Scope enter(Object task) {
33+
return task instanceof ThreadResourceAccounting accounting
34+
? accounting.enterThread()
35+
: Scope.NOOP;
36+
}
37+
38+
/** A measured stretch of one thread's work; closing it records the usage. */
39+
interface Scope extends AutoCloseable {
40+
Scope NOOP = () -> {};
41+
42+
@Override
43+
void close();
44+
}
45+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.executor;
7+
8+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
9+
import static org.junit.jupiter.api.Assertions.assertEquals;
10+
import static org.junit.jupiter.api.Assertions.assertSame;
11+
12+
import java.util.concurrent.atomic.AtomicInteger;
13+
import org.junit.jupiter.api.Test;
14+
15+
class ThreadResourceAccountingTest {
16+
17+
@Test
18+
void enterOpensTheTasksOwnScope() {
19+
AtomicInteger closed = new AtomicInteger();
20+
ThreadResourceAccounting.Scope scope = closed::incrementAndGet;
21+
ThreadResourceAccounting task = () -> scope;
22+
23+
ThreadResourceAccounting.Scope entered = ThreadResourceAccounting.enter(task);
24+
25+
assertSame(scope, entered);
26+
entered.close();
27+
assertEquals(1, closed.get());
28+
}
29+
30+
@Test
31+
void enterIsANoOpForATaskThatDoesNoAccounting() {
32+
assertSame(ThreadResourceAccounting.Scope.NOOP, ThreadResourceAccounting.enter(new Object()));
33+
assertSame(ThreadResourceAccounting.Scope.NOOP, ThreadResourceAccounting.enter(null));
34+
assertDoesNotThrow(ThreadResourceAccounting.Scope.NOOP::close);
35+
}
36+
}

‎docs/user/ppl/admin/settings.md‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,4 +493,38 @@ Expected output:
493493
"transient": {}
494494
}
495495
```
496-
496+
497+
498+
## search.insights.top_queries.ppl.enabled
499+
500+
### Version
501+
502+
3.11
503+
504+
### Description
505+
506+
This setting controls whether completed PPL queries are recorded into Query Insights Top N. When enabled, the PPL plugin reports each PPL query it runs through `_plugins/_ppl` to the Query Insights plugin when the query finishes: its query text, latency, CPU, memory, whether it failed, and, on a security-enabled cluster, the requesting user. It also tags the DSL searches the query runs, so Query Insights lists them as the query's sub-queries.
507+
508+
These are not recorded: `explain` (on the `_explain` endpoint or in the query text), `analyze`, asynchronous submissions, queries routed to the analytics engine, queries that fail to parse, and a PPL query that starts inside another one, whose searches belong to the outer query.
509+
510+
1. The default value is false (opt-in).
511+
2. This setting is node scope, matching the rest of the `search.insights.top_queries.*` family.
512+
3. It is dynamic: update it through the cluster settings API, as in the example below.
513+
514+
Note on query text and user identity: the record stores the query as it was submitted, including any literal values in it, the same way Query Insights stores the source of a DSL search. When a security plugin is installed, the record also includes the requesting user (username, roles, backend roles). Who can see these in Top N results is governed by the Query Insights plugin's own RBAC filter, `search.insights.top_queries.filter_by_mode` — default `none` (no per-user filtering), `username` (a user sees only their own queries; admins see all), or `backend_roles`. Set it to `username` or `backend_roles` if other users' queries and identities should not be visible to every Top N reader.
515+
516+
Note on CPU and memory: the PPL plugin reports the CPU time and the bytes allocated by the query's own engine threads, the same values `_tasks` shows for the PPL task. Query Insights adds the CPU and memory of the searches the query ran, so the figures in Top N cover the whole query. OpenSearch records these only while the cluster setting `task_resource_tracking.enabled` is on (the default). With it off, a PPL record reports 0 CPU and 0 memory.
517+
518+
Note: This setting is **registered by the Query Insights plugin** (it belongs to the `search.insights.top_queries.*` family), not by the PPL plugin. The PPL plugin reads its value to decide whether to report. It therefore only takes effect when the Query Insights plugin is installed; when Query Insights is absent the setting is unregistered and PPL reporting is a no-op.
519+
520+
### Example
521+
522+
With the Query Insights plugin installed, you can enable PPL recording like this:
523+
524+
```shell
525+
curl -sS -H 'Content-Type: application/json' \
526+
-X PUT localhost:9200/_cluster/settings \
527+
-d '{"persistent" : {"search.insights.top_queries.ppl.enabled" : "true"}}'
528+
```
529+
530+
This example is not executed as part of the documentation tests because the setting is registered by the Query Insights plugin, which is not installed in the PPL documentation test cluster.

‎integ-test/build.gradle‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,11 @@ configurations.all {
206206

207207
configurations {
208208
zipArchive
209+
// Resolved only by integTestWithQueryInsights, so no other task depends on a Query Insights
210+
// snapshot being published.
211+
queryInsightsZip {
212+
transitive = false
213+
}
209214
}
210215

211216
dependencies {
@@ -239,6 +244,9 @@ dependencies {
239244
// For GeoIP PPL functions
240245
zipArchive group: 'org.opensearch.plugin', name:'geospatial', version: "${opensearch_build}"
241246

247+
// Installed alongside the plugin by integTestWithQueryInsights
248+
queryInsightsZip group: 'org.opensearch.plugin', name:'query-insights', version: "${opensearch_build}"
249+
242250
}
243251

244252
java {
@@ -282,6 +290,17 @@ def getGeoSpatialPlugin() {
282290
}
283291
}
284292

293+
// The published Query Insights snapshot, or a local build via -PqueryInsightsZip=/path/to.zip.
294+
def getQueryInsightsPlugin() {
295+
provider { (RegularFile) (() ->
296+
project.findProperty('queryInsightsZip')
297+
? file(project.findProperty('queryInsightsZip'))
298+
: configurations.queryInsightsZip.asFileTree.matching {
299+
include '**/query-insights*'
300+
}.singleFile )
301+
}
302+
}
303+
285304
// fetch from the feature-build artifact for now (linux/x64 only; for local dev pass -PanalyticsEngineZip=/path instead).
286305
ext.pluginVersion = opensearch_version.tokenize('-')[0]
287306
ext.featureBuildBase = "https://ci.opensearch.org/ci/dbc/feature-build-opensearch/feature-datafusion/latest/linux/x64/tar/builds/opensearch/plugins"
@@ -572,6 +591,23 @@ testClusters {
572591
plugin(getJobSchedulerPlugin())
573592
plugin ":opensearch-sql-plugin"
574593
}
594+
// Query Insights installed, so the PPL -> Query Insights reporting path actually runs.
595+
integTestWithQueryInsights {
596+
testDistribution = 'archive'
597+
plugin(getJobSchedulerPlugin())
598+
plugin(getQueryInsightsPlugin())
599+
plugin ":opensearch-sql-plugin"
600+
setting "plugins.query.datasources.encryption.masterkey", "1234567812345678"
601+
}
602+
// The same, plus the security plugin (added by configureSecurityPlugin below), so records carry
603+
// the requesting user and Top N reads go through Query Insights' RBAC filter.
604+
integTestWithQueryInsightsAndSecurity {
605+
testDistribution = 'archive'
606+
plugin(getJobSchedulerPlugin())
607+
plugin(getQueryInsightsPlugin())
608+
plugin ":opensearch-sql-plugin"
609+
setting "plugins.query.datasources.encryption.masterkey", "1234567812345678"
610+
}
575611
// Smoke test: verify sql loads cleanly alongside analytics-engine.
576612
analyticsEngineCompat {
577613
testDistribution = 'archive'
@@ -848,6 +884,58 @@ task workerPoolSaturationIT(type: RestIntegTestTask) {
848884

849885
check.dependsOn workerPoolSaturationIT
850886

887+
// Asserts that PPL queries are recorded into Query Insights. Not part of `check` yet: the published
888+
// Query Insights snapshot does not include the PPL consumer until that change merges there, so run
889+
// it against a local build until then:
890+
// ./gradlew :integ-test:integTestWithQueryInsights -PqueryInsightsZip=/path/to/query-insights.zip
891+
task integTestWithQueryInsights(type: RestIntegTestTask) {
892+
useCluster testClusters.integTestWithQueryInsights
893+
894+
dependsOn ':opensearch-sql-plugin:bundlePlugin'
895+
896+
systemProperty 'tests.security.manager', 'false'
897+
systemProperty 'project.root', project.projectDir.absolutePath
898+
systemProperty 'defaultQuerySizeLimit', '10000'
899+
systemProperty 'defaultQueryBucketSize', '1000'
900+
systemProperty 'defaultMaxResultWindow', '10000'
901+
doFirst {
902+
systemProperty 'cluster.debug', getDebug()
903+
}
904+
905+
filter {
906+
includeTestsMatching 'org.opensearch.sql.ppl.QueryInsightsRecordingIT'
907+
}
908+
}
909+
910+
// The reporting path on a secured cluster: whose identity a record carries and who can read it
911+
// back. Not part of `check` yet, for the same reason as integTestWithQueryInsights:
912+
// ./gradlew :integ-test:integTestWithQueryInsightsAndSecurity -PqueryInsightsZip=/path/to.zip
913+
task integTestWithQueryInsightsAndSecurity(type: RestIntegTestTask) {
914+
useCluster testClusters.integTestWithQueryInsightsAndSecurity
915+
916+
dependsOn ':opensearch-sql-plugin:bundlePlugin'
917+
918+
// This task installs the security plugin, so its absence is a breakage rather than a skip.
919+
systemProperty 'tests.required.plugins', 'opensearch-security'
920+
systemProperty 'tests.security.manager', 'false'
921+
systemProperty 'project.root', project.projectDir.absolutePath
922+
systemProperty 'defaultQuerySizeLimit', '10000'
923+
systemProperty 'defaultQueryBucketSize', '1000'
924+
systemProperty 'defaultMaxResultWindow', '10000'
925+
doFirst {
926+
systemProperty 'cluster.debug', getDebug()
927+
systemProperty "https", "false"
928+
systemProperty "user", "admin"
929+
systemProperty "password", "admin"
930+
}
931+
932+
filter {
933+
includeTestsMatching 'org.opensearch.sql.security.QueryInsightsRecordingSecurityIT'
934+
}
935+
}
936+
937+
configureSecurityPlugin(testClusters.integTestWithQueryInsightsAndSecurity)
938+
851939
task integTestWithSecurity(type: RestIntegTestTask) {
852940
useCluster testClusters.integTestWithSecurity
853941
useCluster testClusters.remoteIntegTestWithSecurity
@@ -877,6 +965,8 @@ task integTestWithSecurity(type: RestIntegTestTask) {
877965
// Exclude tests that require the analytics engine plugin stack (run separately via analyticsEngineSecurityIT)
878966
filter {
879967
excludeTestsMatching 'org.opensearch.sql.security.AnalyticsEngineSecurityIT'
968+
// Needs Query Insights installed; runs via integTestWithQueryInsightsAndSecurity.
969+
excludeTestsMatching 'org.opensearch.sql.security.QueryInsightsRecordingSecurityIT'
880970
}
881971

882972
systemProperty 'tests.security.manager', 'false'
@@ -1057,6 +1147,9 @@ integTest {
10571147
// Runs on the dedicated workerPoolSaturationIT cluster.
10581148
exclude 'org/opensearch/sql/ppl/WorkerPoolSaturationIT.class'
10591149

1150+
// Needs Query Insights installed; runs via :integ-test:integTestWithQueryInsights.
1151+
exclude 'org/opensearch/sql/ppl/QueryInsightsRecordingIT.class'
1152+
10601153
// Exclude tests that require the analytics engine plugin stack (run separately via dedicated tasks)
10611154
exclude 'org/opensearch/sql/analytics/AnalyticsEngineProfileIT.class'
10621155

@@ -1445,6 +1538,10 @@ task integTestRemote(type: RestIntegTestTask) {
14451538
excludeTestsMatching "org.opensearch.sql.bwc.*IT"
14461539
}
14471540

1541+
// Need Query Insights installed; run via the integTestWithQueryInsights* tasks.
1542+
excludeTestsMatching 'org.opensearch.sql.ppl.QueryInsightsRecordingIT'
1543+
excludeTestsMatching 'org.opensearch.sql.security.QueryInsightsRecordingSecurityIT'
1544+
14481545
if (analyticsEnabled) {
14491546
// Full-text search (search-filter syntax -> Lucene query_string) needs an inverted-index
14501547
// reader that parquet-backed analytics indices lack, so it's unsupported on this route.

0 commit comments

Comments
 (0)