Skip to content

[Feature][PPL] Publish running results for pushed-down aggregations of asynchronous queries - #5978

Open
ahkcs wants to merge 1 commit into
opensearch-project:mainfrom
ahkcs:feat/ppl-async-partial-aggregations
Open

ahkcs wants to merge 1 commit into
opensearch-project:mainfrom
ahkcs:feat/ppl-async-partial-aggregations

Conversation

@ahkcs

@ahkcs ahkcs commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Description

An async PPL query whose result is a pushed-down aggregation now returns a running result: while the search runs, each RUNNING response (submit and GET /_plugins/_async_query/{id}) holds the aggregation of the shards that have answered so far, and a later response replaces it. The final result still comes from the normal search response, unchanged.

{"status": "RUNNING", "progress": {"fraction_done": 0.4},
 "schema": [{"name": "m", "type": "bigint"}, {"name": "s", "type": "bigint"}],
 "datarows": [[39999, 581482687]], "total": 1, "size": 1}

Why a setting is needed

OpenSearch merges shard results in batches of min(batched_reduce_size, shard count), and batched_reduce_size defaults to 512. Below 512 shards the batch is every shard, so the only merge happens when the last shard answers, right before the response. A running result therefore needs a smaller batched_reduce_size on the request.

plugins.query.async.batched_reduce_size (dynamic, default 5; below 2 turns this off) sets it, only on async queries that qualify. Sync queries and other async queries are untouched. A smaller batch means more merges on the coordinator, but each merge also frees the shard results it consumed.

How it works

flowchart LR
  subgraph search["Search (coordinator)"]
    S["Shard results"] -->|"every N results"| M["Partial merge"]
    M -->|"onPartialReduce / onFinalReduce"| L["ShardListener"]
  end
  L -->|"if a reader asked: final reduce,<br/>same parser, same row conversion"| PA["PartialAggregation<br/>(latest built rows)"]
  C["Client"] -->|"submit / GET while RUNNING"| PR["PartialRows.snapshot()"]
  PR -->|"no rows yet: interim"| PA
  PA -->|"latest rows, no work on read"| C
Loading
  • Which queries: the plan root is a CalciteEnumerableIndexScan with a pushed-down aggregation that is not composite (stats without by, and bucket aggregations that come back in one response). scanAsRoot registers a PartialAggregation only in that case, so a step computed by Calcite above the aggregation means no running result. timewrap is excluded.
  • Building on the search thread: SourceProgress.ShardListener, already on the search task since [Feature][PPL] Report progress for asynchronous Calcite queries #5910, now also handles onPartialReduce/onFinalReduce. In that callback, PartialAggregation finishes the merge with a final reduce (a partial merge skips steps such as trimming terms buckets to size) and converts it. The conversion goes through OpenSearchQueryRequest.reducedResponse (the same parser and value factory as the final response), the enumerator's cell conversion, and ResultRows (the same Calcite-to-ExprValue conversion as buildResultSet).
    • Why there: the coordinator merges that object again in its next batch, and a merge can change its inputs. For example, the t-digest percentiles reduce compresses the digests it adds. Reducing it on a poll thread would race with that merge. The callback runs between merges, on the merging thread.
    • Only on demand: a partial merge is built only if a reader has asked since the last build. The final merge is always built, so the running result never trails the final one.
    • Bucket limit: a merge with more buckets than search.max_buckets is skipped.
  • Shard failures: the listener counts shards that failed or had no copy to search, including a node that left. Each running result carries the same PARTIAL_RESULT warning the final response does ("N of M shards did not return data"), so a running aggregation is never shown as complete.
  • Read path: snapshot() returns the latest built rows and asks for the next build. It never blocks, which QueryRunner.currentResult() requires; it runs on the wait-timeout timer thread and on GET handlers.
  • PartialRows: gains an interim view, shown only until the first final row arrives. It is read under the same lock as the rows, so a response never shows interim rows after final ones. discard() (failure or fallback) drops it too.
  • ResultRows: processValue and buildColumns moved out of OpenSearchExecutionEngine so that both paths share them. buildResultSet behavior is unchanged.

Not covered

  • stats count() alone is pushed down as a hit count with no aggregation, and OpenSearch does not merge early without aggregations or hits, so it has no running result. The docs say so.
  • A plan where Calcite computes on top of the pushed-down aggregation is not covered. For example, eval x = n * 2 | stats sum(x) becomes sum(n) * 2 in an EnumerableCalc.
  • Composite stats ... by keeps the page-by-page rows from [Feature][PPL] Publish partial rows for asynchronous Calcite queries #5920.
  • Remote clusters under ccs_minimize_roundtrips merge remotely, so they produce no early merge.

Open questions for review

  1. Default 5: I believe Elasticsearch's async search uses the same default for the same reason. Should it stay on by default?
  2. Final reduce in the merge callback: each build adds one final reduce, plus conversion, to the merging search thread, and only when a reader has asked. The alternative is a serialized copy in the callback with the reduce done on read, which costs a copy on every merge. The built copy is capped at search.max_buckets but is not charged to the request circuit breaker.
  3. No ScriptService in that reduce: PPL pushes down no pipeline or scripted-metric aggregations, which are the only ones whose reduce needs scripts. If a reduce fails, the poll returns no rows and the query is unaffected.

Tests

Suite Result
AsyncPPLPartialAggregationIT (new): a 40-shard index returns a running result that matches the final schema, with a sum at most the final one; the final rows equal sync; with the setting at 0, no rows until done 2 / 2, 4 repeated runs
AsyncPPLPartialRowsIT, AsyncPPLProgressIT, AsyncPPLQueryLifecycleIT, AsyncPPLRetainedJobLimitIT 39 / 39
PartialAggregationTest (new): builds a merge with the root row type; builds only after a reader asked, and a read does no work; finishes a partial merge (3 terms buckets trimmed to 2) but uses a final one as is; skips a merge over the bucket limit; a failure or empty result gives no rows pass
SourceProgressTest: sets the batch size and keeps merges only for a single aggregation search; plain, PIT and composite searches keep the default pass
PartialRowsTest: interim until the first row, kept across open, dropped by discard pass
OpenSearchQueryRequestReducedResponseTest (new): a merge gives the same rows as the response pass
:opensearch:test, :core:test, :common:test, plugin tests, spotlessCheck pass

Removing setBatchedReduceSize makes AsyncPPLPartialAggregationIT fail. The IT uses a pushed-down script filter and disables the request cache on its index, so that each run is slow enough to poll mid-run.

Related Issues

Resolves #5799
Part of #5765

Check List

  • New functionality includes testing.
  • New functionality has been documented.
    • New functionality has javadoc added.
    • New functionality has a user manual doc added.
  • New PPL command checklist all confirmed. N/A
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created.

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 Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 73b1364)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
📝 TODO sections

🔀 Multiple PR themes

Sub-PR theme: Extract ResultRows helper from OpenSearchExecutionEngine

Relevant files:

  • opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/executor/ResultRows.java

Sub-PR theme: Partial aggregation running results for async PPL queries

Relevant files:

  • opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialRows.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/SourceProgress.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/CalciteEnumerableIndexScan.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexEnumerator.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/request/OpenSearchQueryRequest.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/request/OpenSearchRequest.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/response/OpenSearchResponse.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/response/ShardStats.java
  • common/src/main/java/org/opensearch/sql/common/setting/Settings.java
  • opensearch/src/main/java/org/opensearch/sql/opensearch/setting/OpenSearchSettings.java

⚡ Recommended focus areas for review

Thread safety of rootRows

rootRows is stored as a non-volatile field but read from onReduce running on a search thread while being written from the enumerator thread. Although wanted and latest are volatile, the rootRows reference itself is not, so a reducing search thread may observe a stale null or partially published function reference. Consider making the field volatile or publishing it via a volatile wrapper.

private volatile BiFunction<TotalHits, InternalAggregations, List<Object[]>> rootRows;
private volatile boolean wanted = true;
private volatile Optional<QueryResult.Rows> latest = Optional.empty();

public PartialAggregation(int batchedReduceSize, int maxBuckets, RelDataType rowType) {
  this.batchedReduceSize = batchedReduceSize;
  this.maxBuckets = maxBuckets;
  this.columnNames = rowType.getFieldNames().toArray(String[]::new);
  this.fieldTypes = rowType.getFieldList().stream().map(RelDataTypeField::getType).toList();
}

public int batchedReduceSize() {
  return batchedReduceSize;
}

/** Converts a merged result into the cells the root returns; empty if the request has none. */
public void rootRows(BiFunction<TotalHits, InternalAggregations, List<Object[]>> rootRows) {
  this.rootRows = rootRows;
}
NPE risk on aggregation request

isSingleAggregation only checks request.source().aggregations() != null, but reduceTo == null ? null : request.source().aggregations().buildPipelineTree() is evaluated right after. If aggregation != null but the source had no aggregations, reduceTo is null, but the ternary short-circuits correctly; however if an aggregation push-down request ever has null source() while aggregation != null, isSingleAggregation returns false and reduceTo is null — this is safe. Verify that request.source().aggregations() never becomes null between the check and buildPipelineTree() call (they're the same expression so this is fine, but the pattern is fragile).

PartialAggregation reduceTo =
    aggregation != null && isSingleAggregation(request) ? aggregation : null;
ShardListener listener =
    new ShardListener(
        current,
        reduceTo,
        reduceTo == null ? null : request.source().aggregations().buildPipelineTree());
Settings null check inconsistency

osIndex.getSettings() == null ? null : osIndex.getSettings().getSettingValue(...) returns null and then skips partial aggregation. This silently disables the feature when settings are unavailable (e.g., in tests or special contexts). Consider whether this should log a debug message or fall back to the default of 5 explicitly to avoid surprising behavior where the feature intermittently doesn't engage.

Integer batchedReduceSize =
    osIndex.getSettings() == null
        ? null
        : osIndex.getSettings().getSettingValue(Settings.Key.QUERY_ASYNC_BATCHED_REDUCE_SIZE);
// These rows are the result, so a merge of some shards' aggregations is a running result.
// Timewrap reshapes the rows at the end.
if (batchedReduceSize != null
    && batchedReduceSize >= 2
    && pushDownContext.isAggregatePushed()
    && !TimewrapPivot.isTimewrap()) {
  PartialAggregation aggregation =
      new PartialAggregation(batchedReduceSize, osIndex.getMaxBuckets(), getRowType());
  progress.reduceInto(aggregation);
  tracker.get().partialRows().interim(aggregation::snapshot);
}

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 73b1364

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Retry building after a failed reduce

When build throws, wanted has already been flipped to false, so subsequent partial
reduces will be skipped until a reader calls snapshot(). Worse, if a non-terminal
build fails and no later reduce occurs before the final one, the stale latest
remains. Reset wanted = true on failure so the next reduce retries building the
running result.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [79-89]

 BiFunction<TotalHits, InternalAggregations, List<Object[]>> convert = rootRows;
 // The last merge is always built, so the running result never trails the final one.
 if ((!wanted && !last) || convert == null) {
   return;
 }
 wanted = false;
 try {
   latest = build(totalHits, aggregations, pipelines, last, warnings, convert);
 } catch (Exception e) {
+  wanted = true;
   LOG.debug("Failed to build the running result of an aggregation", e);
 }
Suggestion importance[1-10]: 6

__

Why: Valid observation: if build throws, wanted stays false and subsequent partial reduces are skipped until a reader calls snapshot(), potentially leaving the running result stale. Resetting wanted = true on failure is a reasonable minor improvement for robustness.

Low
Clarify visibility of shard counters

unavailableShards is incremented under the SourceProgress.this lock, but warnings()
is called from onPartialReduce/onFinalReduce which run on the search thread without
that lock being held by the reduce path. Ensure totalShards and unavailableShards
are consistently read under the lock (as warnings() does) and that writes to
totalShards in onListShards also happen-before the reduce reads. Consider making
these fields volatile or documenting the synchronization contract, since the current
code only synchronizes the reader.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/SourceProgress.java [321-327]

+@Override
+protected void onQueryFailure(int shardIndex, SearchShardTarget shardTarget, Exception exc) {
+  synchronized (SourceProgress.this) {
+    // Includes a shard with no copy to search, e.g. on a node that left.
+    unavailableShards++;
+    pass.onShardDone();
+  }
+}
 
-
Suggestion importance[1-10]: 3

__

Why: The suggestion raises a legitimate concern about memory visibility of totalShards/unavailableShards across threads, but the improved_code is identical to existing_code and provides no concrete fix, reducing its actionability.

Low

Previous suggestions

Suggestions up to commit 4173cb0
CategorySuggestion                                                                                                                                    Impact
Possible issue
Protect reduce callback against concurrent updates

onReduce can be invoked concurrently from different search threads for partial and
final reduces; the current non-atomic read/write of wanted and latest can lose the
final merge if a partial reduce overwrites latest after the final one. Synchronize
onReduce (or guard with a lock) so the "last" merge is never clobbered by a late
partial reduce.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [79-90]

-BiFunction<TotalHits, InternalAggregations, List<Object[]>> convert = rootRows;
-// The last merge is always built, so the running result never trails the final one.
-if ((!wanted && !last) || convert == null) {
-  return;
-}
-wanted = false;
-try {
-  latest = build(totalHits, aggregations, pipelines, last, warnings, convert);
-} catch (Exception e) {
-  LOG.debug("Failed to build the running result of an aggregation", e);
+synchronized void onReduce(
+    TotalHits totalHits,
+    InternalAggregations aggregations,
+    PipelineTree pipelines,
+    boolean last,
+    List<Warning> warnings) {
+  BiFunction<TotalHits, InternalAggregations, List<Object[]>> convert = rootRows;
+  if ((!wanted && !last) || convert == null) {
+    return;
+  }
+  wanted = false;
+  try {
+    latest = build(totalHits, aggregations, pipelines, last, warnings, convert);
+  } catch (Exception e) {
+    LOG.debug("Failed to build the running result of an aggregation", e);
+  }
 }
Suggestion importance[1-10]: 7

__

Why: onReduce can be called from multiple search threads concurrently, and the non-atomic update of wanted/latest could cause a late partial reduce to overwrite the final merge. Synchronizing the method is a reasonable safety improvement, though the actual race window and impact depend on OpenSearch's threading model.

Medium
General
Use standard bucket-limit exception type

bucketLimit() returns a new counter each call, but it is created inside build once
per reduce, which is correct — however the per-reduce counter is never reset across
reduces only because a fresh lambda is made each time. Make this explicit by naming
the method per-call behavior, and more importantly, ensure the exception type
matches what callers expect: IllegalStateException is caught as Exception in build,
which is fine, but any MultiBucketConsumerService.TooManyBucketsException from the
real limiter would not be. Consider throwing
MultiBucketConsumerService.TooManyBucketsException for consistency with OpenSearch's
bucket limit semantics so downstream handling and logs are uniform.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [121-129]

-/** Gives up on a merge with more buckets than a search may return. */
 private IntConsumer bucketLimit() {
   int[] buckets = {0};
   return count -> {
     buckets[0] += count;
     if (buckets[0] > maxBuckets) {
-      throw new IllegalStateException("more than " + maxBuckets + " buckets");
+      throw new org.opensearch.search.aggregations.MultiBucketConsumerService
+          .TooManyBucketsException("more than " + maxBuckets + " buckets", maxBuckets);
     }
   };
 }
Suggestion importance[1-10]: 3

__

Why: Using TooManyBucketsException would be more consistent with OpenSearch's conventions, but since the exception is caught as Exception in build and only logged, this is a minor stylistic improvement with limited functional impact.

Low
Suggestions up to commit 17a1c0e
CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix race on wanted flag between threads

onReduce reads wanted and writes latest without synchronization while snapshot()
concurrently writes wanted and reads latest. Although fields are volatile, the
read-modify-write on wanted in onReduce (!wanted && !last then wanted = false) is
not atomic with respect to snapshot() setting wanted = true, which can cause a
reader's request to be lost. Guard both methods with a common lock or use an
AtomicBoolean with compareAndSet to avoid dropped update signals.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [45-47]

 private volatile BiFunction<TotalHits, InternalAggregations, List<Object[]>> rootRows;
-private volatile boolean wanted = true;
+private final java.util.concurrent.atomic.AtomicBoolean wanted = new java.util.concurrent.atomic.AtomicBoolean(true);
 private volatile Optional<QueryResult.Rows> latest = Optional.empty();
Suggestion importance[1-10]: 5

__

Why: The concern about a race between snapshot() setting wanted=true and onReduce reading/writing it is plausible since both are not atomic. However, the worst case is a missed partial merge (which the next reduce will cover), and the final reduce is always built, so impact is limited.

Low
General
Surface bucket-limit skips more visibly

bucketLimit() is invoked via ReduceContext.forFinalReduction(..., bucketLimit(),
...) inside build, and is only called once per partial merge, so the buckets[0]
counter is reset each call — good. However, the IllegalStateException thrown inside
the lambda is caught by the broad catch (Exception e) in onReduce, which silently
swallows it with a debug log. Consider logging the bucket-limit case explicitly (or
at least at info/warn) so operators can diagnose why a partial aggregation never
produces rows.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [118-126]

 private IntConsumer bucketLimit() {
   int[] buckets = {0};
   return count -> {
     buckets[0] += count;
     if (buckets[0] > maxBuckets) {
-      throw new IllegalStateException("more than " + maxBuckets + " buckets");
+      throw new IllegalStateException(
+          "partial aggregation skipped: more than " + maxBuckets + " buckets");
     }
   };
 }
Suggestion importance[1-10]: 3

__

Why: Minor observability improvement; the suggested change only tweaks the exception message, not the log level that actually controls visibility, so it provides marginal benefit.

Low
Suggestions up to commit 99726a3
CategorySuggestion                                                                                                                                    Impact
General
Synchronize the snapshot/reduce handshake

The wanted and latest fields are declared volatile but updated from multiple threads
(search threads via onReduce, reader threads via snapshot) without any atomic
coordination. A reader thread can set wanted=true and then, between that write and
the next onReduce, another reader can read a stale latest while the search thread
has already consumed wanted=false for a prior request. Consider using an
AtomicBoolean for wanted or guarding both reads/writes under a single lock to make
the "ask for next / return latest" handshake correct under concurrency.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [65-68]

 public void rootRows(BiFunction<TotalHits, InternalAggregations, List<Object[]>> rootRows) {
     this.rootRows = rootRows;
   }
 
   /** The latest merge built; asks for the next one. Does not block. */
-  public Optional<QueryResult.Rows> snapshot() {
+  public synchronized Optional<QueryResult.Rows> snapshot() {
     wanted = true;
     return latest;
   }
Suggestion importance[1-10]: 5

__

Why: The concern about concurrent access between reader and search threads is valid, though the volatile fields may be sufficient for the intended semantics. Adding synchronized is a minor safety improvement but the suggestion doesn't deeply analyze whether the current design is actually broken.

Low
Verify thread-local timewrap check at scan time

TimewrapPivot.isTimewrap() reads thread-local state at plan time, but scanAsRoot()
may be invoked on a different thread during execution than the one that will later
actually reshape rows, and the thread-local may not yet be set when scan is created.
Confirm that isTimewrap() returns the correct value at this call site; otherwise a
timewrap query could still enable partial aggregation and emit non-prefix running
rows. If the check depends on plan-time state, derive it from the RelNode tree
instead of a thread-local.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/CalciteEnumerableIndexScan.java [143-157]

+Integer batchedReduceSize =
+    osIndex.getSettings() == null
+        ? null
+        : osIndex.getSettings().getSettingValue(Settings.Key.QUERY_ASYNC_BATCHED_REDUCE_SIZE);
+// These rows are the result, so a merge of some shards' aggregations is a running result.
+// Timewrap reshapes the rows at the end.
+if (batchedReduceSize != null
+    && batchedReduceSize >= 2
+    && pushDownContext.isAggregatePushed()
+    && !TimewrapPivot.isTimewrap()) {
 
-
Suggestion importance[1-10]: 4

__

Why: The concern about thread-local state in TimewrapPivot.isTimewrap() is valid to raise, but the suggestion only asks to verify without providing concrete evidence of a bug, and the improved_code is identical to existing_code.

Low
Make bucket-count accumulator thread-safe

The IntConsumer is freshly allocated per call to bucketLimit(), but it is passed to
ReduceContext.forFinalReduction which may be used across threads or multiple
invocations of topLevelReduce. More importantly, the buckets counter is captured by
a non-thread-safe int array; if the consumer is ever invoked concurrently, the
read-modify-write on buckets[0] is racy. Use a local AtomicInteger (or document that
bucket-count callbacks are single-threaded here).

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [116-124]

 private IntConsumer bucketLimit() {
-  int[] buckets = {0};
+  java.util.concurrent.atomic.AtomicInteger buckets = new java.util.concurrent.atomic.AtomicInteger();
   return count -> {
-    buckets[0] += count;
-    if (buckets[0] > maxBuckets) {
+    if (buckets.addAndGet(count) > maxBuckets) {
       throw new IllegalStateException("more than " + maxBuckets + " buckets");
     }
   };
 }
Suggestion importance[1-10]: 3

__

Why: The bucket limit consumer is created fresh per reduce call and used within a single topLevelReduce invocation, so concurrent access is unlikely. The suggestion is speculative without clear evidence of a race condition.

Low
Suggestions up to commit 1ffe6fd
CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard concurrent state transitions in reducer

The wanted/latest fields are mutated from both the reader thread (snapshot) and the
search thread (onReduce) without synchronization beyond volatile. A reader that sets
wanted = true can race with onReduce reading wanted and then writing wanted = false
and latest, allowing a stale latest to be returned while a concurrent reduce is in
flight. Consider guarding the state transitions with a lock or using atomic compound
operations to ensure a snapshot either sees the new merge or forces the next reduce
to build one.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [65-86]

-public Optional<QueryResult.Rows> snapshot() {
+public synchronized Optional<QueryResult.Rows> snapshot() {
     wanted = true;
     return latest;
   }
 
   /** Called on the search thread that made the merge. */
   void onReduce(
       TotalHits totalHits,
       InternalAggregations aggregations,
       PipelineTree pipelines,
       boolean last) {
     BiFunction<TotalHits, InternalAggregations, List<Object[]>> convert = rootRows;
-    if (!wanted || convert == null) {
+    synchronized (this) {
+      if (!wanted || convert == null) {
+        return;
+      }
+      wanted = false;
+    }
+    Optional<QueryResult.Rows> built;
+    try {
+      built = build(totalHits, aggregations, pipelines, last, convert);
+    } catch (Exception e) {
+      LOG.debug("Failed to build the running result of an aggregation", e);
       return;
     }
-    wanted = false;
-    try {
-      latest = build(totalHits, aggregations, pipelines, last, convert);
-    } catch (Exception e) {
-      LOG.debug("Failed to build the running result of an aggregation", e);
+    synchronized (this) {
+      latest = built;
     }
   }
Suggestion importance[1-10]: 5

__

Why: The concern about races between reader and search threads is valid given only volatile fields are used, though the existing design may tolerate occasional stale reads since snapshots are intended to be best-effort. The suggested synchronization adds safety but marginal impact.

Low
Avoid NPE when unboxing setting value

getSettingValue may return null (e.g., setting unavailable at runtime), which would
cause a NullPointerException on auto-unboxing to int. Defend against a null result
before unboxing so a missing setting falls back to the "off" value instead of
failing the query.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/CalciteEnumerableIndexScan.java [143-146]

-int batchedReduceSize =
+Integer configured =
         osIndex.getSettings() == null
-            ? 0
+            ? null
             : osIndex.getSettings().getSettingValue(Settings.Key.QUERY_ASYNC_BATCHED_REDUCE_SIZE);
+    int batchedReduceSize = configured == null ? 0 : configured;
Suggestion importance[1-10]: 4

__

Why: A potential NPE on unboxing is a reasonable defensive concern, but getSettingValue for a registered setting typically returns non-null. The fix is minor defensive hardening.

Low
General
Verify pipeline tree reuse for partial reduce

AggregatorFactories.Builder#buildPipelineTree is typically only safe to call on the
top-level aggregations builder once. Building the pipeline tree here, and also later
during final reduce on the coordinator, could cause duplicate pipeline application
or inconsistent state. Verify that building and reusing the PipelineTree on partial
merges does not conflict with the coordinator's own final reduce; if unsure, limit
partial-reduce building to the non-pipeline aggregations case only.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/SourceProgress.java [59-65]

 PartialAggregation reduceTo =
         aggregation != null && isSingleAggregation(request) ? aggregation : null;
-    ShardListener listener =
-        new ShardListener(
-            current,
-            reduceTo,
-            reduceTo == null ? null : request.source().aggregations().buildPipelineTree());
+    PipelineTree pipelineTree = null;
+    if (reduceTo != null) {
+      pipelineTree = request.source().aggregations().buildPipelineTree();
+    }
+    ShardListener listener = new ShardListener(current, reduceTo, pipelineTree);
Suggestion importance[1-10]: 3

__

Why: The suggestion asks to verify behavior rather than fix a concrete issue, and the improved_code is functionally equivalent to the existing code. Limited actionable impact.

Low
Suggestions up to commit a07b712
CategorySuggestion                                                                                                                                    Impact
General
Prefer real rows over stale interim

After building the interim outside the lock, the second check only verifies that
interim has not changed, but it does not re-check whether rows have since been
added. If the query thread added real rows while the interim was being built, the
stale interim will be returned instead of the actual row prefix. Re-check
rows.isEmpty() under the final lock and prefer real rows if present.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialRows.java [61-78]

 public Optional<QueryResult.Rows> snapshot() {
     Supplier<Optional<QueryResult.Rows>> pending;
     synchronized (this) {
       if (schemaOf != null && !rows.isEmpty()) {
         return Optional.of(rowsSoFar());
       }
       pending = interim;
     }
     if (pending == null) {
       return Optional.empty();
     }
     // Outside the lock: building it can take a while, and the query thread adds rows under it.
     Optional<QueryResult.Rows> built = pending.get();
     synchronized (this) {
+      if (schemaOf != null && !rows.isEmpty()) {
+        return Optional.of(rowsSoFar());
+      }
       // Discarded or superseded while it was built.
       return interim == pending ? built : Optional.empty();
     }
   }
Suggestion importance[1-10]: 6

__

Why: This is a valid race condition concern: rows added during interim building may be masked by returning the stale interim. Re-checking under the final lock improves correctness of partial results.

Low
Invalidate cache when converter changes

The cache check compares reduce == built using reference identity on a volatile
field read outside the lock, but built is not volatile. A thread may observe a stale
built under the synchronized block only on first entry; however, reads of latest
outside the lock can interleave such that two threads rebuild the same Reduce. More
importantly, built is accessed under the lock but declared non-volatile — this is
fine within synchronized blocks, but the real issue is that cached is also
non-volatile and returned after exiting the synchronized block in a prior branch via
the return cached statement, which is safe. Consider also handling the case where
convert changes between snapshots (e.g., if rootRows is re-set), since built would
then falsely suggest the cached result is current.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialAggregation.java [68-78]

 public Optional<QueryResult.Rows> snapshot() {
     Reduce reduce = latest;
     BiFunction<TotalHits, InternalAggregations, List<Object[]>> convert = rootRows;
     if (reduce == null || convert == null) {
       return Optional.empty();
     }
     synchronized (this) {
-      if (reduce == built) {
+      if (reduce == built && convert == builtWith) {
         return cached;
       }
     }
Suggestion importance[1-10]: 3

__

Why: In practice, rootRows is set once before use, so the risk of a changed converter returning a stale cached result is low. The suggestion is a minor defensive improvement.

Low
Possible issue
Guard against null setting value

getSettingValue returns an Integer that may be null if the setting is not
registered, which would cause an NullPointerException on auto-unboxing to int. Guard
against a null return value in addition to a null settings object.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/CalciteEnumerableIndexScan.java [143-146]

 SourceProgress progress = tracker.get().addSource();
-int batchedReduceSize =
+Integer configured =
     osIndex.getSettings() == null
-        ? 0
+        ? null
         : osIndex.getSettings().getSettingValue(Settings.Key.QUERY_ASYNC_BATCHED_REDUCE_SIZE);
+int batchedReduceSize = configured == null ? 0 : configured;
Suggestion importance[1-10]: 4

__

Why: The setting is registered in OpenSearchSettings, so a null return is unlikely, but a defensive null check would prevent potential NPE from auto-unboxing in edge cases.

Low

@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.18182% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.49%. Comparing base (6beda2b) to head (73b1364).

Files with missing lines Patch % Lines
...earch/storage/scan/CalciteEnumerableIndexScan.java 75.00% 1 Missing and 3 partials ⚠️
...opensearch/sql/opensearch/executor/ResultRows.java 93.33% 1 Missing and 2 partials ⚠️
...l/opensearch/executor/progress/SourceProgress.java 88.88% 0 Missing and 3 partials ⚠️
...arch/sql/opensearch/request/OpenSearchRequest.java 0.00% 1 Missing ⚠️
...search/storage/scan/OpenSearchIndexEnumerator.java 88.88% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##               main    #5978    +/-   ##
==========================================
  Coverage     89.49%   89.49%            
- Complexity    12269    12311    +42     
==========================================
  Files           980      982     +2     
  Lines         42018    42137   +119     
  Branches       4836     4853    +17     
==========================================
+ Hits          37604    37711   +107     
- Misses         2940     2944     +4     
- Partials       1474     1482     +8     
Flag Coverage Δ
integration 69.96% <82.95%> (+0.01%) ⬆️
unit 76.87% <64.20%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

@ahkcs
ahkcs force-pushed the feat/ppl-async-partial-aggregations branch from a07b712 to 1ffe6fd Compare November 24, 2026 19:06
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 1ffe6fd

@ahkcs
ahkcs force-pushed the feat/ppl-async-partial-aggregations branch from 1ffe6fd to 99726a3 Compare November 24, 2026 23:19
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 99726a3

@ahkcs
ahkcs force-pushed the feat/ppl-async-partial-aggregations branch from 99726a3 to 17a1c0e Compare November 30, 2026 17:59
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 17a1c0e

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 4173cb0

…PPL queries

An async query whose root is a scan with a pushed-down, non-composite
aggregation now returns the aggregation of the shards that have answered
so far while it runs. The search is sent with a small batched_reduce_size
(plugins.query.async.batched_reduce_size, default 5) so the coordinator
merges shard results as they arrive. The shard listener builds the running
result from a merge on the search thread that made it, before the next
merge reuses it, and only once a reader has asked; a read never blocks.
Rows go through the same parser and result-row conversion as the final
response, and carry a PARTIAL_RESULT warning once a shard has failed or
had no copy to search.

Signed-off-by: Kai Huang <ahkcs@amazon.com>
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 73b1364

angle943 added a commit to opensearch-project/OpenSearch-Dashboards that referenced this pull request Dec 1, 2026
…and Visualization tabs (#13273)

* feat(explore): stream a stats query without a by clause on the Statistics and Visualization tabs

The SQL plugin can report a running result for a pushed-down aggregation
without grouping (opensearch-project/sql#5978): while the search runs,
each poll carries the aggregation of the shards that have answered so far,
and the next one replaces it. The Statistics and Visualization tabs always
ran their query on the standard path, so they showed nothing until it
finished.

When streaming is on and the tab query ends in a `stats` without `by`,
the tab query now runs as an async job like the logs table, with the same
time filter and no default sort, and falls back to the standard path when
the engine cannot stream. Every other aggregation stays on the standard
path: its buckets arrive whole either way, and that path cancels the query
on the cluster when stopped, which releasing an async job does not yet do
(opensearch-project/sql#6004).

While a streamed tab query has no row yet, the tab keeps its loading state
instead of rendering "No items found", and the query panel's progress bar
and screen reader announcement follow the active tab's streamed query, so
they describe the aggregation the tab shows rather than the logs query.

Signed-off-by: Justin Kim <jungkm@amazon.com>

* fix(explore): mark a running aggregation and clear it when stopped

A running aggregation's values are recomputed on every poll and can be
far from the final ones: in a test run the sum read 938,641,603 at 83%
against a final 2,252,427,317. Unlike streamed log rows, they are not
part of the answer.

- The Statistics and Visualization tabs show a callout while their query
  streams a running result.
- A stopped or failed run clears the running values instead of leaving
  them on screen and in a CSV export, and a run that cannot finish
  re-runs on the standard path instead of ending "Incomplete".
- A lone `stats count()` stays on the standard path: the engine answers
  it as a hit count, so streaming it shows nothing sooner and gives up
  cancelling it on Stop.

Signed-off-by: Justin Kim <jungkm@amazon.com>

* fix(explore): show the final aggregation in an expanded row and clear the chart when stopped

The Statistics tab kept the expanded row's JSON from the row it was opened
on, so it still showed the running values after the final row arrived. It
now remembers which rows are expanded and renders the JSON from the current
row.

After Stop, the Visualization tab kept drawing the last running point
because the visualization builder caches its data. The container now draws
nothing once the results are cleared.

Signed-off-by: Justin Kim <jungkm@amazon.com>

* fix(explore): show the running-result callout only for a streamed aggregation

For a query without an aggregation, the Statistics and Visualization tabs
read the same results as the logs table. While those rows streamed, the tabs
showed the "Running result" callout above rows that are final.

A streamed aggregation now marks its streaming status as a running result,
and the callout shows only for that.

Signed-off-by: Justin Kim <jungkm@amazon.com>

---------

Signed-off-by: Justin Kim <jungkm@amazon.com>
@ahkcs ahkcs added PPL Piped processing language enhancement New feature or request labels Dec 2, 2026

This branch has not been deployed

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

Labels

enhancement New feature or request PPL Piped processing language

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][PPL] Publish partial results for fully pushed aggregations

1 participant