Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions core/src/main/java/org/opensearch/sql/job/QueryJob.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public final class QueryJob {
private OptionalLong startedAtMillis = OptionalLong.empty();
private OptionalLong completedAtMillis = OptionalLong.empty();
private Optional<QueryFailure> failure = Optional.empty();
private volatile boolean refusedAtStart;
private Optional<QueryResult> result = Optional.empty();
private double runningFraction;

Expand Down Expand Up @@ -133,10 +134,19 @@ public QueryJobStatus status() {
* callers needing {@code ThreadContext} preserved must wrap their listener with {@code
* ContextPreservingActionListener} before registering.
*
* <p>A zero budget answers {@link QueryResult.Running} unless {@link QueryRunner#run()} threw, in
* which case the stage fails with that refusal.
*
* <p>Non-{@link Exception} throwables re-throw so JVM-level errors (e.g. {@link
* OutOfMemoryError}) are not silently downgraded to an application-level failure.
*/
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());
}
CompletableFuture<QueryResult> out = new CompletableFuture<>();
completion.whenComplete(
(value, throwable) -> {
Expand All @@ -150,10 +160,7 @@ public CompletionStage<QueryResult> await(Duration budget) {
}
out.completeExceptionally(cause);
});
long millis = budget == null ? 0L : budget.toMillis();
if (millis <= 0L) {
out.complete(running());
} else {
if (millis > 0L) {
// Cancellable, so an early outcome does not keep the job reachable until the timeout.
CompletableFuture<Void> timer = new CompletableFuture<>();
timer
Expand Down Expand Up @@ -232,6 +239,7 @@ void startRunner() {
stage = Objects.requireNonNull(runner.run(), "runner must not return null");
} catch (RuntimeException e) {
onRunnerFailure(e);
refusedAtStart = true;
return;
}
stage.whenComplete(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
*/
public interface QueryRunner {

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

/** Requests cooperative cancellation. Safe to call from any state. */
Expand Down
30 changes: 24 additions & 6 deletions core/src/test/java/org/opensearch/sql/job/QueryJobTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,20 @@ void await_zeroBudget_returnsRunningImmediately() {
assertInstanceOf(QueryResult.Running.class, result);
}

@Test
void await_zeroBudget_failsWithRefusalWhenRunThrows() {
RecordingRunner runner = new RecordingRunner();
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
runner.runError = refusal;
QueryJob job = newJob(runner, 132L);
job.startRunner();
CompletableFuture<QueryResult> stage = job.await(Duration.ZERO).toCompletableFuture();
assertTrue(stage.isDone(), "a refusal must answer the submission inline");
ExecutionException ex = assertThrows(ExecutionException.class, stage::get);
assertSame(refusal, ex.getCause());
assertEquals(QueryJobState.FAILED, job.status().state());
}

@Test
void await_cancellationSurfacesAsExceptionalCompletion() {
RecordingRunner runner = new RecordingRunner();
Expand Down Expand Up @@ -329,17 +343,17 @@ void progress_runnerErrorKeepsPreviousValue() {
}

@Test
void await_failureAfterExpiryWithoutPollReportsOutcome() {
void await_failureBeforeZeroBudget_stillReturnsRunning() {
RecordingRunner runner = new RecordingRunner();
QueryJob job = newJob(runner, 226L);
job.startRunner();
IllegalStateException cause = new IllegalStateException("boom");
runner.fail(cause);
ExecutionException ex =
assertThrows(
ExecutionException.class,
() -> job.await(Duration.ZERO).toCompletableFuture().get(1, TimeUnit.SECONDS));
assertSame(cause, ex.getCause());
// A failure delivered through the stage is observable via status()/GET, not the submit.
QueryResult result = job.await(Duration.ZERO).toCompletableFuture().getNow(null);
assertInstanceOf(QueryResult.Running.class, result);
assertEquals(QueryJobState.FAILED, job.status().state());
assertEquals("boom", job.status().failure().orElseThrow().reason());
}

@Test
Expand Down Expand Up @@ -401,10 +415,14 @@ private static final class RecordingRunner implements QueryRunner {
private volatile double progress;
private volatile RuntimeException progressError;
private volatile int progressCalls;
private RuntimeException runError;

@Override
public CompletionStage<QueryResult> run() {
runInvocations++;
if (runError != null) {
throw runError;
}
return future;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,33 @@ void submit_synchronousRunnerFailureIsRemovedAndPreservesCause() {
verifyNoInteractions(threadPool);
}

@Test
void submit_zeroWaitReturnsRunningWhenEngineFailsBeforeAwait() {
RecordingRunner runner = new RecordingRunner();
runner.fail(new IllegalArgumentException("Field [nonexistent_field] not found."));

QueryResult.Running running = submitRunning(runner);

assertEquals(QueryJobState.FAILED, service.get(running.id(), ALICE).state());
expireRetainedJob();
assertThrows(QueryJobNotFoundException.class, () -> service.get(running.id(), ALICE));
}

@Test
void submit_zeroWaitRefusalFailsSubmissionAndRemovesJob() {
QueryRunner runner = mock(QueryRunner.class);
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
when(runner.run()).thenThrow(refusal);

CompletableFuture<QueryResult> response =
service.submit(runner, ALICE, Duration.ZERO, KEEP_ALIVE).toCompletableFuture();

CompletionException failure = assertThrows(CompletionException.class, response::join);
assertSame(refusal, failure.getCause());
assertTrue(store.jobs().isEmpty());
verifyNoInteractions(threadPool);
}

@Test
void submit_runningResultRetainsCompletionUntilTtl() {
RecordingRunner runner = new RecordingRunner();
Expand Down
18 changes: 17 additions & 1 deletion ppl/src/main/java/org/opensearch/sql/ppl/PPLQueryRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.opensearch.sql.common.response.ResponseListener;
Expand Down Expand Up @@ -77,6 +78,9 @@ public CompletionStage<QueryResult> run() {
throw new IllegalStateException("PPLQueryRunner is single-use");
}
long startMillis = clock.millis();
Thread submitter = Thread.currentThread();
AtomicBoolean submitting = new AtomicBoolean(true);
AtomicReference<RuntimeException> refusal = new AtomicReference<>();
pplService.execute(
request,
new ResponseListener<QueryResponse>() {
Expand All @@ -87,7 +91,15 @@ public void onResponse(QueryResponse response) {

@Override
public void onFailure(Exception e) {
future.completeExceptionally(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);
}
}
},
new ResponseListener<ExplainResponse>() {
Expand All @@ -102,6 +114,10 @@ public void onFailure(Exception e) {
}
},
queryInsightsSink);
submitting.set(false);
if (refusal.get() != null) {
throw refusal.get();
}
return future;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package org.opensearch.sql.ppl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
Expand Down Expand Up @@ -57,12 +58,40 @@ public void run_deliversQueryResponseThroughFuture()
}

@Test
public void run_propagatesQueryFailure() {
public void run_throwsWhenExecuteRejectsOnTheCallingThread() {
PPLService service = mock(PPLService.class);
IllegalStateException refusal = new IllegalStateException("[sql-worker] saturated");
doAnswer(
invocation -> {
ResponseListener<QueryResponse> listener = invocation.getArgument(1);
listener.onFailure(new IllegalStateException("boom"));
listener.onFailure(refusal);
return null;
})
.when(service)
.execute(any(PPLQueryRequest.class), any(), any(), any());

PPLQueryRunner runner =
new PPLQueryRunner(
service,
new PPLQueryRequest("source=logs", null, "/_plugins/_ppl", "jdbc"),
s -> {},
Clock.systemUTC(),
() -> {},
() -> QueryProgress.NONE);
assertSame(refusal, assertThrows(IllegalStateException.class, runner::run));
}

@Test
public void run_reportsWorkerFailureThroughFutureEvenBeforeExecuteReturns() throws Exception {
PPLService service = mock(PPLService.class);
IllegalArgumentException failure =
new IllegalArgumentException("Field [nonexistent_field] not found.");
doAnswer(
invocation -> {
ResponseListener<QueryResponse> listener = invocation.getArgument(1);
Thread worker = new Thread(() -> listener.onFailure(failure), "sql-worker");
worker.start();
worker.join();
return null;
})
.when(service)
Expand All @@ -78,7 +107,7 @@ public void run_propagatesQueryFailure() {
() -> QueryProgress.NONE);
ExecutionException e =
assertThrows(ExecutionException.class, () -> runner.run().toCompletableFuture().get());
assertEquals("boom", e.getCause().getMessage());
assertSame(failure, e.getCause());
}

@Test
Expand Down
Loading