Skip to content

feat: Show PPL queries in Live Queries - #612

Open
KishoreKicha14 wants to merge 7 commits into
opensearch-project:mainfrom
KishoreKicha14:feat/ppl-live-queries
Open

KishoreKicha14 wants to merge 7 commits into
opensearch-project:mainfrom
KishoreKicha14:feat/ppl-live-queries

Conversation

@KishoreKicha14

@KishoreKicha14 KishoreKicha14 commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Description

With opensearch-project/query-insights/pull/699 Live Queries reports a running PPL query as one row: its coordinator task is the PPL task, and its shard_tasks holds the searches it runs and their shard tasks. This page read every row as a DSL search, so a PPL row showed N/A for its index and search type, its query text appeared nowhere, and its searches were listed as shard tasks with the phase indices:data/read/search.

Changes:

  • Query source column: a PPL or DSL badge, and a PPL badge shows the query text on hover. query_source is also a search field.
  • Index of a PPL row: the indices named in its source= clauses, plus any other index its running searches read, so it stays the same while the query is between searches.
  • Flyout of a PPL query: the query text under PPL Query, its searches under Child Search Tasks with the indices each one reads, and their shard tasks under Shard Tasks with the same columns as for a DSL search. Between searches it says that no search is running. A DSL search's flyout is unchanged.
  • A PPL row has no WLM group, because WLM manages only the searches a PPL query runs, so its WLM Group column shows N/A.
Screenshot 2026-10-26 at 6 05 15 PM Screenshot 2026-10-26 at 6 05 44 PM Screenshot 2026-10-26 at 6 06 11 PM

Testing

  • 615 Jest tests pass. The new ones render Live Queries responses captured from a cluster running a PPL join beside a DSL search (cypress/fixtures/stub_live_queries_ppl.json).
  • Prettier and ESLint report no errors, and the plugin builds.
  • I ran it against a single node with security, the SQL plugin and the Query Insights change while slow PPL and DSL queries ran; see the screenshots above.

Issues Resolved

Related: #577 also adds a query source to Live Queries, based on labels from an earlier backend design. This PR reads the PPL task instead, so the two overlap in InflightQueries.tsx and TaskDetailFlyout.tsx.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit abcdec0)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Missing empty-state wrapping

The "No searches running..." / "No active shard tasks..." message is rendered outside the {shardTasks.length > 0 && (...)} block. Previously the empty-state <p> was wrapped inside the conditional that also included the heading. Now, when shardTasks.length === 0 && !taskResourceUsages?.length, the condition becomes true for both PPL (correct) and DSL (also correct), but check that the JSX structure is syntactically valid — the removal of the outer wrapping {task.shard_tasks.length === 0 && ...} guard combined with the new {shardTasks.length > 0 && ( opener may result in mismatched fragments. Verify the final rendered tree still shows the empty-state message for DSL rows with no shard tasks.

{shardTasks.length > 0 && (
  <>
    <EuiTitle size="xs">
      <h4>Shard Tasks</h4>
    </EuiTitle>
    <EuiHorizontalRule margin="xs" />
    <EuiInMemoryTable
      tableCaption="Shard tasks"
      items={shardTasks}
      columns={shardColumns}
      itemId="task_id"
      pagination={{ initialPageSize: 10, showPerPageOptions: false }}
    />
  </>
)}

{task.shard_tasks.length === 0 && !taskResourceUsages?.length && (
  <p>
    {isPpl
      ? 'No searches running at this moment. Refresh to update.'
      : 'No active shard tasks at this moment. Refresh to update.'}
  </p>
)}
Line-continuation parsing bug

In the // comment handler, the code treats a backslash before any character as a two-char escape (i += text[i] === '\\' ? 2 : 1). The intent per the comment is to continue the comment across a line break only when \ precedes \n/\r. As written, any \ inside a // comment consumes the next character unconditionally, which could skip past a legitimate newline terminator if the preceding char is \ followed by a non-newline (then subsequent newline is still found on the next iteration, so likely benign), but if \ is the final char before end-of-text it reads past text.length. Low-impact but worth guarding.

  // A backslash before the line break continues the comment on the next line.
  i += 2;
  while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += text[i] === '\\' ? 2 : 1;
} else if (PPL_QUOTES.includes(c)) {

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to abcdec0

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix line-comment parser skipping newlines

The line-comment handling can advance past a newline when a backslash is followed by
\n/\r, because the loop condition is only checked before the increment. This can
swallow content on the next line. Also, PPL line comments typically do not support
backslash line-continuation; consider removing the continuation logic entirely, or
at minimum re-check bounds and newline after the two-char skip.

public/utils/live-query-utils.ts [74-77]

 } else if (text.startsWith('//', i)) {
-  // A backslash before the line break continues the comment on the next line.
   i += 2;
-  while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += text[i] === '\\' ? 2 : 1;
-} else if (PPL_QUOTES.includes(c)) {
+  while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i++;
Suggestion importance[1-10]: 4

__

Why: The concern about backslash line-continuation potentially skipping past a newline is plausible but minor; PPL line comments likely don't need this behavior. However, the existing tests pass, and the impact is limited to edge cases with backslashes before newlines in comments.

Low

Previous suggestions

Suggestions up to commit af39bdf
CategorySuggestion                                                                                                                                    Impact
General
Guard line-comment scan against end-of-input

The line-comment loop advances by 2 on a backslash but doesn't check that the next
character is a line terminator, so a backslash followed by \n is skipped as
expected, but a backslash as the final character of input can over-advance past
text.length. Also, the condition text[i] !== '\n' means a backslash-newline sequence
is incorrectly consumed as part of the comment body, which is PPL-lexer-specific
behavior that may not be accurate. Validate the lookahead or guard the += 2 to avoid
skipping past end-of-input.

public/utils/live-query-utils.ts [62-64]

 } else if (text.startsWith('//', i)) {
       // A backslash before the line break continues the comment on the next line.
       i += 2;
-      while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += text[i] === '\\' ? 2 : 1;
+      while (i < text.length && text[i] !== '\n' && text[i] !== '\r') {
+        if (text[i] === '\\' && i + 1 < text.length) i += 2;
+        else i++;
+      }
Suggestion importance[1-10]: 3

__

Why: The concern about over-advancing past text.length is minor since the outer while loop condition i < text.length would still terminate correctly on the next iteration. The improvement is a marginal robustness tweak with little practical impact.

Low
Tighten shard-task categorization for PPL flyout

SEARCH_ACTION is 'indices:data/read/search', but shard tasks have actions like
'indices:data/read/search[phase/query]' which start with that prefix. The current
strict equality works, but if any coordinator-level non-search action appeared it
would be miscategorized into Shard Tasks. Consider making the search-task filter
exact-match (already done) and the shard filter explicitly test for the [phase/...]
suffix for robustness.

public/pages/InflightQueries/TaskDetailFlyout.tsx [103-106]

 const childSearchTasks = isPpl ? task.shard_tasks.filter((t) => t.action === SEARCH_ACTION) : [];
 const shardTasks = isPpl
-  ? task.shard_tasks.filter((t) => t.action !== SEARCH_ACTION)
+  ? task.shard_tasks.filter((t) => t.action !== SEARCH_ACTION && t.action?.startsWith(SEARCH_ACTION))
   : task.shard_tasks;
Suggestion importance[1-10]: 2

__

Why: The suggestion acknowledges the current code works correctly for the known action values. The proposed change adds a defensive filter but could unintentionally exclude legitimate shard tasks whose action doesn't start with the search prefix, making it potentially worse.

Low
Suggestions up to commit 72dda61
CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify child tasks source for PPL indices

For a PPL row, shards is the full list of child tasks of the PPL coordinator (which
includes both child search coordinator tasks and shard-phase tasks). pplIndices
filters by action === SEARCH_ACTION, which is correct, but ensure shards here is
actually q.shard_tasks (child tasks array) — if shards was derived earlier only from
shard-phase tasks, no search-action entries will match and the join's right-side
index will never be added. Verify the variable passed matches what pplIndices
expects.

public/pages/InflightQueries/InflightQueries.tsx [389-392]

 let index = indexMatch ? indexMatch[1] : 'N/A';
 if (queryText !== undefined) {
-  index = pplIndices(queryText, shards).join(', ') || 'N/A';
+  index = pplIndices(queryText, (q as any).shard_tasks ?? []).join(', ') || 'N/A';
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion asks the author to verify the shards variable, which cannot be fully confirmed from the diff. It raises a legitimate concern but is primarily a verification request.

Low
General
Avoid shared stateful global regex

The PPL_SOURCE regex is defined at module scope with the global (g) flag and is
reused via matchAll across calls. While matchAll is safe for global regexes, sharing
a stateful global regex is still fragile; more importantly, if any caller ever
switches to exec/test, the retained lastIndex across invocations will cause
intermittent misses. Consider constructing the regex inside the function or dropping
the stateful risk by using a non-global pattern with a loop, to make the utility
robust to future callers.

public/utils/live-query-utils.ts [30]

-const PPL_SOURCE = /(?:^|\[)\s*(?:search\s+)?source\s*=\s*([^\s|\],]+(?:\s*,\s*[^\s|\],]+)*)/gi;
+const pplSourceRegex = () =>
+  /(?:^|\[)\s*(?:search\s+)?source\s*=\s*([^\s|\],]+(?:\s*,\s*[^\s|\],]+)*)/gi;
Suggestion importance[1-10]: 3

__

Why: matchAll with a global regex is safe and doesn't retain lastIndex state, so the concern is largely speculative about future callers. The suggestion offers a minor defensive improvement.

Low
Suggestions up to commit 33befc9
CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard against undefined shard tasks

If task.shard_tasks is undefined (as it may be when upstream code sets it to [] only
via || [], but passes raw records elsewhere), these filter calls will throw. Guard
against undefined shard_tasks to avoid runtime errors when rendering the flyout for
malformed records.

public/pages/InflightQueries/TaskDetailFlyout.tsx [95-106]

 const { _querySource, _queryText } = task as RichLiveQueryRecord & {
     _querySource?: string;
     _queryText?: string;
   };
   const isPpl = _querySource === 'PPL';
   const querySource = isPpl
     ? _queryText || null
     : (task as any)._source || (sourceMatch ? sourceMatch[1] : null);
-  const childSearchTasks = isPpl ? task.shard_tasks.filter((t) => t.action === SEARCH_ACTION) : [];
+  const allShardTasks = task.shard_tasks ?? [];
+  const childSearchTasks = isPpl ? allShardTasks.filter((t) => t.action === SEARCH_ACTION) : [];
   const shardTasks = isPpl
-    ? task.shard_tasks.filter((t) => t.action !== SEARCH_ACTION)
-    : task.shard_tasks;
+    ? allShardTasks.filter((t) => t.action !== SEARCH_ACTION)
+    : allShardTasks;
Suggestion importance[1-10]: 4

__

Why: The existing code at line 302 (task.shard_tasks.length === 0) already assumes shard_tasks is defined, and callers set it to [] via || []. The guard is a minor defensive improvement but not critical.

Low
General
Avoid shared stateful global regex

The PPL_SOURCE regex is declared at module scope with the /g flag and reused via
matchAll. While matchAll itself doesn't mutate lastIndex, sharing a stateful global
regex at module level is fragile—if any future caller uses exec or test on it,
results will become non-deterministic. Consider constructing a fresh regex per call
or dropping module-level reuse to avoid subtle bugs.

public/utils/live-query-utils.ts [30]

-const PPL_SOURCE = /(?:^|\[)\s*(?:search\s+)?source\s*=\s*([^\s|\],]+(?:\s*,\s*[^\s|\],]+)*)/gi;
+const pplSourceRegex = () => /(?:^|\[)\s*(?:search\s+)?source\s*=\s*([^\s|\],]+(?:\s*,\s*[^\s|\],]+)*)/gi;
Suggestion importance[1-10]: 3

__

Why: matchAll does not mutate lastIndex of the regex, so the current usage is safe. The concern is speculative about future misuse, offering only marginal defensive value.

Low
Suggestions up to commit 8ad092f
CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard against undefined shard_tasks

task.shard_tasks may be undefined for finished queries or defensive callers (the
later check task.shard_tasks.length === 0 already assumes an array, but earlier code
uses (selectedItem as any).shard_tasks || []). Guard against an undefined
shard_tasks here to prevent a runtime TypeError when isPpl is true but shard_tasks
is missing.

public/pages/InflightQueries/TaskDetailFlyout.tsx [95-106]

 const { _querySource, _queryText } = task as RichLiveQueryRecord & {
   _querySource?: string;
   _queryText?: string;
 };
 const isPpl = _querySource === 'PPL';
 const querySource = isPpl
   ? _queryText || null
   : (task as any)._source || (sourceMatch ? sourceMatch[1] : null);
-const childSearchTasks = isPpl ? task.shard_tasks.filter((t) => t.action === SEARCH_ACTION) : [];
+const allShardTasks = task.shard_tasks || [];
+const childSearchTasks = isPpl ? allShardTasks.filter((t) => t.action === SEARCH_ACTION) : [];
 const shardTasks = isPpl
-  ? task.shard_tasks.filter((t) => t.action !== SEARCH_ACTION)
-  : task.shard_tasks;
+  ? allShardTasks.filter((t) => t.action !== SEARCH_ACTION)
+  : allShardTasks;
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly notes that task.shard_tasks could theoretically be undefined, but existing code elsewhere already assumes it's an array, so the actual risk is limited. It's a minor defensive improvement.

Low
General
Avoid shared stateful global regex

This regex uses the g flag and is referenced in matchAll within pplIndices. Since
PPL_SOURCE is a module-level constant, its lastIndex state is preserved across calls
when used with exec, and even with matchAll the shared stateful regex can cause
subtle issues if ever used elsewhere. Clone the regex inside the function or use a
fresh regex per call to avoid shared state bugs.

public/utils/live-query-utils.ts [30]

-const PPL_SOURCE = /(?:^|\[)\s*(?:search\s+)?source\s*=\s*([^\s|\],]+(?:\s*,\s*[^\s|\],]+)*)/gi;
+const PPL_SOURCE_PATTERN = '(?:^|\\[)\\s*(?:search\\s+)?source\\s*=\\s*([^\\s|\\],]+(?:\\s*,\\s*[^\\s|\\],]+)*)';
Suggestion importance[1-10]: 2

__

Why: matchAll does not mutate the regex's lastIndex, so sharing the global regex is safe here. The concern is largely unfounded, making this a low-impact suggestion.

Low

@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.33094% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.70%. Comparing base (b3b3bdc) to head (abcdec0).

Files with missing lines Patch % Lines
public/utils/live-query-utils.ts 87.15% 6 Missing and 8 partials ⚠️
public/pages/InflightQueries/InflightQueries.tsx 75.00% 0 Missing and 3 partials ⚠️
public/pages/InflightQueries/TaskDetailFlyout.tsx 88.88% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #612      +/-   ##
==========================================
+ Coverage   75.07%   75.70%   +0.63%     
==========================================
  Files          47       48       +1     
  Lines        4128     4264     +136     
  Branches     1132     1223      +91     
==========================================
+ Hits         3099     3228     +129     
- Misses        682      687       +5     
- Partials      347      349       +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 33befc9

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 72dda61

'',
'Timestamp',
'Task ID',
'Query source',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The release integration tests run a copy of this spec that lives in the functional test repo (opensearch-dashboards-functional-test, file cypress/integration/plugins/query-insights-dashboards/5_live_queries_spec.js), not this file.

That copy still expects 12 headers with Index right after Task ID. Once this merges, the new Query source column will make it fail. Could you open a matching PR there so both land together?

Comment thread public/utils/live-query-utils.ts Outdated

// A PPL query names its indices in `source=`, which can only start the query or a subsearch
// (`[ source=... ]`). Anchoring there keeps a field called `source` in a `where` from matching.
const PPL_SOURCE = /(?:^|\[)\s*(?:search\s+)?source\s*=\s*([^\s|\],]+(?:\s*,\s*[^\s|\],]+)*)/gi;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Index column relies on this regex most of the time. A few valid PPL queries come out wrong. Could you handle these and add tests?

Query Index shown
index=logs | head 5 N/A
| source=logs N/A
/* note */ source=logs N/A
search status=500 source=logs N/A
source=[ source=logs | where a > 1 ] as t [

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

* stable while the query is between searches; the indices of its running searches add any the
* text doesn't name with `source=`, such as a join's right side.
*/
export const pplIndices = (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a follow up, could you instrument the SQL plugin to provide indices concretely? Then the regex is not needed.

SQL already parses the query and knows every index it reads. It could expose them on the PPL task, either in the task status or as indices[...] in the task description like DSL searches have. The query insights backend could then return them, and this page could show them directly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will add an issue

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit af39bdf

Query Insights reports a running PPL query as one Live Queries row
whose coordinator task is the PPL task, with the searches it runs and
their shard tasks as child tasks. The page read every row as a DSL
search: the index and search type came out as N/A, the query text was
shown nowhere, and the child searches were listed as a phase named
indices:data/read/search.

Add a Query Source column with a PPL or DSL badge, and a query_source
search field. A PPL row's badge shows the query text on hover, and its
index comes from the source= clauses in that text, plus any other index
its running searches target. The text keeps the index stable while
the query is between searches. In the flyout, a PPL row shows its query
text under PPL Query, lists its tasks as Child Tasks, and labels its
searches as Search.

The tests render Live Queries responses captured from a cluster running
a PPL join beside a DSL search.

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
A PPL query's flyout listed the searches it runs and their shard tasks
in one Child Tasks table, with each search as a row whose phase read
Search.

List the searches under Child Search Tasks, with the indices each one
reads, and their shard tasks under Shard Tasks, with the shard and
phase columns a DSL search shows. The flyout tells the two apart by
action, so the Live Queries response doesn't change. A DSL search's
flyout is unchanged.

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
The Live Queries Cypress suite checks the table's column headers in
order, so it failed once the Query source column was added after
Task ID.

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
Live Queries leaves wlm_group_id off PPL rows as of
opensearch-project/query-insights#699: WLM manages the searches a PPL
query runs, not the query, so a PPL row has no group of its own.
Remove it from the PPL row in stub_live_queries_ppl.json so the
fixture matches what the API returns.

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
The Index column read a PPL query's indices with a regex anchored at
the start of the query or a subsearch. It missed index=, a leading
pipe, a leading comment and search expressions before source=, and
showed "[" for a subsearch used as the source.

Tokenize the text instead, dropping comments and quoted strings, and
read the source= or index= of the command that starts the query and
each subsearch, wherever it sits in that command.

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
Every [ was read as the start of a subsearch. The brackets of
appendcol, appendpipe, append and foreach hold commands over the
results so far, so a field could come out as an index:
source=logs | appendcol [ eval index = 1 ] read logs and 1. A
bracket's first command now names indices only when it's a search,
not one of the PPL grammar's other commands.

Also:
- A partly backticked name, such as logs.`2024`, was cut at the
  backtick. Parts with nothing between them now make one name.
- A queryId containing ] left the whole task description as the
  query text. The prefix now ends at the first ]: .

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
A PPL row joined its indices with ", ", while a search's row shows
its indices[...] as written, "a,b". The same indices then counted as
two keys in the index chart. Join a PPL row's the same way.

Signed-off-by: Kishore Kumaar Natarajan <kkumaarn@amazon.com>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit abcdec0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants