Skip to content

Commit bbdfe7e

Browse files
committed
fix(async-ppl): Return the job id for wait=0 when the engine fails first
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>
1 parent 9204af9 commit bbdfe7e

6 files changed

Lines changed: 116 additions & 15 deletions

File tree

‎core/src/main/java/org/opensearch/sql/job/QueryJob.java‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ public final class QueryJob {
5656
private OptionalLong startedAtMillis = OptionalLong.empty();
5757
private OptionalLong completedAtMillis = OptionalLong.empty();
5858
private Optional<QueryFailure> failure = Optional.empty();
59+
private volatile boolean refusedAtStart;
5960
private Optional<QueryResult> result = Optional.empty();
6061
private double runningFraction;
6162

@@ -133,10 +134,19 @@ public QueryJobStatus status() {
133134
* callers needing {@code ThreadContext} preserved must wrap their listener with {@code
134135
* ContextPreservingActionListener} before registering.
135136
*
137+
* <p>A zero budget answers {@link QueryResult.Running} unless {@link QueryRunner#run()} threw, in
138+
* which case the stage fails with that refusal.
139+
*
136140
* <p>Non-{@link Exception} throwables re-throw so JVM-level errors (e.g. {@link
137141
* OutOfMemoryError}) are not silently downgraded to an application-level failure.
138142
*/
139143
public CompletionStage<QueryResult> await(Duration budget) {
144+
long millis = budget == null ? 0L : budget.toMillis();
145+
// Decided before subscribing: an engine failure that lands before this call belongs to the
146+
// job, and subscribing to an already-failed completion would beat the Running answer.
147+
if (millis <= 0L && !refusedAtStart) {
148+
return CompletableFuture.completedStage(running());
149+
}
140150
CompletableFuture<QueryResult> out = new CompletableFuture<>();
141151
completion.whenComplete(
142152
(value, throwable) -> {
@@ -150,10 +160,7 @@ public CompletionStage<QueryResult> await(Duration budget) {
150160
}
151161
out.completeExceptionally(cause);
152162
});
153-
long millis = budget == null ? 0L : budget.toMillis();
154-
if (millis <= 0L) {
155-
out.complete(running());
156-
} else {
163+
if (millis > 0L) {
157164
// Cancellable, so an early outcome does not keep the job reachable until the timeout.
158165
CompletableFuture<Void> timer = new CompletableFuture<>();
159166
timer
@@ -232,6 +239,7 @@ void startRunner() {
232239
stage = Objects.requireNonNull(runner.run(), "runner must not return null");
233240
} catch (RuntimeException e) {
234241
onRunnerFailure(e);
242+
refusedAtStart = true;
235243
return;
236244
}
237245
stage.whenComplete(

‎core/src/main/java/org/opensearch/sql/job/QueryRunner.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
*/
2121
public interface QueryRunner {
2222

23-
/** Starts execution and returns the future that carries the final result. */
23+
/**
24+
* Starts execution and returns the future that carries the final result. Throws instead when the
25+
* query is refused before it starts, so the submission itself fails.
26+
*/
2427
CompletionStage<QueryResult> run();
2528

2629
/** Requests cooperative cancellation. Safe to call from any state. */

‎core/src/test/java/org/opensearch/sql/job/QueryJobTest.java‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,20 @@ void await_zeroBudget_returnsRunningImmediately() {
223223
assertInstanceOf(QueryResult.Running.class, result);
224224
}
225225

226+
@Test
227+
void await_zeroBudget_failsWithRefusalWhenRunThrows() {
228+
RecordingRunner runner = new RecordingRunner();
229+
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
230+
runner.runError = refusal;
231+
QueryJob job = newJob(runner, 132L);
232+
job.startRunner();
233+
CompletableFuture<QueryResult> stage = job.await(Duration.ZERO).toCompletableFuture();
234+
assertTrue(stage.isDone(), "a refusal must answer the submission inline");
235+
ExecutionException ex = assertThrows(ExecutionException.class, stage::get);
236+
assertSame(refusal, ex.getCause());
237+
assertEquals(QueryJobState.FAILED, job.status().state());
238+
}
239+
226240
@Test
227241
void await_cancellationSurfacesAsExceptionalCompletion() {
228242
RecordingRunner runner = new RecordingRunner();
@@ -329,17 +343,17 @@ void progress_runnerErrorKeepsPreviousValue() {
329343
}
330344

331345
@Test
332-
void await_failureAfterExpiryWithoutPollReportsOutcome() {
346+
void await_failureBeforeZeroBudget_stillReturnsRunning() {
333347
RecordingRunner runner = new RecordingRunner();
334348
QueryJob job = newJob(runner, 226L);
335349
job.startRunner();
336350
IllegalStateException cause = new IllegalStateException("boom");
337351
runner.fail(cause);
338-
ExecutionException ex =
339-
assertThrows(
340-
ExecutionException.class,
341-
() -> job.await(Duration.ZERO).toCompletableFuture().get(1, TimeUnit.SECONDS));
342-
assertSame(cause, ex.getCause());
352+
// A failure delivered through the stage is observable via status()/GET, not the submit.
353+
QueryResult result = job.await(Duration.ZERO).toCompletableFuture().getNow(null);
354+
assertInstanceOf(QueryResult.Running.class, result);
355+
assertEquals(QueryJobState.FAILED, job.status().state());
356+
assertEquals("boom", job.status().failure().orElseThrow().reason());
343357
}
344358

345359
@Test
@@ -401,10 +415,14 @@ private static final class RecordingRunner implements QueryRunner {
401415
private volatile double progress;
402416
private volatile RuntimeException progressError;
403417
private volatile int progressCalls;
418+
private RuntimeException runError;
404419

405420
@Override
406421
public CompletionStage<QueryResult> run() {
407422
runInvocations++;
423+
if (runError != null) {
424+
throw runError;
425+
}
408426
return future;
409427
}
410428

‎opensearch/src/test/java/org/opensearch/sql/job/OpenSearchQueryJobServiceTest.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,33 @@ void submit_synchronousRunnerFailureIsRemovedAndPreservesCause() {
171171
verifyNoInteractions(threadPool);
172172
}
173173

174+
@Test
175+
void submit_zeroWaitReturnsRunningWhenEngineFailsBeforeAwait() {
176+
RecordingRunner runner = new RecordingRunner();
177+
runner.fail(new IllegalArgumentException("Field [nonexistent_field] not found."));
178+
179+
QueryResult.Running running = submitRunning(runner);
180+
181+
assertEquals(QueryJobState.FAILED, service.get(running.id(), ALICE).state());
182+
expireRetainedJob();
183+
assertThrows(QueryJobNotFoundException.class, () -> service.get(running.id(), ALICE));
184+
}
185+
186+
@Test
187+
void submit_zeroWaitRefusalFailsSubmissionAndRemovesJob() {
188+
QueryRunner runner = mock(QueryRunner.class);
189+
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
190+
when(runner.run()).thenThrow(refusal);
191+
192+
CompletableFuture<QueryResult> response =
193+
service.submit(runner, ALICE, Duration.ZERO, KEEP_ALIVE).toCompletableFuture();
194+
195+
CompletionException failure = assertThrows(CompletionException.class, response::join);
196+
assertSame(refusal, failure.getCause());
197+
assertTrue(store.jobs().isEmpty());
198+
verifyNoInteractions(threadPool);
199+
}
200+
174201
@Test
175202
void submit_runningResultRetainsCompletionUntilTtl() {
176203
RecordingRunner runner = new RecordingRunner();

‎ppl/src/main/java/org/opensearch/sql/ppl/PPLQueryRunner.java‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import java.util.concurrent.CompletableFuture;
1212
import java.util.concurrent.CompletionStage;
1313
import java.util.concurrent.atomic.AtomicBoolean;
14+
import java.util.concurrent.atomic.AtomicReference;
1415
import java.util.function.Consumer;
1516
import java.util.function.Supplier;
1617
import org.opensearch.sql.common.response.ResponseListener;
@@ -77,6 +78,9 @@ public CompletionStage<QueryResult> run() {
7778
throw new IllegalStateException("PPLQueryRunner is single-use");
7879
}
7980
long startMillis = clock.millis();
81+
Thread submitter = Thread.currentThread();
82+
AtomicBoolean submitting = new AtomicBoolean(true);
83+
AtomicReference<RuntimeException> refusal = new AtomicReference<>();
8084
pplService.execute(
8185
request,
8286
new ResponseListener<QueryResponse>() {
@@ -87,7 +91,15 @@ public void onResponse(QueryResponse response) {
8791

8892
@Override
8993
public void onFailure(Exception e) {
90-
future.completeExceptionally(e);
94+
// execute reports a query it could not hand to a worker on this thread before it
95+
// returns; engine failures arrive on worker threads, possibly before execute returns.
96+
if (Thread.currentThread() == submitter
97+
&& submitting.get()
98+
&& e instanceof RuntimeException rejected) {
99+
refusal.set(rejected);
100+
} else {
101+
future.completeExceptionally(e);
102+
}
91103
}
92104
},
93105
new ResponseListener<ExplainResponse>() {
@@ -102,6 +114,10 @@ public void onFailure(Exception e) {
102114
}
103115
},
104116
queryInsightsSink);
117+
submitting.set(false);
118+
if (refusal.get() != null) {
119+
throw refusal.get();
120+
}
105121
return future;
106122
}
107123

‎ppl/src/test/java/org/opensearch/sql/ppl/PPLQueryRunnerTest.java‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package org.opensearch.sql.ppl;
77

88
import static org.junit.Assert.assertEquals;
9+
import static org.junit.Assert.assertSame;
910
import static org.junit.Assert.assertThrows;
1011
import static org.junit.Assert.assertTrue;
1112
import static org.mockito.ArgumentMatchers.any;
@@ -57,12 +58,40 @@ public void run_deliversQueryResponseThroughFuture()
5758
}
5859

5960
@Test
60-
public void run_propagatesQueryFailure() {
61+
public void run_throwsWhenExecuteRejectsOnTheCallingThread() {
6162
PPLService service = mock(PPLService.class);
63+
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
6264
doAnswer(
6365
invocation -> {
6466
ResponseListener<QueryResponse> listener = invocation.getArgument(1);
65-
listener.onFailure(new IllegalStateException("boom"));
67+
listener.onFailure(refusal);
68+
return null;
69+
})
70+
.when(service)
71+
.execute(any(PPLQueryRequest.class), any(), any(), any());
72+
73+
PPLQueryRunner runner =
74+
new PPLQueryRunner(
75+
service,
76+
new PPLQueryRequest("source=logs", null, "/_plugins/_ppl", "jdbc"),
77+
s -> {},
78+
Clock.systemUTC(),
79+
() -> {},
80+
() -> QueryProgress.NONE);
81+
assertSame(refusal, assertThrows(IllegalStateException.class, runner::run));
82+
}
83+
84+
@Test
85+
public void run_reportsWorkerFailureThroughFutureEvenBeforeExecuteReturns() throws Exception {
86+
PPLService service = mock(PPLService.class);
87+
IllegalArgumentException failure =
88+
new IllegalArgumentException("Field [nonexistent_field] not found.");
89+
doAnswer(
90+
invocation -> {
91+
ResponseListener<QueryResponse> listener = invocation.getArgument(1);
92+
Thread worker = new Thread(() -> listener.onFailure(failure), "sql-worker");
93+
worker.start();
94+
worker.join();
6695
return null;
6796
})
6897
.when(service)
@@ -78,7 +107,7 @@ public void run_propagatesQueryFailure() {
78107
() -> QueryProgress.NONE);
79108
ExecutionException e =
80109
assertThrows(ExecutionException.class, () -> runner.run().toCompletableFuture().get());
81-
assertEquals("boom", e.getCause().getMessage());
110+
assertSame(failure, e.getCause());
82111
}
83112

84113
@Test

0 commit comments

Comments
 (0)