Skip to content

Commit eb5e16d

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 now calls a new PPLService.submit, which throws failures raised on the submitting thread (parse errors, a saturated sql-worker pool) instead of passing them to the listener, so QueryJob can tell a refusal from an engine failure. Refusals still fail the submit inline (400/429); engine failures are reported through GET. Thread pool usage is unchanged. Signed-off-by: Peng Huo <penghuo@gmail.com>
1 parent 9204af9 commit eb5e16d

8 files changed

Lines changed: 143 additions & 19 deletions

File tree

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

Lines changed: 21 additions & 5 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 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
@@ -169,6 +176,10 @@ public CompletionStage<QueryResult> await(Duration budget) {
169176
return out.minimalCompletionStage();
170177
}
171178

179+
private synchronized boolean refusedAtStart() {
180+
return refusedAtStart;
181+
}
182+
172183
private QueryResult.Running running() {
173184
double sample = sampleRunnerProgress();
174185
synchronized (this) {
@@ -215,7 +226,9 @@ public void cancel() {
215226
*
216227
* <ul>
217228
* <li>the job has already been cancelled while pending — the runner is not started;
218-
* <li>{@code runner.run()} throws — the job moves to {@link QueryJobState#FAILED};
229+
* <li>{@code runner.run()} throws — the job moves to {@link QueryJobState#FAILED} and is
230+
* treated as refused, so {@link #await(Duration)} reports the cause even with a zero
231+
* budget;
219232
* <li>{@code runner.run()} returns {@code null} — treated as a runner failure.
220233
* </ul>
221234
*/
@@ -232,6 +245,9 @@ void startRunner() {
232245
stage = Objects.requireNonNull(runner.run(), "runner must not return null");
233246
} catch (RuntimeException e) {
234247
onRunnerFailure(e);
248+
synchronized (this) {
249+
refusedAtStart = true;
250+
}
235251
return;
236252
}
237253
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: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,34 @@ void await_zeroBudget_returnsRunningImmediately() {
223223
assertInstanceOf(QueryResult.Running.class, result);
224224
}
225225

226+
@Test
227+
void await_zeroBudget_returnsRunningWhenStageFailedBeforeAwait() {
228+
RecordingRunner runner = new RecordingRunner();
229+
// The engine thread fails the stage before await(0) subscribes: a field-not-found reported
230+
// that early is still the job's outcome, not the submission's.
231+
runner.fail(new IllegalArgumentException("Field [nonexistent_field] not found."));
232+
QueryJob job = newJob(runner, 131L);
233+
job.startRunner();
234+
QueryResult result = job.await(Duration.ZERO).toCompletableFuture().getNow(null);
235+
assertNotNull(result, "zero budget must not surface an engine failure");
236+
assertInstanceOf(QueryResult.Running.class, result);
237+
assertEquals(QueryJobState.FAILED, job.status().state());
238+
}
239+
240+
@Test
241+
void await_zeroBudget_failsWithRefusalWhenRunThrows() {
242+
RecordingRunner runner = new RecordingRunner();
243+
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
244+
runner.runError = refusal;
245+
QueryJob job = newJob(runner, 132L);
246+
job.startRunner();
247+
CompletableFuture<QueryResult> stage = job.await(Duration.ZERO).toCompletableFuture();
248+
assertTrue(stage.isDone(), "a refusal must answer the submission inline");
249+
ExecutionException ex = assertThrows(ExecutionException.class, stage::get);
250+
assertSame(refusal, ex.getCause());
251+
assertEquals(QueryJobState.FAILED, job.status().state());
252+
}
253+
226254
@Test
227255
void await_cancellationSurfacesAsExceptionalCompletion() {
228256
RecordingRunner runner = new RecordingRunner();
@@ -329,17 +357,17 @@ void progress_runnerErrorKeepsPreviousValue() {
329357
}
330358

331359
@Test
332-
void await_failureAfterExpiryWithoutPollReportsOutcome() {
360+
void await_failureBeforeZeroBudget_stillReturnsRunning() {
333361
RecordingRunner runner = new RecordingRunner();
334362
QueryJob job = newJob(runner, 226L);
335363
job.startRunner();
336364
IllegalStateException cause = new IllegalStateException("boom");
337365
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());
366+
// A failure delivered through the stage is observable via status()/GET, not the submit.
367+
QueryResult result = job.await(Duration.ZERO).toCompletableFuture().getNow(null);
368+
assertInstanceOf(QueryResult.Running.class, result);
369+
assertEquals(QueryJobState.FAILED, job.status().state());
370+
assertEquals("boom", job.status().failure().orElseThrow().reason());
343371
}
344372

345373
@Test
@@ -401,10 +429,14 @@ private static final class RecordingRunner implements QueryRunner {
401429
private volatile double progress;
402430
private volatile RuntimeException progressError;
403431
private volatile int progressCalls;
432+
private RuntimeException runError;
404433

405434
@Override
406435
public CompletionStage<QueryResult> run() {
407436
runInvocations++;
437+
if (runError != null) {
438+
throw runError;
439+
}
408440
return future;
409441
}
410442

‎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: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,10 @@
2424
/**
2525
* PPL adapter for the neutral {@link QueryRunner} SPI.
2626
*
27-
* <p>Wraps a single {@link PPLService#execute} call. Result production runs on the PPL query
27+
* <p>Wraps a single {@link PPLService#submit} call. Result production runs on the PPL query
2828
* manager's worker threads exactly as it does today; this class only bridges the callback-based
29-
* response into a {@link CompletionStage}.
29+
* response into a {@link CompletionStage}. A query refused before it reaches a worker throws from
30+
* {@link #run()}.
3031
*
3132
* <p>Cancellation is cooperative: {@link #cancel()} marks the future as cancelled so a late
3233
* response drops on the floor, and invokes the caller-supplied hook so the engine can stop the
@@ -77,7 +78,7 @@ public CompletionStage<QueryResult> run() {
7778
throw new IllegalStateException("PPLQueryRunner is single-use");
7879
}
7980
long startMillis = clock.millis();
80-
pplService.execute(
81+
pplService.submit(
8182
request,
8283
new ResponseListener<QueryResponse>() {
8384
@Override

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,25 @@ public void execute(
8484
ResponseListener<ExplainResponse> explainListener,
8585
Consumer<QueryInsightsMetadata> sink) {
8686
try {
87-
queryManager.submit(plan(request, queryListener, explainListener, sink));
87+
submit(request, queryListener, explainListener, sink);
8888
} catch (Exception e) {
8989
queryListener.onFailure(e);
9090
}
9191
}
9292

93+
/**
94+
* Like {@link #execute}, but a query refused before it reaches a worker (parse error, saturated
95+
* pool) throws instead of notifying {@code queryListener}. Later failures still go to the
96+
* listeners.
97+
*/
98+
public void submit(
99+
PPLQueryRequest request,
100+
ResponseListener<QueryResponse> queryListener,
101+
ResponseListener<ExplainResponse> explainListener,
102+
Consumer<QueryInsightsMetadata> sink) {
103+
queryManager.submit(plan(request, queryListener, explainListener, sink));
104+
}
105+
93106
/**
94107
* Explain the query in {@link PPLQueryRequest} using {@link ResponseListener} to get and format
95108
* explain response.

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

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
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;
1213
import static org.mockito.Mockito.doAnswer;
14+
import static org.mockito.Mockito.doThrow;
1315
import static org.mockito.Mockito.mock;
1416

1517
import java.time.Clock;
@@ -40,7 +42,7 @@ public void run_deliversQueryResponseThroughFuture()
4042
return null;
4143
})
4244
.when(service)
43-
.execute(any(PPLQueryRequest.class), any(), any(), any());
45+
.submit(any(PPLQueryRequest.class), any(), any(), any());
4446

4547
PPLQueryRunner runner =
4648
new PPLQueryRunner(
@@ -56,6 +58,23 @@ public void run_deliversQueryResponseThroughFuture()
5658
assertTrue(result.tookMillis() >= 0);
5759
}
5860

61+
@Test
62+
public void run_throwsWhenSubmissionIsRefused() {
63+
PPLService service = mock(PPLService.class);
64+
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
65+
doThrow(refusal).when(service).submit(any(PPLQueryRequest.class), any(), any(), any());
66+
67+
PPLQueryRunner runner =
68+
new PPLQueryRunner(
69+
service,
70+
new PPLQueryRequest("source=logs", null, "/_plugins/_ppl", "jdbc"),
71+
s -> {},
72+
Clock.systemUTC(),
73+
() -> {},
74+
() -> QueryProgress.NONE);
75+
assertSame(refusal, assertThrows(IllegalStateException.class, runner::run));
76+
}
77+
5978
@Test
6079
public void run_propagatesQueryFailure() {
6180
PPLService service = mock(PPLService.class);
@@ -66,7 +85,7 @@ public void run_propagatesQueryFailure() {
6685
return null;
6786
})
6887
.when(service)
69-
.execute(any(PPLQueryRequest.class), any(), any(), any());
88+
.submit(any(PPLQueryRequest.class), any(), any(), any());
7089

7190
PPLQueryRunner runner =
7291
new PPLQueryRunner(
@@ -152,7 +171,7 @@ public void cancel_afterCompletionDoesNotStopExecution() {
152171
return null;
153172
})
154173
.when(service)
155-
.execute(any(PPLQueryRequest.class), any(), any(), any());
174+
.submit(any(PPLQueryRequest.class), any(), any(), any());
156175
AtomicInteger stops = new AtomicInteger();
157176
PPLQueryRunner runner =
158177
new PPLQueryRunner(

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import org.junit.runner.RunWith;
2020
import org.mockito.Mock;
2121
import org.mockito.junit.MockitoJUnitRunner;
22+
import org.opensearch.sql.common.antlr.SyntaxCheckException;
2223
import org.opensearch.sql.common.response.ResponseListener;
2324
import org.opensearch.sql.common.setting.Settings;
2425
import org.opensearch.sql.executor.AnalyzeResponse;
@@ -272,6 +273,18 @@ public void testExecuteWithIllegalQueryShouldBeCaughtByHandler() {
272273
getExplainListener(false));
273274
}
274275

276+
@Test
277+
public void testSubmitWithIllegalQueryThrowsInsteadOfNotifyingListener() {
278+
Assert.assertThrows(
279+
SyntaxCheckException.class,
280+
() ->
281+
pplService.submit(
282+
new PPLQueryRequest("search", null, QUERY),
283+
getQueryListener(false),
284+
getExplainListener(false),
285+
metadata -> {}));
286+
}
287+
275288
@Test
276289
public void testExplainWithIllegalQueryShouldBeCaughtByHandler() {
277290
pplService.explain(new PPLQueryRequest("search", null, QUERY), getExplainListener(true));

0 commit comments

Comments
 (0)