Skip to content

[Feature][PPL] Publish partial rows for asynchronous Calcite queries - #5920

Merged
penghuo merged 1 commit into
opensearch-project:mainfrom
ahkcs:feat/ppl-async-partial-rows
Nov 23, 2026
Merged

penghuo merged 1 commit into
opensearch-project:mainfrom
ahkcs:feat/ppl-async-partial-rows

Conversation

@ahkcs

@ahkcs ahkcs commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Async PPL responses now return the rows a query has produced so far: the submit response when wait_for_completion_timeout expires, and GET /_plugins/_async_query/{id} while the job is RUNNING.

{"id": "<opaque-id>", "status": "RUNNING", "progress": {"fraction_done": 0.42},
 "schema": [{"name": "n", "type": "int"}], "datarows": [[0], [1], [2]], "total": 3, "size": 3}

How it works

flowchart LR
  subgraph exec["Query thread"]
    RS["Calcite ResultSet"] -->|each row| BRS["buildResultSet"]
    BRS -->|"add(row), warnings"| PR["PartialRows<br/>(on the query's tracker)"]
    BRS -.->|"failure / fallback: discard()"| PR
  end
  C["Client"] -->|"submit (wait expires)<br/>or GET while RUNNING"| QJ["QueryJob"]
  QJ -->|"currentResult(), then progress()"| R["PPLQueryRunner"]
  R -->|"snapshot()"| PR
  QJ --> F["AsyncQueryResultResponseFormatter<br/>(same for submit and GET)"]
  F -->|"progress + schema + datarows so far"| C
Loading

The rows a Calcite root ResultSet emits are already final rows in final order; they are never retracted. So no plan classification is needed:

  • OpenSearchExecutionEngine.buildResultSet appends each converted row to a PartialRows buffer held by the async query's tracker (the same object that holds progress since [Feature][PPL] Report progress for asynchronous Calcite queries #5910). Sync queries have no tracker and are unchanged.
  • A snapshot is the buffered rows plus a schema built by the same code as the final response (buildColumns, extracted). It is published only after the first row, so its schema equals the final schema. The buffer stops at the query size limit, as the final result does.
  • Composite (stats ... by) pages reach the root as they are fetched, so they become visible without a composite-specific adapter.
  • A step that must see all rows first (eventstats, stats without by, a sort that is not pushed down) returns rows only after it has read its whole input; a pushed-down sort streams like a scan.
  • timewrap reshapes all rows at the end, so it publishes none while running.
  • If execution fails or falls back to the legacy engine (any exception from the Calcite execute path), the buffered rows are discarded, so stale Calcite rows are never shown; a fallback query returns no rows until it finishes.

Every response is a complete replacement view; there is no delta protocol.

Lifecycle seam (core/job)

  • QueryRunner.currentResult() (default empty), sampled outside the job monitor like progress().
  • QueryJobStatus.current() and QueryResult.Running.current() carry the snapshot, present only while RUNNING.
  • QueryRunner.close() (default no-op, idempotent), called once the job is terminal. The PPL runner drops its progress and rows suppliers and its cancellation hook (which holds the query task), so a job retained for keep_alive no longer holds the buffer.

Responses

  • Submit and GET RUNNING bodies are now rendered by the same formatter (AsyncQueryResultResponseFormatter, with an id field set only on submit), so they cannot drift. Query-job responses are built through AsyncQueryResult.forQueryJob and marked explicitly, rather than inferred from other fields.
  • Snapshots build their schema once and are reused until a row is added. They carry the warnings raised so far (e.g. PARTIAL_RESULT when a shard did not answer), as the final response does.
  • A wait timeout completes on the JVM-wide CompletableFuture timer thread, so the RUNNING submit body, which can now hold thousands of rows, is formatted on the generic pool.
  • A job's rows are sampled before its progress, so rows never come with a progress older than the work behind them.

Behavior changes to flag

  • GET bodies of query jobs now match sync, as [Feature][PPL] Publish partial rows from root ResultSet and Composite pagination #5798 requires:
    • Type names use the PPL spec, as the sync response does: bigint, not long; int, not integer. AsyncPPLQueryLifecycleIT and AsyncPPLMultiNodeRoutingIT documented the old difference on purpose and are updated.
    • SUCCEEDED bodies now include warnings when present.
    • Spark responses are unchanged: they keep the SQL spec and have no warnings.
  • GET RUNNING now includes schema, datarows, total, and size (empty when there are no rows yet). The submit RUNNING body gains size.

Observed

AsyncPPLPartialRowsIT, source=<fixture> | fields n (10,000 rows, 1,000 PIT pages), rows per RUNNING response polled every 20 ms: 0, 0, 789, 2057, 3179, 4699, 6329, 7939, 9769, then SUCCEEDED with all 10,000, equal to sync.

Tests

Suite Result
AsyncPPLPartialRowsIT (new): scan and row-local eval/where return rows early; composite with 100-bucket pages returns rows before the last page; blocking eventstats returns rows only after reading all input; size limit 500; timewrap; failure after rows were visible 7 / 7
CalciteCrossClusterAsyncProgressIT, with a new remote partial-rows case 6 / 6
AsyncPPLProgressIT 6 / 6
AsyncPPLMultiNodeRoutingIT (asyncMultiNodeIT) 9 / 9
AsyncPPLSecurityIT 2 / 2
AsyncPPLQueryLifecycleIT 24 / 25; see below
check for core, opensearch, ppl, async-query-core, async-query, and the plugin pass

Each AsyncPPLPartialRowsIT case asserts that the final schema and rows equal sync, and that every RUNNING response is a complete view whose rows are a prefix of the final rows, never shrink, and carry the final schema. New unit tests cover the job seam, PartialRows (including a concurrent writer/reader prefix check), the runner, routing, and the formatter.

AsyncPPLQueryLifecycleIT: one parity_* case fails per run, a different one each time. The same failure reproduces on a clean upstream/main, so it is pre-existing and not caused by this PR. With wait_for_completion_timeout=0, a fast analysis error now completes before the wait starts and is returned inline, instead of the RUNNING id the test expects. This likely changed with #5915; I'll follow up separately.

Related Issues

Resolves #5798
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 2, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 3fa6a0d)

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

Partial rows are not discarded on size-limit truncation

When querySizeLimit stops the loop early, rows accumulated in partialRows are not cleared, but the final QueryResponse returned to the client contains only values (bounded by the limit). A late snapshot read on a RUNNING state could still observe the buffer, and more importantly the comment claims the buffer "stops at the query size limit, as the final result does" — this is true only because values.size() < querySizeLimit is the loop condition, but partialRows.add(tuple) is called before the next-iteration check, so the buffer and the final result do stay in sync. Verify there is no off-by-one where partialRows ends up with querySizeLimit rows while values is capped identically (looks correct, but worth a unit test at the boundary).

  while (resultSet.next() && (querySizeLimit == null || values.size() < querySizeLimit)) {
    Map<String, ExprValue> row = new LinkedHashMap<String, ExprValue>();
    for (int i = 1; i <= columnCount; i++) {
      Object value =
          accessors != null
              ? accessors.get(i - 1).getObject()
              : resultSet.getObject(columnNames[i - 1]);
      Object converted = processValue(value, fieldTypes.get(i - 1));
      ExprValue exprValue = ExprValueUtils.fromObjectValue(converted);
      row.put(columnNames[i - 1], exprValue);
    }
    ExprValue tuple = ExprTupleValue.fromExprValueMap(row);
    values.add(tuple);
    if (partialRows != null) {
      // Warnings first, so a row is never shown without them.
      if (CalcitePlanContext.warningCount() != warningsPublished) {
        warningsPublished = CalcitePlanContext.warningCount();
        partialRows.warnings(CalcitePlanContext.peekWarnings());
      }
      partialRows.add(tuple);
    }
  }
} catch (SQLException | RuntimeException | Error e) {
  // A failed or fallen-back query must not keep showing these rows.
  if (partialRows != null) {
    partialRows.discard();
  }
  throw e;
}
Possible race between sampleCurrentResult and terminal transition

sampleCurrentResult() reads state under the monitor, releases it, then calls runner.currentResult() and returns the result. If the job transitions to SUCCEEDED/FAILED between those steps, the outer status()/running() builds a snapshot where state is terminal but current contains rows. runningOnly() filters by current state, so the end result is correct for status(); however, running() does not apply runningOnly() — it embeds whatever sampleCurrentResult returned directly into QueryResult.Running. Since running() is only invoked for the await-timeout path while the job is not terminal, this is likely benign, but the terminal-race window could publish stale current rows through QueryResult.Running after SUCCEEDED has been observed by another thread. Consider re-checking state under the monitor and dropping current if no longer RUNNING.

private QueryResult.Running running() {
  Optional<QueryResult.Rows> current = sampleCurrentResult();
  double sample = sampleRunnerProgress();
  synchronized (this) {
    double fraction = Math.min(MAX_RUNNING_FRACTION, progress(sample).fractionDone());
    return new QueryResult.Running(id, new QueryProgress(fraction), runningOnly(current));
  }
}
Thread-pool rejection fallback may still race

respondRunning is dispatched to the generic thread pool to avoid running Gson formatting on the timer thread. On a RuntimeException (e.g., EsRejectedExecutionException when the pool is saturated), the code falls back to formatting inline on the timer thread with formatRunning(running, false). This defeats the purpose of the dispatch and may block the timer thread under load. Consider failing the listener with a transient error instead, or at minimum documenting that the fallback can execute on the caller's (timer) thread.

  try {
    clientRef
        .threadPool()
        .generic()
        .execute(() -> respondRunning(running, ctxListener));
  } catch (RuntimeException e) {
    ctxListener.onResponse(
        new TransportPPLQueryResponse(formatRunning(running, false)));
  }
}

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 3fa6a0d

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Avoid double-close of runner on cancel

safeCloseRunner() is invoked unconditionally in cancel(), so if cancel() is called
after the job has already reached a terminal state (SUCCEEDED/FAILED, which also
called safeCloseRunner()), close() will be invoked twice on the runner. The javadoc
promises close() is called "once the job is terminal", and the test
close_isCalledOnceOnEachTerminalTransition expects exactly one close. Only close
when this call actually performed the terminal transition.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [215]

 if (shouldCancelRunner) {
   safeCancelRunner();
 }
 completion.cancel(false);
-safeCloseRunner();
+if (shouldCancelRunner) {
+  safeCloseRunner();
+}
Suggestion importance[1-10]: 6

__

Why: Valid observation: cancel() unconditionally calls safeCloseRunner(), which could double-close if cancel is invoked after a terminal transition. The test close_isCalledOnceOnEachTerminalTransition does call cancel() after complete() and expects one close, so this is a real concern, though close() is also documented as idempotent.

Low
General
Invalidate snapshot cache on warning change

Caching based on last.rows().size() != rows.size() means that if warnings change but
the row count hasn't, snapshot() returns the stale cached Rows with the old
warnings. Although warnings() sets last = null when the warning list changes, this
is fragile — ensure consistency by also comparing warnings, or always rebuild when
warnings differ.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialRows.java [50-63]

 public synchronized Optional<QueryResult.Rows> snapshot() {
   if (schemaOf == null || rows.isEmpty()) {
     return Optional.empty();
   }
-  if (last == null || last.rows().size() != rows.size()) {
+  if (last == null
+      || last.rows().size() != rows.size()
+      || !last.warnings().equals(warnings)) {
     List<ExprValue> copy = List.copyOf(rows);
     if (schema == null) {
       // Only the first row decides runtime-typed columns.
       schema = schemaOf.apply(copy);
     }
     last = new QueryResult.Rows(schema, copy, Cursor.None, warnings, 0);
   }
   return Optional.of(last);
 }
Suggestion importance[1-10]: 3

__

Why: The concern is partially mitigated already: warnings() sets last = null when warnings change, so the cache is invalidated. The suggestion is defensive but mostly redundant given the existing invalidation logic.

Low

Previous suggestions

Suggestions up to commit 233f737
CategorySuggestion                                                                                                                                    Impact
Possible issue
Avoid double-closing a terminal runner

cancel() calls safeCloseRunner() unconditionally, even when the job is already
terminal (SUCCEEDED/FAILED) and close() was previously invoked by
onRunnerSuccess/onRunnerFailure. This violates the "called once the job is terminal"
contract and can double-close a runner that is not strictly idempotent. Gate the
close on the actual CANCELLED transition using shouldCancelRunner (or a similar
flag) so close runs at most once.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [207-215]

 public void cancel() {
       state = QueryJobState.CANCELLED;
       completedAtMillis = OptionalLong.of(clock.millis());
       shouldCancelRunner = true;
     }
     if (shouldCancelRunner) {
       safeCancelRunner();
+      completion.cancel(false);
+      safeCloseRunner();
     }
-    completion.cancel(false);
-    safeCloseRunner();
   }
Suggestion importance[1-10]: 6

__

Why: Valid observation: safeCloseRunner() is called unconditionally in cancel(), which can double-close when the job is already terminal. The safeCloseRunner swallows exceptions, so the runtime impact is limited, but the contract violation is real.

Low
General
Flush trailing warnings to partial rows

After the loop, warnings accumulated on the final rows (or any after the last
publish) are never pushed to partialRows. A reader snapshotting between the last
warnings() call and the terminal transition can observe rows without their warnings.
Publish a final partialRows.warnings(...) after the loop (before building columns)
to flush any trailing warnings.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java [482-489]

 if (partialRows != null) {
         // Warnings first, so a row is never shown without them.
         if (CalcitePlanContext.warningCount() != warningsPublished) {
           warningsPublished = CalcitePlanContext.warningCount();
           partialRows.warnings(CalcitePlanContext.peekWarnings());
         }
         partialRows.add(tuple);
       }
+    }
+    if (partialRows != null && CalcitePlanContext.warningCount() != warningsPublished) {
+      partialRows.warnings(CalcitePlanContext.peekWarnings());
+    }
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies that warnings emitted after the last row may not be flushed to partialRows, which could affect the warnings carried by the final running snapshot. However since terminal transitions use the engine's result (not partial rows), the practical impact is modest.

Low
Null-check warnings before isEmpty

response.getWarnings() can be null on the Spark path when the underlying QueryResult
was not constructed with a warnings list; List.isEmpty() would then throw
NullPointerException. Guard against null explicitly before dereferencing.

async-query/src/main/java/org/opensearch/sql/spark/transport/format/AsyncQueryResultResponseFormatter.java [53-63]

 boolean runningJob = response.isQueryJob() && "RUNNING".equals(status);
     if ("success".equalsIgnoreCase(status) || "succeeded".equalsIgnoreCase(status) || runningJob) {
       json.total(response.size()).size(response.size());
       json.schema(
           response.columnNameTypes().entrySet().stream()
               .map((entry) -> new Column(entry.getKey(), entry.getValue()))
               .collect(Collectors.toList()));
       json.datarows(fetchDataRows(response));
-      if (!response.getWarnings().isEmpty()) {
+      if (response.getWarnings() != null && !response.getWarnings().isEmpty()) {
         json.warnings(response.getWarnings());
       }
     }
Suggestion importance[1-10]: 3

__

Why: response.getWarnings() here refers to AsyncQueryResult.getWarnings(), which comes from the parent QueryResult class. The warnings field is typically initialized to a non-null list in constructors in this PR (e.g., List.of()), reducing the likelihood of NPE, though defensive null-checking is still a minor improvement.

Low
Suggestions up to commit 9db3b41
CategorySuggestion                                                                                                                                    Impact
General
Handle race condition in state check

The method releases the monitor before calling runner.currentResult(), allowing the
state to transition from RUNNING to terminal between the check and the call. If the
runner is closed after the state check but before currentResult() is invoked, the
call may access invalid state. Consider checking the state again after obtaining the
result or handling this race condition explicitly.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [315-328]

 private Optional<QueryResult.Rows> sampleCurrentResult() {
   synchronized (this) {
     if (state != QueryJobState.RUNNING) {
       return Optional.empty();
     }
   }
   try {
     Optional<QueryResult.Rows> current = runner.currentResult();
+    synchronized (this) {
+      if (state != QueryJobState.RUNNING) {
+        return Optional.empty();
+      }
+    }
     return current == null ? Optional.empty() : current;
   } catch (RuntimeException e) {
     LOG.debug("Failed to read the rows of a running query job", e);
     return Optional.empty();
   }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential race condition where the state could transition from RUNNING to terminal between the check and the currentResult() call. Adding a second state check after obtaining the result would prevent returning stale data from a closed runner.

Medium
Broaden exception handling for thread pool

The catch block only handles RuntimeException when submitting the respondRunning
task to the thread pool. If the thread pool is shut down or in an invalid state, it
may throw RejectedExecutionException (a RuntimeException), but other Error types
could also occur. The fallback response is sent synchronously, which could block the
timer thread. Consider handling this more robustly or documenting the assumption.

plugin/src/main/java/org/opensearch/sql/plugin/transport/TransportPPLQueryAction.java [369-380]

 case org.opensearch.sql.job.QueryResult.Running running -> {
   // Wait timeouts complete on the JVM-wide timer thread; format elsewhere.
   try {
     clientRef
         .threadPool()
         .generic()
         .execute(() -> respondRunning(running, ctxListener));
-  } catch (RuntimeException e) {
+  } catch (Exception e) {
+    LOG.debug("Failed to submit running response formatting task", e);
     ctxListener.onResponse(
         new TransportPPLQueryResponse(formatRunning(running, false)));
   }
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion to catch Exception instead of just RuntimeException and add logging is reasonable for robustness. However, RejectedExecutionException is already a RuntimeException, so the functional change is mainly about catching other potential exceptions and adding logging.

Low
Log exceptions during runner cleanup

The safeCloseRunner() method silently ignores all RuntimeExceptions during runner
cleanup. This could hide critical resource leaks or cleanup failures. Consider
logging the exception at debug or warn level to aid troubleshooting while
maintaining the best-effort semantics.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [359-365]

 private void safeCloseRunner() {
   try {
     runner.close();
-  } catch (RuntimeException ignored) {
-    // Best-effort.
+  } catch (RuntimeException e) {
+    LOG.debug("Failed to close query runner", e);
   }
 }
Suggestion importance[1-10]: 5

__

Why: Logging the exception would help with debugging resource cleanup issues while maintaining best-effort semantics. However, since the method is already documented as "best-effort" and the exception is intentionally ignored, this is a minor improvement.

Low
Add logging for non-SQL exceptions

The catch block for RuntimeException | Error calls discardPartialRows() but doesn't
wrap or log the exception before rethrowing. This asymmetry with the SQLException
handler could make debugging harder. Consider logging the exception or ensuring
consistent error handling across both paths.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java [344-363]

 } catch (SQLException e) {
   discardPartialRows();
   if (isPitContextLimitReached(e)) {
     ...
   }
   throw new RuntimeException(e);
 } catch (RuntimeException | Error e) {
   discardPartialRows();
+  LOG.debug("Query execution failed, partial rows discarded", e);
   throw e;
 }
Suggestion importance[1-10]: 4

__

Why: Adding logging for consistency is a minor improvement. The asymmetry between the two catch blocks is noted, but since discardPartialRows() is called in both cases and the exception is rethrown, the functional impact is minimal.

Low
Suggestions up to commit da78e9d
CategorySuggestion                                                                                                                                    Impact
General
Prevent duplicate discard on SQLException

The SQLException handler wraps the exception in RuntimeException after calling
discardPartialRows(), but the second catch block also calls discardPartialRows() and
will catch that wrapped exception. This causes discardPartialRows() to be invoked
twice for SQL exceptions. Remove the duplicate call by handling discard only in the
second catch block.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java [344-363]

 } catch (SQLException e) {
-  discardPartialRows();
   if (isPitContextLimitReached(e)) {
     ...
   }
   throw new RuntimeException(e);
 } catch (RuntimeException | Error e) {
   discardPartialRows();
   throw e;
 }
Suggestion importance[1-10]: 8

__

Why: Valid issue. The SQLException is wrapped in RuntimeException and then caught by the second catch block, causing discardPartialRows() to be called twice. This is inefficient and could lead to unexpected behavior if the discard operation is not idempotent.

Medium
Prevent potential double listener invocation

If execute() throws (e.g., thread pool rejection), the catch block calls
ctxListener.onResponse() directly. However, respondRunning() also calls
ctxListener.onResponse() when it succeeds. If the exception occurs after the task is
queued but before it runs, both paths may invoke the listener, violating the
single-response contract. Guard against double-response by checking if the listener
has already been notified.

plugin/src/main/java/org/opensearch/sql/plugin/transport/TransportPPLQueryAction.java [369-381]

 case org.opensearch.sql.job.QueryResult.Running running -> {
   try {
     clientRef
         .threadPool()
         .generic()
         .execute(() -> respondRunning(running, ctxListener));
   } catch (RuntimeException e) {
+    // Only respond if the task wasn't queued; otherwise respondRunning will handle it
     ctxListener.onResponse(
         new TransportPPLQueryResponse(formatRunning(running, false)));
   }
 }
Suggestion importance[1-10]: 3

__

Why: The concern about double-response is valid in theory, but the catch block only catches exceptions from execute() itself (e.g., rejection before queuing), not from the queued task. Once queued, respondRunning() will handle the response. The current code appears correct, though the comment suggestion adds clarity.

Low
Suggestions up to commit 81b5c13
CategorySuggestion                                                                                                                                    Impact
General
Close runner before completing future

The runner should be closed before completing the future to prevent race conditions
where observers of the completed future might still try to sample progress or
current result from a closed runner.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [266-277]

 private void onRunnerSuccess(QueryResult value) {
   synchronized (this) {
     if (state != QueryJobState.RUNNING) {
       return;
     }
     state = QueryJobState.SUCCEEDED;
     completedAtMillis = OptionalLong.of(clock.millis());
     result = Optional.of(value);
   }
+  safeCloseRunner();
   completion.complete(value);
-  safeCloseRunner();
 }
Suggestion importance[1-10]: 4

__

Why: While the ordering concern is valid, the suggestion doesn't account for the fact that safeCloseRunner() is best-effort and the completion needs to happen regardless. The current order ensures the future completes even if closing fails, which is the safer approach.

Low
Possible issue
Guard RUNNING rows for query jobs

The RUNNING state should only return rows for query jobs, not for Spark jobs. Add a
check to ensure current is only used when the status represents a query job,
otherwise return empty schema and rows like PENDING/CANCELLED states.

async-query-core/src/main/java/org/opensearch/sql/spark/asyncquery/AsyncQueryExecutorServiceImpl.java [266-277]

-// RUNNING carries the rows produced so far, if any.
-QueryResult.Rows current = status.current().orElse(QueryResult.Rows.EMPTY);
+// RUNNING carries the rows produced so far, if any, for query jobs only.
+if (status.current().isPresent()) {
+  QueryResult.Rows current = status.current().get();
+  return new AsyncQueryExecutionResponse(
+      status.state().name(),
+      current.schema(),
+      current.rows(),
+      null,
+      null,
+      null,
+      null,
+      status.progress(),
+      current.warnings());
+}
 return new AsyncQueryExecutionResponse(
-    status.state().name(),
-    current.schema(),
-    current.rows(),
-    null,
-    null,
-    null,
-    null,
-    status.progress(),
-    current.warnings());
+    status.state().name(), EMPTY_SCHEMA, List.of(), null, null, null, null, status.progress(), List.of());
Suggestion importance[1-10]: 3

__

Why: The suggestion misunderstands the code. The current field is only present in RUNNING state per the QueryJobStatus invariants (line 88-89 in QueryJobStatus.java), so the orElse(QueryResult.Rows.EMPTY) already handles the case when current is not present. The existing code is correct.

Low
Suggestions up to commit 146638b
CategorySuggestion                                                                                                                                    Impact
General
Cache repeated method call result

The status.current() is called three times in sequence without caching the result.
If the underlying implementation is not thread-safe or has side effects, this could
lead to inconsistent data being returned (e.g., different schema, rows, or warnings
from different snapshots). Cache the result of status.current() in a local variable
before mapping.

async-query-core/src/main/java/org/opensearch/sql/spark/asyncquery/AsyncQueryExecutorServiceImpl.java [267-276]

+Optional<QueryResult.Rows> current = status.current();
 return new AsyncQueryExecutionResponse(
     status.state().name(),
-    status.current().map(QueryResult.Rows::schema).orElse(EMPTY_SCHEMA),
-    status.current().map(QueryResult.Rows::rows).orElse(List.of()),
+    current.map(QueryResult.Rows::schema).orElse(EMPTY_SCHEMA),
+    current.map(QueryResult.Rows::rows).orElse(List.of()),
     null,
     null,
     null,
     null,
     status.progress(),
-    status.current().map(QueryResult.Rows::warnings).orElse(List.of()));
+    current.map(QueryResult.Rows::warnings).orElse(List.of()));
Suggestion importance[1-10]: 7

__

Why: Caching status.current() prevents potential inconsistencies from multiple calls and improves code clarity. The suggestion correctly identifies that the method is called three times, which could lead to different snapshots if the underlying state changes between calls.

Medium
Handle schema computation exceptions safely

The schemaOf.apply(copy) is called while holding the monitor, but schemaOf is a
user-provided function that could block or throw. If it blocks, it prevents other
threads from adding rows or taking snapshots. If it throws, the monitor is released
but schema remains null, causing subsequent snapshots to retry the same failing
operation. Move the schema computation outside the synchronized block or handle
exceptions explicitly.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/progress/PartialRows.java [57-70]

 public synchronized Optional<QueryResult.Rows> snapshot() {
   if (schemaOf == null || rows.isEmpty()) {
     return Optional.empty();
   }
   if (last == null || last.rows().size() != rows.size()) {
     List<ExprValue> copy = List.copyOf(rows);
-    if (schema == null) {
-      // Fixed once there is a row: only the first row decides runtime-typed columns.
-      schema = schemaOf.apply(copy);
+    Schema computedSchema = schema;
+    if (computedSchema == null) {
+      try {
+        computedSchema = schemaOf.apply(copy);
+        schema = computedSchema;
+      } catch (RuntimeException e) {
+        // Schema computation failed; return empty to avoid blocking future snapshots
+        return Optional.empty();
+      }
     }
-    last = new QueryResult.Rows(schema, copy, Cursor.None, warnings, 0);
+    last = new QueryResult.Rows(computedSchema, copy, Cursor.None, warnings, 0);
   }
   return Optional.of(last);
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that schemaOf.apply() could throw or block while holding the monitor. However, returning Optional.empty() on exception may not be the best approach as it silently swallows errors. The concern about blocking is valid and the suggestion to handle exceptions is reasonable, though the specific implementation could be improved.

Low
Possible issue
Prevent race condition in state sampling

The sampleCurrentResult() and sampleRunnerProgress() are called outside the
synchronized block, which means the job state could transition between these calls
and the synchronized block. If the job completes after sampleCurrentResult() but
before entering the synchronized block, the status could incorrectly include current
rows for a non-RUNNING state. Consider sampling inside the synchronized block or
validating state consistency.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [117-132]

 public QueryJobStatus status() {
-  // Rows first: progress read afterwards covers at least the work behind those rows.
-  Optional<QueryResult.Rows> current = sampleCurrentResult();
-  double sample = sampleRunnerProgress();
   synchronized (this) {
+    // Sample only if RUNNING to avoid race conditions with state transitions
+    Optional<QueryResult.Rows> current = 
+        state == QueryJobState.RUNNING ? sampleCurrentResult() : Optional.empty();
+    double sample = 
+        state == QueryJobState.RUNNING ? sampleRunnerProgress() : 0D;
     return new QueryJobStatus(
         id,
         state,
         submittedAtMillis,
         startedAtMillis,
         completedAtMillis,
         failure,
         result,
         progress(sample),
         runningOnly(current));
   }
 }
Suggestion importance[1-10]: 3

__

Why: While the concern about race conditions is valid, the existing code already handles this through the runningOnly() method which filters current based on state inside the synchronized block. The suggested change would move expensive operations inside the monitor, potentially causing performance issues. The current design appears intentional.

Low

@ahkcs ahkcs added the enhancement New feature or request label Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 1122f45

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 927a191

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 146638b

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 81b5c13

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit da78e9d

@codecov

codecov Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.93939% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.15%. Comparing base (5172006) to head (3fa6a0d).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
...opensearch/executor/OpenSearchExecutionEngine.java 87.17% 2 Missing and 3 partials ⚠️
...src/main/java/org/opensearch/sql/job/QueryJob.java 91.66% 1 Missing and 1 partial ⚠️
...in/java/org/opensearch/sql/job/QueryJobStatus.java 33.33% 1 Missing and 1 partial ⚠️
.../sql/opensearch/executor/progress/PartialRows.java 96.55% 0 Missing and 1 partial ⚠️

❌ Your project check has failed because the head coverage (89.15%) is below the target coverage (99.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@              Coverage Diff              @@
##               main    #5920       +/-   ##
=============================================
+ Coverage     75.59%   89.15%   +13.55%     
- Complexity    10497    12218     +1721     
=============================================
  Files           971      979        +8     
  Lines         41474    41946      +472     
  Branches       4742     4824       +82     
=============================================
+ Hits          31353    37397     +6044     
+ Misses         8777     3077     -5700     
- Partials       1344     1472      +128     
Flag Coverage Δ
integration 69.93% <75.15%> (?)
sql-engine ?
unit 76.29% <89.09%> (?)

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.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 9db3b41

@ahkcs
ahkcs force-pushed the feat/ppl-async-partial-rows branch from 9db3b41 to 233f737 Compare November 11, 2026 19:45
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 233f737

@penghuo penghuo added the PPL Piped processing language label Nov 19, 2026
}
listener.onResponse(response);
} catch (SQLException e) {
discardPartialRows();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Which test fails if both discardPartialRows() calls (:346, :363) are removed? I removed them: :opensearch:test (1884 tests) and AsyncPPLPartialRowsIT (7/7) still pass. failureAfterRowsReturnsNoRows can't catch it, because a FAILED job never carries current (QueryJobStatus.java:88).

The discard is observable with plugins.calcite.fallback.allowed=true. I made a scan fail after about 3,000 rows had been published, by lowering plugins.query.memory_limit. With the discard, RUNNING polls show 0 rows during the ~3 s v2 fallback. Without it, they show 3,999 stale Calcite rows until FAILED.

Could we pin this with an engine unit test: a ResultSet that throws after N rows, then assert the tracker's snapshot is empty?

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.

Good catch, thanks. I moved the discard into buildResultSet, where the rows are published, and added build_result_set_discards_partial_rows_when_the_result_set_fails: the ResultSet throws after 3 rows, and the test asserts the tracker's snapshot is empty. It fails with the discard removed.

Async submit-timeout and GET responses now carry the rows the query has
produced so far. The root ResultSet only emits final rows in final
order, so buildResultSet publishes each converted row as it is read and
every response is a complete view whose rows are a prefix of the final
result; composite pages become visible the same way. A step that must
see all rows first returns rows only after reading its input, timewrap
publishes none, and rows are dropped if execution fails or falls back
to the legacy engine.

QueryRunner exposes currentResult() and close(); QueryJobStatus and
Running carry the rows only while RUNNING. Submit and GET RUNNING
bodies are rendered by the same formatter, and a query job's GET body
uses PPL type names and warnings, matching the sync response.

Resolves opensearch-project#5798

Signed-off-by: Kai Huang <[email protected]>
Signed-off-by: verify <verify@local>
@ahkcs
ahkcs force-pushed the feat/ppl-async-partial-rows branch from 233f737 to 3fa6a0d Compare November 20, 2026 21:25
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 3fa6a0d

@ahkcs
ahkcs requested a review from penghuo November 20, 2026 22:04

@penghuo penghuo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@penghuo
penghuo merged commit 059a764 into opensearch-project:main Nov 23, 2026
43 of 47 checks passed
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 rows from root ResultSet and Composite pagination

2 participants