Skip to content

Commit 059a764

Browse files
authored
Publish partial rows for asynchronous Calcite PPL queries (#5920)
Signed-off-by: Kai Huang <ahkcs@amazon.com>
1 parent 69d9612 commit 059a764

30 files changed

Lines changed: 1169 additions & 111 deletions

File tree

‎async-query-core/src/main/java/org/opensearch/sql/spark/asyncquery/AsyncQueryExecutorServiceImpl.java‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -220,8 +220,8 @@ private Principal currentPrincipal() {
220220
* Maps a neutral {@link QueryJobStatus} onto the response shape the async-query transport actions
221221
* already know how to format. Terminal SUCCEEDED carries schema and rows for the {@link
222222
* QueryResult.Rows} variant, or the explain response in {@code explain} for the {@link
223-
* QueryResult.Explain} variant. FAILED carries a sanitized error; RUNNING / PENDING / CANCELLED
224-
* carry no rows.
223+
* QueryResult.Explain} variant. FAILED carries a sanitized error, RUNNING the rows produced so
224+
* far, and PENDING / CANCELLED no rows.
225225
*/
226226
private static AsyncQueryExecutionResponse toAsyncResponse(QueryJobStatus status) {
227227
if (status.state() == QueryJobState.SUCCEEDED && status.result().isPresent()) {
@@ -235,7 +235,8 @@ private static AsyncQueryExecutionResponse toAsyncResponse(QueryJobStatus status
235235
null,
236236
null,
237237
null,
238-
status.progress());
238+
status.progress(),
239+
rows.warnings());
239240
}
240241
if (result instanceof QueryResult.Explain explain) {
241242
return new AsyncQueryExecutionResponse(
@@ -259,9 +260,19 @@ private static AsyncQueryExecutionResponse toAsyncResponse(QueryJobStatus status
259260
null,
260261
null,
261262
details,
262-
status.progress());
263+
status.progress(),
264+
List.of());
263265
}
266+
QueryResult.Rows current = status.current().orElse(QueryResult.Rows.EMPTY);
264267
return new AsyncQueryExecutionResponse(
265-
status.state().name(), EMPTY_SCHEMA, List.of(), null, null, null, null, status.progress());
268+
status.state().name(),
269+
current.schema(),
270+
current.rows(),
271+
null,
272+
null,
273+
null,
274+
null,
275+
status.progress(),
276+
current.warnings());
266277
}
267278
}

‎async-query-core/src/main/java/org/opensearch/sql/spark/asyncquery/model/AsyncQueryExecutionResponse.java‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import lombok.Data;
1111
import org.opensearch.sql.data.model.ExprValue;
1212
import org.opensearch.sql.executor.ExecutionEngine;
13+
import org.opensearch.sql.executor.Warning;
1314
import org.opensearch.sql.job.QueryProgress;
1415

1516
/** AsyncQueryExecutionResponse to store the response form spark job execution. */
@@ -40,6 +41,10 @@ public class AsyncQueryExecutionResponse {
4041
/** {@code null} on the Spark path. */
4142
private final QueryProgress progress;
4243

44+
private final List<Warning> warnings;
45+
46+
private final boolean queryJob;
47+
4348
/** Spark-shaped constructor; keeps callers that never populate structured error details. */
4449
public AsyncQueryExecutionResponse(
4550
String status,
@@ -62,7 +67,16 @@ public AsyncQueryExecutionResponse(
6267
String sessionId,
6368
ExecutionEngine.ExplainResponse explain,
6469
Map<String, Object> errorDetails) {
65-
this(status, schema, results, error, sessionId, explain, errorDetails, null);
70+
this.status = status;
71+
this.schema = schema;
72+
this.results = results;
73+
this.error = error;
74+
this.sessionId = sessionId;
75+
this.explain = explain;
76+
this.errorDetails = errorDetails;
77+
this.progress = null;
78+
this.warnings = List.of();
79+
this.queryJob = false;
6680
}
6781

6882
public AsyncQueryExecutionResponse(
@@ -73,7 +87,8 @@ public AsyncQueryExecutionResponse(
7387
String sessionId,
7488
ExecutionEngine.ExplainResponse explain,
7589
Map<String, Object> errorDetails,
76-
QueryProgress progress) {
90+
QueryProgress progress,
91+
List<Warning> warnings) {
7792
this.status = status;
7893
this.schema = schema;
7994
this.results = results;
@@ -82,5 +97,7 @@ public AsyncQueryExecutionResponse(
8297
this.explain = explain;
8398
this.errorDetails = errorDetails;
8499
this.progress = progress;
100+
this.warnings = warnings;
101+
this.queryJob = true;
85102
}
86103
}

‎async-query-core/src/test/java/org/opensearch/sql/spark/asyncquery/AsyncQueryExecutorServiceRoutingTest.java‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import static org.junit.jupiter.api.Assertions.assertNull;
1010
import static org.junit.jupiter.api.Assertions.assertSame;
1111
import static org.junit.jupiter.api.Assertions.assertThrows;
12+
import static org.junit.jupiter.api.Assertions.assertTrue;
1213
import static org.mockito.Mockito.verify;
1314
import static org.mockito.Mockito.verifyNoInteractions;
1415
import static org.mockito.Mockito.when;
@@ -160,13 +161,41 @@ void jobSnapshotsCarryProgress() {
160161
OptionalLong.empty(),
161162
Optional.empty(),
162163
Optional.empty(),
163-
new QueryProgress(0.4D)));
164+
new QueryProgress(0.4D),
165+
Optional.empty()));
164166
assertEquals(0.4D, fetch().getProgress().fractionDone());
165167

166168
stubSnapshot(QueryJobState.FAILED, Optional.empty(), Optional.empty());
167169
assertEquals(0D, fetch().getProgress().fractionDone());
168170
}
169171

172+
@Test
173+
void runningSnapshotCarriesRowsSoFar() {
174+
Schema schema = new Schema(List.of(new Schema.Column("count", null, INTEGER)));
175+
QueryResult.Rows current =
176+
new QueryResult.Rows(schema, List.of(tupleValue(Map.of("count", 3))), null, null, 0);
177+
when(securityAdapter.current()).thenReturn(ALICE);
178+
when(jobService.get(JOB_ID, ALICE))
179+
.thenReturn(
180+
new QueryJobStatus(
181+
JOB_ID,
182+
QueryJobState.RUNNING,
183+
0,
184+
OptionalLong.of(1),
185+
OptionalLong.empty(),
186+
Optional.empty(),
187+
Optional.empty(),
188+
new QueryProgress(0.4D),
189+
Optional.of(current)));
190+
191+
AsyncQueryExecutionResponse response = fetch();
192+
193+
assertEquals("RUNNING", response.getStatus());
194+
assertSame(schema, response.getSchema());
195+
assertEquals(current.rows(), response.getResults());
196+
assertTrue(response.isQueryJob());
197+
}
198+
170199
@Test
171200
void succeededSnapshotReportsFullProgress() {
172201
Schema schema = new Schema(List.of(new Schema.Column("count", null, INTEGER)));
@@ -213,7 +242,7 @@ private void assertSnapshotWithoutResult(QueryJobState state) {
213242
void runningMarkerIsNotRenderedAsFinalRows() {
214243
stubSnapshot(
215244
QueryJobState.SUCCEEDED,
216-
Optional.of(new QueryResult.Running(JOB_ID, QueryProgress.NONE)),
245+
Optional.of(new QueryResult.Running(JOB_ID, QueryProgress.NONE, Optional.empty())),
217246
Optional.empty());
218247

219248
AsyncQueryExecutionResponse response = fetch();
@@ -400,7 +429,8 @@ private QueryJobStatus snapshot(
400429
state.isTerminal() ? OptionalLong.of(2) : OptionalLong.empty(),
401430
failure,
402431
result,
403-
state == QueryJobState.SUCCEEDED ? QueryProgress.DONE : QueryProgress.NONE);
432+
state == QueryJobState.SUCCEEDED ? QueryProgress.DONE : QueryProgress.NONE,
433+
Optional.empty());
404434
}
405435

406436
private void assertEmptyResults(AsyncQueryExecutionResponse response) {

‎async-query/src/main/java/org/opensearch/sql/spark/transport/TransportGetAsyncQueryResultAction.java‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,16 +85,25 @@ protected void doExecute(
8585
}
8686
ResponseFormatter<AsyncQueryResult> formatter =
8787
new AsyncQueryResultResponseFormatter(JsonResponseFormatter.Style.PRETTY);
88-
String responseContent =
89-
formatter.format(
90-
new AsyncQueryResult(
88+
AsyncQueryResult result =
89+
asyncQueryExecutionResponse.isQueryJob()
90+
? AsyncQueryResult.forQueryJob(
9191
asyncQueryExecutionResponse.getStatus(),
9292
asyncQueryExecutionResponse.getSchema(),
9393
asyncQueryExecutionResponse.getResults(),
94-
Cursor.None,
9594
asyncQueryExecutionResponse.getError(),
9695
asyncQueryExecutionResponse.getErrorDetails(),
97-
asyncQueryExecutionResponse.getProgress()));
96+
asyncQueryExecutionResponse.getProgress(),
97+
null,
98+
asyncQueryExecutionResponse.getWarnings())
99+
: new AsyncQueryResult(
100+
asyncQueryExecutionResponse.getStatus(),
101+
asyncQueryExecutionResponse.getSchema(),
102+
asyncQueryExecutionResponse.getResults(),
103+
Cursor.None,
104+
asyncQueryExecutionResponse.getError(),
105+
asyncQueryExecutionResponse.getErrorDetails());
106+
String responseContent = formatter.format(result);
98107
listener.onResponse(new GetAsyncQueryResultActionResponse(responseContent));
99108
} catch (org.opensearch.sql.job.exceptions.QueryJobNotFoundException e) {
100109
// Translate to a transport-serializable OpenSearchException so cross-node forwarding

‎async-query/src/main/java/org/opensearch/sql/spark/transport/format/AsyncQueryResultResponseFormatter.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import lombok.Getter;
1414
import lombok.RequiredArgsConstructor;
1515
import org.opensearch.core.common.Strings;
16+
import org.opensearch.sql.executor.Warning;
1617
import org.opensearch.sql.protocol.response.QueryResult;
1718
import org.opensearch.sql.protocol.response.format.JsonResponseFormatter;
1819
import org.opensearch.sql.spark.transport.model.AsyncQueryResult;
@@ -49,14 +50,19 @@ public Object buildJsonObject(AsyncQueryResult response) {
4950
String status = response.getStatus();
5051
// "SUCCESS" is the legacy Spark job-run state; "SUCCEEDED" is the neutral QueryJobState name
5152
// emitted by the id-shape routing path (issue #5765).
52-
if ("success".equalsIgnoreCase(status) || "succeeded".equalsIgnoreCase(status)) {
53+
boolean runningJob = response.isQueryJob() && "RUNNING".equals(status);
54+
if ("success".equalsIgnoreCase(status) || "succeeded".equalsIgnoreCase(status) || runningJob) {
5355
json.total(response.size()).size(response.size());
5456
json.schema(
5557
response.columnNameTypes().entrySet().stream()
5658
.map((entry) -> new Column(entry.getKey(), entry.getValue()))
5759
.collect(Collectors.toList()));
5860
json.datarows(fetchDataRows(response));
61+
if (!response.getWarnings().isEmpty()) {
62+
json.warnings(response.getWarnings());
63+
}
5964
}
65+
json.id(response.getId());
6066
json.status(response.getStatus());
6167
if (response.getProgress() != null) {
6268
json.progress(Map.of("fraction_done", response.getProgress().fractionDone()));
@@ -89,6 +95,8 @@ private Object[][] fetchDataRows(QueryResult response) {
8995
@JsonIgnoreProperties(ignoreUnknown = true)
9096
public static class JsonResponse {
9197

98+
private final String id;
99+
92100
private final String status;
93101

94102
private final Map<String, Double> progress;
@@ -100,6 +108,8 @@ public static class JsonResponse {
100108
private Integer total;
101109
private Integer size;
102110

111+
private final List<Warning> warnings;
112+
103113
/**
104114
* Either a human-readable string (Spark path) or a structured map matching the sync REST
105115
* error body (PPL {@code FAILED} path). Typed as {@link Object} so Gson emits either shape

‎async-query/src/main/java/org/opensearch/sql/spark/transport/model/AsyncQueryResult.java‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@
66
package org.opensearch.sql.spark.transport.model;
77

88
import java.util.Collection;
9+
import java.util.List;
910
import java.util.Map;
1011
import lombok.Getter;
1112
import org.opensearch.sql.data.model.ExprValue;
1213
import org.opensearch.sql.executor.ExecutionEngine;
14+
import org.opensearch.sql.executor.Warning;
1315
import org.opensearch.sql.executor.pagination.Cursor;
1416
import org.opensearch.sql.job.QueryProgress;
17+
import org.opensearch.sql.lang.PPLLangSpec;
1518
import org.opensearch.sql.protocol.response.QueryResult;
1619

1720
/** AsyncQueryResult for async query APIs. */
@@ -32,6 +35,10 @@ public class AsyncQueryResult extends QueryResult {
3235
/** {@code null} on the Spark path. */
3336
@Getter private final QueryProgress progress;
3437

38+
@Getter private final String id;
39+
40+
@Getter private final boolean queryJob;
41+
3542
public AsyncQueryResult(
3643
String status,
3744
ExecutionEngine.Schema schema,
@@ -48,22 +55,45 @@ public AsyncQueryResult(
4855
Cursor cursor,
4956
String error,
5057
Map<String, Object> errorDetails) {
51-
this(status, schema, exprValues, cursor, error, errorDetails, null);
58+
super(schema, exprValues, cursor);
59+
this.status = status;
60+
this.error = error;
61+
this.errorDetails = errorDetails;
62+
this.progress = null;
63+
this.id = null;
64+
this.queryJob = false;
5265
}
5366

54-
public AsyncQueryResult(
67+
/** Query jobs are PPL, so they render as the sync PPL response. */
68+
public static AsyncQueryResult forQueryJob(
5569
String status,
5670
ExecutionEngine.Schema schema,
5771
Collection<ExprValue> exprValues,
58-
Cursor cursor,
5972
String error,
6073
Map<String, Object> errorDetails,
61-
QueryProgress progress) {
62-
super(schema, exprValues, cursor);
74+
QueryProgress progress,
75+
String id,
76+
List<Warning> warnings) {
77+
return new AsyncQueryResult(
78+
status, schema, exprValues, error, errorDetails, progress, id, warnings);
79+
}
80+
81+
private AsyncQueryResult(
82+
String status,
83+
ExecutionEngine.Schema schema,
84+
Collection<ExprValue> exprValues,
85+
String error,
86+
Map<String, Object> errorDetails,
87+
QueryProgress progress,
88+
String id,
89+
List<Warning> warnings) {
90+
super(schema, exprValues, Cursor.None, PPLLangSpec.PPL_SPEC, warnings);
6391
this.status = status;
6492
this.error = error;
6593
this.errorDetails = errorDetails;
6694
this.progress = progress;
95+
this.id = id;
96+
this.queryJob = true;
6797
}
6898

6999
public AsyncQueryResult(
@@ -85,5 +115,7 @@ public AsyncQueryResult(
85115
this.error = error;
86116
this.errorDetails = errorDetails;
87117
this.progress = null;
118+
this.id = null;
119+
this.queryJob = false;
88120
}
89121
}

‎async-query/src/test/java/org/opensearch/sql/spark/transport/TransportGetAsyncQueryResultActionTest.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import com.google.common.collect.ImmutableList;
2121
import com.google.common.collect.ImmutableMap;
2222
import java.util.Arrays;
23+
import java.util.List;
2324
import java.util.HashSet;
2425
import org.junit.jupiter.api.Assertions;
2526
import org.junit.jupiter.api.BeforeEach;
@@ -146,6 +147,33 @@ public void testDoExecuteWithSuccessResponse() {
146147
getAsyncQueryResultActionResponse.getResult());
147148
}
148149

150+
@Test
151+
public void testDoExecuteWithQueryJobResponseUsesPplTypes() {
152+
GetAsyncQueryResultActionRequest request = new GetAsyncQueryResultActionRequest("jobId");
153+
ExecutionEngine.Schema schema =
154+
new ExecutionEngine.Schema(
155+
ImmutableList.of(new ExecutionEngine.Schema.Column("age", "age", INTEGER)));
156+
when(jobExecutorService.getAsyncQueryResults(eq("jobId"), any()))
157+
.thenReturn(
158+
new AsyncQueryExecutionResponse(
159+
"SUCCEEDED",
160+
schema,
161+
List.of(tupleValue(ImmutableMap.of("age", 20))),
162+
null,
163+
null,
164+
null,
165+
null,
166+
org.opensearch.sql.job.QueryProgress.DONE,
167+
List.of()));
168+
169+
action.doExecute(task, request, actionListener);
170+
171+
verify(actionListener).onResponse(createJobActionResponseArgumentCaptor.capture());
172+
String body = createJobActionResponseArgumentCaptor.getValue().getResult();
173+
Assertions.assertTrue(body.contains("\"type\": \"int\""), body);
174+
Assertions.assertTrue(body.contains("\"fraction_done\": 1.0"), body);
175+
}
176+
149177
@Test
150178
public void testDoExecuteWithException() {
151179
GetAsyncQueryResultActionRequest request = new GetAsyncQueryResultActionRequest("123");

0 commit comments

Comments
 (0)