Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,17 @@ public AsyncQueryExecutionResponse getAsyncQueryResults(
throw new AsyncQueryNotFoundException(String.format("QueryId: %s not found", queryId));
}

/**
* Deletes a {@link QueryJobId} through {@link QueryJobService#delete} and returns the job's final
* state name ({@code CANCELLED}, {@code SUCCEEDED}, or {@code FAILED}); cancels any other id on
* the Spark path and returns the cancelled query id.
*/
@Override
public String cancelQuery(String queryId, AsyncQueryRequestContext asyncQueryRequestContext) {
Optional<QueryJobId> jobId = asJobId(queryId);
if (jobId.isPresent() && queryJobService != null) {
return queryJobService.delete(jobId.get(), currentPrincipal()).state().name();
}
Optional<AsyncQueryJobMetadata> asyncQueryJobMetadata =
asyncQueryJobMetadataStorageService.getJobMetadata(queryId);
if (asyncQueryJobMetadata.isPresent()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,87 @@ void ownershipDenialPropagatesWithoutSparkFallback() {
verifyNoSparkCalls();
}

@Test
void cancelDeletesPplJobWithCurrentPrincipalAndReturnsFinalState() {
when(securityAdapter.current()).thenReturn(ALICE);
when(jobService.delete(JOB_ID, ALICE))
.thenReturn(snapshot(QueryJobState.CANCELLED, Optional.empty(), Optional.empty()));

assertEquals("CANCELLED", cancel());

verify(jobService).delete(JOB_ID, ALICE);
verifyNoSparkCalls();
}

@Test
void cancelOfTerminalPplJobReturnsPriorState() {
when(securityAdapter.current()).thenReturn(ALICE);
when(jobService.delete(JOB_ID, ALICE))
.thenReturn(snapshot(QueryJobState.FAILED, Optional.empty(), Optional.empty()));

assertEquals("FAILED", cancel());
verifyNoSparkCalls();
}

@Test
void cancelOfMissingPplJobPropagatesWithoutSparkFallback() {
when(securityAdapter.current()).thenReturn(ALICE);
QueryJobNotFoundException missing = new QueryJobNotFoundException(JOB_ID);
when(jobService.delete(JOB_ID, ALICE)).thenThrow(missing);

assertSame(missing, assertThrows(QueryJobNotFoundException.class, this::cancel));
verifyNoSparkCalls();
}

@Test
void cancelOwnershipDenialPropagatesWithoutSparkFallback() {
when(securityAdapter.current()).thenReturn(ALICE);
QueryJobForbiddenException forbidden = new QueryJobForbiddenException();
when(jobService.delete(JOB_ID, ALICE)).thenThrow(forbidden);

assertSame(forbidden, assertThrows(QueryJobForbiddenException.class, this::cancel));
verifyNoSparkCalls();
}

@Test
void cancelWithoutSecurityAdapterUsesUnsecuredPrincipal() {
service =
new AsyncQueryExecutorServiceImpl(
metadataStorage, sparkDispatcher, sparkConfig, jobService, null);
when(jobService.delete(JOB_ID, Principal.UNSECURED))
.thenReturn(snapshot(QueryJobState.CANCELLED, Optional.empty(), Optional.empty()));

assertEquals("CANCELLED", cancel());

verifyNoInteractions(securityAdapter);
verifyNoSparkCalls();
}

@Test
void sparkOnlyServiceKeepsJobIdsOnSparkCancelPath() {
service = new AsyncQueryExecutorServiceImpl(metadataStorage, sparkDispatcher, sparkConfig);
when(metadataStorage.getJobMetadata(JOB_ID.encode())).thenReturn(Optional.empty());

assertThrows(AsyncQueryNotFoundException.class, this::cancel);

verifyNoInteractions(jobService, securityAdapter, sparkDispatcher, sparkConfig);
}

@Test
void malformedJobIdKeepsSparkCancelPath() {
when(metadataStorage.getJobMetadata("spark-query-id")).thenReturn(Optional.empty());

assertThrows(
AsyncQueryNotFoundException.class,
() -> service.cancelQuery("spark-query-id", requestContext));

verifyNoInteractions(jobService, securityAdapter, sparkDispatcher, sparkConfig);
}

private String cancel() {
return service.cancelQuery(JOB_ID.encode(), requestContext);
}

private AsyncQueryExecutionResponse fetch() {
return service.getAsyncQueryResults(JOB_ID.encode(), requestContext);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import static org.opensearch.rest.RestRequest.Method.DELETE;
import static org.opensearch.rest.RestRequest.Method.GET;
import static org.opensearch.rest.RestRequest.Method.POST;
import static org.opensearch.sql.opensearch.executor.OpenSearchQueryManager.SQL_WORKER_THREAD_POOL_NAME;

import com.google.common.collect.ImmutableList;
import java.io.IOException;
Expand Down Expand Up @@ -47,6 +48,7 @@
import org.opensearch.sql.spark.transport.model.CreateAsyncQueryActionResponse;
import org.opensearch.sql.spark.transport.model.GetAsyncQueryResultActionRequest;
import org.opensearch.sql.spark.transport.model.GetAsyncQueryResultActionResponse;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.client.node.NodeClient;

@RequiredArgsConstructor
Expand Down Expand Up @@ -213,6 +215,13 @@ private void handleException(
private RestChannelConsumer executeDeleteRequest(RestRequest restRequest, NodeClient nodeClient) {
MetricUtils.incrementNumericalMetric(MetricName.ASYNC_QUERY_CANCEL_API_REQUEST_COUNT);
String queryId = restRequest.param("queryId");
boolean isPpl = isPplRequest(restRequest);
// PPL jobs acknowledge with their final status; Spark keeps its existing 204 contract.
RestStatus successStatus = isPpl ? RestStatus.OK : RestStatus.NO_CONTENT;
// PPL DELETE is a store lookup and a cancel — cheap and non-blocking. Route it off sql-worker
// so a saturated query pool can't delay cancellations that are supposed to free that pool up.
// Spark DELETE still runs on sql-worker to preserve its existing dispatch contract.
String poolName = isPpl ? ThreadPool.Names.GENERIC : SQL_WORKER_THREAD_POOL_NAME;
return restChannel ->
Scheduler.schedule(
Comment thread
ahkcs marked this conversation as resolved.
Resolved
nodeClient,
Expand All @@ -226,7 +235,7 @@ public void onResponse(
CancelAsyncQueryActionResponse cancelAsyncQueryActionResponse) {
restChannel.sendResponse(
new BytesRestResponse(
RestStatus.NO_CONTENT,
successStatus,
"application/json; charset=UTF-8",
cancelAsyncQueryActionResponse.getResult()));
}
Expand All @@ -235,7 +244,8 @@ public void onResponse(
public void onFailure(Exception e) {
handleException(e, restChannel, restRequest.method());
}
}));
}),
poolName);
}

private void reportError(final RestChannel channel, final Exception e, final RestStatus status) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

package org.opensearch.sql.spark.transport;

import org.opensearch.ExceptionsHelper;
import org.opensearch.ResourceNotFoundException;
import org.opensearch.action.ActionListenerResponseHandler;
import org.opensearch.action.ActionRequest;
import org.opensearch.cluster.node.DiscoveryNode;
Expand All @@ -13,7 +15,6 @@
import org.opensearch.core.action.ActionResponse;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.sql.job.QueryJobId;
import org.opensearch.sql.spark.asyncquery.exceptions.AsyncQueryNotFoundException;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.TransportRequestOptions;
import org.opensearch.transport.TransportService;
Expand All @@ -36,6 +37,12 @@ private AsyncQueryOwnerRouting() {}
/**
* Forwards {@code request} to the node identified by {@code jobId.ownerNodeId()}.
*
* <p>Owner node absent from the current cluster state surfaces as {@link
* ResourceNotFoundException} (a transport-serializable 404), so GET and DELETE agree on status
* when the owner has left the cluster. Cross-node failures arrive wrapped in {@code
* RemoteTransportException}; the listener is wrapped to unwrap the cause before returning, so
* the client sees the real exception (and not the owner node's hostname/port).
*
* @param clusterService source of the current cluster state and node roster
* @param transportService transport client used to issue the cross-node send
* @param jobId parsed id whose {@code ownerNodeId} names the target node
Expand All @@ -57,14 +64,22 @@ static <RespT extends ActionResponse> void forwardToOwner(
DiscoveryNode ownerNode = clusterService.state().nodes().get(jobId.ownerNodeId());
if (ownerNode == null) {
listener.onFailure(
new AsyncQueryNotFoundException("QueryId: " + jobId.encode() + " not found"));
new ResourceNotFoundException("QueryId: " + jobId.encode() + " not found"));
return;
}
ActionListener<RespT> unwrapping =
ActionListener.wrap(
listener::onResponse,
failure -> {
Throwable cause = ExceptionsHelper.unwrapCause(failure);
listener.onFailure(
cause instanceof Exception ? (Exception) cause : new RuntimeException(cause));
});
transportService.sendRequest(
ownerNode,
actionName,
request,
TransportRequestOptions.EMPTY,
new ActionListenerResponseHandler<>(listener, responseReader, ThreadPool.Names.SAME));
new ActionListenerResponseHandler<>(unwrapping, responseReader, ThreadPool.Names.SAME));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,20 @@

package org.opensearch.sql.spark.transport;

import java.util.Optional;
import org.json.JSONObject;
import org.opensearch.OpenSearchStatusException;
import org.opensearch.ResourceNotFoundException;
import org.opensearch.action.ActionType;
import org.opensearch.action.support.ActionFilters;
import org.opensearch.action.support.HandledTransportAction;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.inject.Inject;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.sql.job.QueryJobId;
import org.opensearch.sql.job.exceptions.QueryJobForbiddenException;
import org.opensearch.sql.job.exceptions.QueryJobNotFoundException;
import org.opensearch.sql.spark.asyncquery.AsyncQueryExecutorServiceImpl;
import org.opensearch.sql.spark.asyncquery.model.NullAsyncQueryRequestContext;
import org.opensearch.sql.spark.transport.model.CancelAsyncQueryActionRequest;
Expand All @@ -24,16 +33,21 @@ public class TransportCancelAsyncQueryRequestAction

public static final String NAME = "cluster:admin/opensearch/ql/async_query/delete";
private final AsyncQueryExecutorServiceImpl asyncQueryExecutorService;
private final ClusterService clusterService;
private final TransportService transportService;
public static final ActionType<CancelAsyncQueryActionResponse> ACTION_TYPE =
new ActionType<>(NAME, CancelAsyncQueryActionResponse::new);

@Inject
public TransportCancelAsyncQueryRequestAction(
TransportService transportService,
ActionFilters actionFilters,
ClusterService clusterService,
AsyncQueryExecutorServiceImpl asyncQueryExecutorService) {
super(NAME, transportService, actionFilters, CancelAsyncQueryActionRequest::new);
this.asyncQueryExecutorService = asyncQueryExecutorService;
this.clusterService = clusterService;
this.transportService = transportService;
}

@Override
Expand All @@ -42,12 +56,31 @@ protected void doExecute(
CancelAsyncQueryActionRequest request,
ActionListener<CancelAsyncQueryActionResponse> listener) {
try {
String jobId =
asyncQueryExecutorService.cancelQuery(
request.getQueryId(), new NullAsyncQueryRequestContext());
String queryId = request.getQueryId();
Optional<QueryJobId> parsed = QueryJobId.tryParse(queryId);
if (parsed.isPresent()
&& !clusterService.localNode().getId().equals(parsed.get().ownerNodeId())) {
AsyncQueryOwnerRouting.forwardToOwner(
clusterService,
transportService,
parsed.get(),
NAME,
request,
CancelAsyncQueryActionResponse::new,
listener);
return;
}
String result =
asyncQueryExecutorService.cancelQuery(queryId, new NullAsyncQueryRequestContext());
listener.onResponse(
new CancelAsyncQueryActionResponse(
String.format("Deleted async query with id: %s", jobId)));
parsed.isPresent()
? new JSONObject().put("status", result).toString()
: String.format("Deleted async query with id: %s", result)));
} catch (QueryJobNotFoundException e) {
listener.onFailure(new ResourceNotFoundException(e.getMessage()));
} catch (QueryJobForbiddenException e) {
listener.onFailure(new OpenSearchStatusException(e.getMessage(), RestStatus.FORBIDDEN));
} catch (Exception e) {
listener.onFailure(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionRequestValidationException;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;

@AllArgsConstructor
@Getter
Expand All @@ -21,6 +22,13 @@ public class CancelAsyncQueryActionRequest extends ActionRequest {
/** Constructor of SubmitJobActionRequest from StreamInput. */
public CancelAsyncQueryActionRequest(StreamInput in) throws IOException {
super(in);
this.queryId = in.readOptionalString();
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalString(queryId);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.rest.RestChannel;
import org.opensearch.rest.RestRequest;
import org.opensearch.rest.RestResponse;
import org.opensearch.sql.common.setting.Settings;
import org.opensearch.sql.opensearch.setting.OpenSearchSettings;
import org.opensearch.sql.spark.transport.TransportCancelAsyncQueryRequestAction;
import org.opensearch.sql.spark.transport.model.CancelAsyncQueryActionRequest;
import org.opensearch.sql.spark.transport.model.CancelAsyncQueryActionResponse;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.client.node.NodeClient;

Expand Down Expand Up @@ -140,6 +145,54 @@ public void pplGet_passesWhenDataSourcesDisabled() {
Mockito.verifyNoInteractions(channel);
}

@Test
@SneakyThrows
public void pplDelete_respondsOkWithStatusAcknowledgement() {
setDataSourcesEnabled(false);
String acknowledgement = "{\"status\":\"CANCELLED\"}";

RestResponse response =
deleteAndRespond(
org.opensearch.sql.job.QueryJobId.create("node-a").encode(), acknowledgement);

Assertions.assertEquals(RestStatus.OK, response.status());
Assertions.assertEquals(acknowledgement, response.content().utf8ToString());
}

@Test
@SneakyThrows
public void sparkDelete_keepsNoContentStatus() {
setDataSourcesEnabled(true);

RestResponse response =
deleteAndRespond("00abc1234efghij5", "Deleted async query with id: 00abc1234efghij5");

Assertions.assertEquals(RestStatus.NO_CONTENT, response.status());
}

@SuppressWarnings("unchecked")
private RestResponse deleteAndRespond(String queryId, String transportResult) throws Exception {
Mockito.when(request.method()).thenReturn(RestRequest.Method.DELETE);
Mockito.when(request.param("queryId")).thenReturn(queryId);
unit.handleRequest(request, channel, nodeClient);
ArgumentCaptor<Runnable> scheduled = ArgumentCaptor.forClass(Runnable.class);
Mockito.verify(threadPool)
.schedule(scheduled.capture(), ArgumentMatchers.any(), ArgumentMatchers.any());
scheduled.getValue().run();
ArgumentCaptor<ActionListener<CancelAsyncQueryActionResponse>> listener =
ArgumentCaptor.forClass(ActionListener.class);
Mockito.verify(nodeClient)
.execute(
ArgumentMatchers.eq(TransportCancelAsyncQueryRequestAction.ACTION_TYPE),
ArgumentMatchers.argThat(
(CancelAsyncQueryActionRequest r) -> queryId.equals(r.getQueryId())),
listener.capture());
listener.getValue().onResponse(new CancelAsyncQueryActionResponse(transportResult));
ArgumentCaptor<RestResponse> response = ArgumentCaptor.forClass(RestResponse.class);
Mockito.verify(channel).sendResponse(response.capture());
return response.getValue();
}

private void setDataSourcesEnabled(boolean value) {
Mockito.when(settings.getSettingValue(Settings.Key.DATASOURCES_ENABLED)).thenReturn(value);
}
Expand Down
Loading
Loading