Skip to content

fix(async-ppl): Return the job id for wait=0 when the engine fails first - #5957

Open
penghuo wants to merge 1 commit into
opensearch-project:mainfrom
penghuo:fix-async-wait-zero-sync-failure-race
Open

penghuo wants to merge 1 commit into
opensearch-project:mainfrom
penghuo:fix-async-wait-zero-sync-failure-race

Conversation

@penghuo

@penghuo penghuo commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Description

AsyncPPLMultiNodeRoutingIT.failed_forwardsFromNonOwnerNodeToOwner fails intermittently (CI run). An async PPL submit with wait_for_completion_timeout=0 sometimes returns the query error as a sync 400 instead of the job id.

Root cause. Calcite analysis, including field resolution, runs on the sql-worker thread. QueryJob.await(Duration) subscribed to the job's completion before handling a zero budget. When the worker failed before the submitting thread reached await(0), the subscription completed the result exceptionally and the Running answer was dropped.

Fix.

  • QueryJob.await answers Running for a zero budget before subscribing, so a failure on a worker thread is always reported through GET, whatever the timing.
  • A query rejected before it is handed to a worker (parse error, saturated sql-worker pool) still fails the submit inline with 400/429, as WorkerPoolSaturationIT requires. PPLService.execute reports such a rejection on the calling thread before it returns. PPLQueryRunner treats exactly that case as a refusal and throws it from run(), and QueryJob then fails await(0) with it.
wait=0 submit Before After
Rejected before reaching a worker (syntax error, sql-worker saturated) 400 / 429 400 / 429
Failed on a worker (field not found, sql-complex-worker saturated, execution error) Timing-dependent: error or job id Job id; GET reports FAILED

Requests with a positive wait_for_completion_timeout and sync requests behave as before.

QueryJobTest.await_failureAfterExpiryWithoutPollReportsOutcome asserted the racy behavior, so it is renamed to await_failureBeforeZeroBudget_stillReturnsRunning and now expects Running. PPLQueryRunnerTest.run_propagatesQueryFailure is replaced by two tests: one for a rejection on the calling thread, one for a worker failure that arrives before execute returns.

Related Issues

No issue filed; the flaky CI run is linked above.

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.
  • 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 17, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit bbdfe7e)

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

Thread-identity heuristic may misclassify

The refusal detection relies on Thread.currentThread() == submitter plus a submitting flag to distinguish a synchronous refusal from an engine failure. If PPLService.execute dispatches work synchronously on the caller thread (e.g. a validation or planning failure that calls onFailure inline from the same thread but after some work that is logically engine failure), it will be classified as a refusal and thrown from run() rather than completing the future. Conversely, if any engine path were to reuse the submitter thread for onFailure before submitting is cleared, legitimate engine failures would be reclassified as refusals. This coupling between thread identity and semantic meaning (refusal vs failure) is fragile; worth confirming via tests that cover synchronous engine-side failures on the calling thread.

@Override
public void onFailure(Exception e) {
  // execute reports a query it could not hand to a worker on this thread before it
  // returns; engine failures arrive on worker threads, possibly before execute returns.
  if (Thread.currentThread() == submitter
      && submitting.get()
      && e instanceof RuntimeException rejected) {
    refusal.set(rejected);
  } else {
    future.completeExceptionally(e);
  }
}
Possible race on refusedAtStart visibility

refusedAtStart is set in startRunner() after onRunnerFailure(e) returns. await(0) reads it without synchronization (volatile read is fine for visibility). If a caller invokes await(Duration.ZERO) concurrently with startRunner() on another thread and run() throws, await may observe refusedAtStart=false and return Running even though the job ultimately becomes FAILED due to a submission refusal. In the actual submission flow this is likely serialized, but the invariant should be documented or enforced.

public CompletionStage<QueryResult> await(Duration budget) {
  long millis = budget == null ? 0L : budget.toMillis();
  // Decided before subscribing: an engine failure that lands before this call belongs to the
  // job, and subscribing to an already-failed completion would beat the Running answer.
  if (millis <= 0L && !refusedAtStart) {
    return CompletableFuture.completedStage(running());
  }

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.13%. Comparing base (9204af9) to head (bbdfe7e).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...src/main/java/org/opensearch/sql/job/QueryJob.java 80.00% 0 Missing and 1 partial ⚠️
...in/java/org/opensearch/sql/ppl/PPLQueryRunner.java 90.90% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##               main    #5957   +/-   ##
=========================================
  Coverage     89.12%   89.13%           
- Complexity    12156    12177   +21     
=========================================
  Files           974      978    +4     
  Lines         41718    41812   +94     
  Branches       4800     4809    +9     
=========================================
+ Hits          37183    37269   +86     
- Misses         3070     3075    +5     
- Partials       1465     1468    +3     
Flag Coverage Δ
integration 69.92% <75.00%> (+0.05%) ⬆️
unit 76.24% <87.50%> (+0.03%) ⬆️

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.

@penghuo
penghuo marked this pull request as draft November 18, 2026 23:01
@penghuo
penghuo force-pushed the fix-async-wait-zero-sync-failure-race branch from 291212f to eb5e16d Compare November 18, 2026 23:01
@penghuo penghuo changed the title fix(async-ppl): wait=0 must return Running id even on sync-failure path fix(async-ppl): Return the job id for wait=0 when the engine fails first Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit eb5e16d

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to bbdfe7e

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Set refusal flag before completing failure

refusedAtStart is set after onRunnerFailure(e), which completes completion
exceptionally. A caller invoking await(Duration.ZERO) between these two statements
observes refusedAtStart == false and gets Running, missing the refusal. Set the flag
before invoking onRunnerFailure so the visibility order matches the documented
contract.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [239-243]

     stage = Objects.requireNonNull(runner.run(), "runner must not return null");
   } catch (RuntimeException e) {
+    refusedAtStart = true;
     onRunnerFailure(e);
-    refusedAtStart = true;
     return;
   }
Suggestion importance[1-10]: 8

__

Why: This is a valid race condition: onRunnerFailure completes the completion future before refusedAtStart is set, so a concurrent await(Duration.ZERO) could observe the failure-completed stage but see refusedAtStart == false and return Running, violating the documented contract. Reordering fixes the race.

Medium
Distinguish refusal from inline query failure

The heuristic (same-thread + submitting flag) misclassifies synchronous engine
failures that happen on the submitter thread (e.g., validation errors thrown by
execute and surfaced via onFailure inline) as refusals, causing QueryJob.startRunner
to treat legitimate query failures as refusals and remove the job. Consider
distinguishing refusals explicitly (e.g., a dedicated exception type or sentinel
from the executor) rather than inferring by thread identity.

ppl/src/main/java/org/opensearch/sql/ppl/PPLQueryRunner.java [93-102]

       public void onFailure(Exception e) {
-        // execute reports a query it could not hand to a worker on this thread before it
-        // returns; engine failures arrive on worker threads, possibly before execute returns.
+        // Only treat as a refusal if the executor signalled it as such; otherwise it's a
+        // normal query failure and must be delivered through the future.
         if (Thread.currentThread() == submitter
             && submitting.get()
-            && e instanceof RuntimeException rejected) {
+            && e instanceof RejectedExecutionException rejected) {
           refusal.set(rejected);
         } else {
           future.completeExceptionally(e);
         }
       }
Suggestion importance[1-10]: 7

__

Why: The suggestion highlights a real concern: the thread-identity heuristic may misclassify synchronous engine validation failures delivered on the calling thread as refusals, causing submission to fail rather than returning Running. This is a legitimate design concern, though the proposed fix (using RejectedExecutionException) may require broader changes in the executor contract.

Medium

Previous suggestions

Suggestions up to commit b9a4b9b
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve already-available successful result on zero wait

The zero-budget short-circuit returns running() even when the job has already
completed successfully (not just failed). A caller passing Duration.ZERO to a job
whose runner's stage completed with real Rows before await was invoked will now get
Running instead of the available result, which is a regression from the previous
behavior that subscribed to completion first. Consider also checking whether
completion is already completed successfully (or is cancelled) before returning
running().

core/src/main/java/org/opensearch/sql/job/QueryJob.java [144-149]

 long millis = budget == null ? 0L : budget.toMillis();
 // Decided before subscribing: an engine failure that lands before this call belongs to the
 // job, and subscribing to an already-failed completion would beat the Running answer.
-if (millis <= 0L && !refusedAtStart()) {
+if (millis <= 0L && !refusedAtStart() && !completion.isDone()) {
   return CompletableFuture.completedStage(running());
 }
Suggestion importance[1-10]: 6

__

Why: Valid concern: if the runner's stage completed successfully before await(Duration.ZERO) is called, the new short-circuit returns Running instead of the available result, which may be a behavioral regression. However, the PR's intent (per tests) seems to deliberately treat non-refusal outcomes as Running for zero budget, so the severity is moderate.

Low
General
Also treat checked synchronous failures as refusals

If execute rejects synchronously with a checked Exception (not a RuntimeException),
the current logic falls into the else branch and completes the future exceptionally
— but run() still returns the future rather than throwing, so the submission will
not fail inline as the Javadoc promises. Consider wrapping/rethrowing any
synchronously-reported exception from the submitter thread, not only
RuntimeException.

ppl/src/main/java/org/opensearch/sql/ppl/PPLQueryRunner.java [85-96]

 Consumer<Exception> onFailure =
     e -> {
       // execute reports a query it could not hand to a worker on this thread before it
       // returns; engine failures arrive on worker threads, possibly before execute returns.
-      if (Thread.currentThread() == submitter
-          && submitting.get()
-          && e instanceof RuntimeException rejected) {
-        refusal.set(rejected);
+      if (Thread.currentThread() == submitter && submitting.get()) {
+        refusal.set(
+            e instanceof RuntimeException rejected
+                ? rejected
+                : new IllegalStateException(e));
       } else {
         future.completeExceptionally(e);
       }
     };
Suggestion importance[1-10]: 4

__

Why: The point is technically valid — a checked exception reported synchronously would complete the future rather than throw from run(). In practice ResponseListener.onFailure typically receives runtime exceptions from the engine, so the impact is minor.

Low
Suggestions up to commit eb5e16d
CategorySuggestion                                                                                                                                    Impact
Possible issue
Set refusal flag before completing future

Setting refusedAtStart = true after onRunnerFailure(e) creates a race:
onRunnerFailure completes the completion future, which can trigger waiters on
another thread before refusedAtStart is set. A concurrent await(Duration.ZERO) could
observe refusedAtStart == false and return Running instead of surfacing the refusal.
Set refusedAtStart = true before invoking onRunnerFailure.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [243-252]

 CompletionStage<QueryResult> stage;
 try {
   stage = Objects.requireNonNull(runner.run(), "runner must not return null");
 } catch (RuntimeException e) {
-  onRunnerFailure(e);
   synchronized (this) {
     refusedAtStart = true;
   }
+  onRunnerFailure(e);
   return;
 }
Suggestion importance[1-10]: 8

__

Why: This identifies a legitimate race condition: onRunnerFailure(e) completes the completion future which could wake up waiters before refusedAtStart is set, causing await(Duration.ZERO) on another thread to miss the refusal signal. Reordering the assignment before onRunnerFailure is a meaningful correctness fix.

Medium
General
Clarify zero-budget behavior for completed jobs

The condition inverts the intended logic: per the Javadoc, a zero budget should
return Running UNLESS the runner was refused at start. The current code returns
Running only when refusedAtStart() is false, which is correct, but then falls
through to subscribe to completion when refused — meaning the refusal path actually
works, but a non-refused already-completed-successfully job at millis <= 0 will also
return Running instead of the actual result. Consider also checking for
already-completed success to preserve prior behavior, or confirm this trade-off is
intended.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [144-149]

+long millis = budget == null ? 0L : budget.toMillis();
+// Decided before subscribing: an engine failure that lands before this call belongs to the
+// job, and subscribing to an already-failed completion would beat the Running answer.
+if (millis <= 0L && !refusedAtStart()) {
+  return CompletableFuture.completedStage(running());
+}
 
-
Suggestion importance[1-10]: 2

__

Why: The suggestion is confused and contradictory — it acknowledges the current logic matches the Javadoc but speculates about a trade-off without clear evidence. The improved_code is identical to existing_code, offering no actionable change.

Low

@penghuo penghuo added the PPL Piped processing language label Nov 19, 2026
@penghuo
penghuo force-pushed the fix-async-wait-zero-sync-failure-race branch from eb5e16d to b9a4b9b Compare November 19, 2026 18:14
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit b9a4b9b

With wait_for_completion_timeout=0, QueryJob.await subscribed to the
job's completion before taking the Running fast path. Calcite analysis
runs on the sql-worker thread, so a fast failure there (e.g. field not
found) could complete the job before the submitting thread reached
await(0). The subscription then fired inline and the submit returned the
engine error as a sync 400 instead of the job id, which flaked
AsyncPPLMultiNodeRoutingIT.failed_forwardsFromNonOwnerNodeToOwner.

Answer Running for a zero budget before subscribing, unless the runner
refused the query while starting. PPLQueryRunner treats a failure that
PPLService.execute reports on the calling thread before it returns (a
parse error or a saturated sql-worker pool, raised before the query is
handed to a worker) as a refusal and throws it from run(); engine
failures arrive on worker threads and complete the future. Refusals
still fail the submit inline (400/429); engine failures are reported
through GET. PPLService and thread pool usage are unchanged.

Signed-off-by: Peng Huo <penghuo@gmail.com>
@penghuo
penghuo force-pushed the fix-async-wait-zero-sync-failure-race branch from b9a4b9b to bbdfe7e Compare November 19, 2026 19:31
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit bbdfe7e

@penghuo penghuo added the enhancement New feature or request label Nov 19, 2026
@penghuo
penghuo marked this pull request as ready for review November 19, 2026 21:20

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.

1 participant