Skip to content

Commit 5798a0d

Browse files
Introduce abstract base classes for Arrow result handling (#881)
## Description <!-- Provide a brief summary of the changes made and the issue they aim to address.--> This PR is the first of two and splits the changes originally proposed in #634. Key changes: - Create AbstractRemoteChunkProvider and AbstractArrowResultChunk as unified base implementations for chunk management - Add state machine (ArrowResultChunkStateMachine) to handle chunk lifecycle transitions - Improve thread synchronization between main thread and IO/download threads The new async implementation (2nd PR) will provide an alternative path for handling large Arrow datasets with improved scalability, while maintaining the existing synchronous approach for backwards compatibility. Below is a class diagram that provides a clearer understanding and concise summary of the class structure: ![class-diagram](https://github.com/user-attachments/assets/e9503d47-5895-439a-9d39-f4963da3e5df) ## Testing <!-- Describe how the changes have been tested--> - Fake service tests - Unit tests - Multi-DBR tests - Local testing in a highly concurrent environment ## Additional Notes to the Reviewer <!-- Share any additional context or insights that may help the reviewer understand the changes better. This could include challenges faced, limitations, or compromises made during the development process. Also, mention any areas of the code that you would like the reviewer to focus on specifically. -->
1 parent 7e2b46e commit 5798a0d

22 files changed

Lines changed: 1192 additions & 732 deletions

src/main/java/com/databricks/jdbc/api/impl/DatabricksConnectionContext.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,12 @@ public String getApplicationName() {
898898
return getParameter(DatabricksJdbcUrlParams.APPLICATION_NAME);
899899
}
900900

901+
/** {@inheritDoc} */
902+
@Override
903+
public int getChunkReadyTimeoutSeconds() {
904+
return Integer.parseInt(getParameter(DatabricksJdbcUrlParams.CHUNK_READY_TIMEOUT_SECONDS));
905+
}
906+
901907
private static boolean nullOrEmptyString(String s) {
902908
return s == null || s.isEmpty();
903909
}
Lines changed: 376 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,376 @@
1+
package com.databricks.jdbc.api.impl.arrow;
2+
3+
import static com.databricks.jdbc.common.DatabricksJdbcConstants.ARROW_METADATA_KEY;
4+
5+
import com.databricks.jdbc.common.CompressionCodec;
6+
import com.databricks.jdbc.common.util.DriverUtil;
7+
import com.databricks.jdbc.dbclient.IDatabricksHttpClient;
8+
import com.databricks.jdbc.dbclient.impl.common.StatementId;
9+
import com.databricks.jdbc.exception.DatabricksParsingException;
10+
import com.databricks.jdbc.exception.DatabricksSQLException;
11+
import com.databricks.jdbc.log.JdbcLogger;
12+
import com.databricks.jdbc.log.JdbcLoggerFactory;
13+
import com.databricks.jdbc.model.core.ExternalLink;
14+
import java.io.IOException;
15+
import java.io.InputStream;
16+
import java.nio.channels.ClosedByInterruptException;
17+
import java.time.Instant;
18+
import java.util.ArrayList;
19+
import java.util.List;
20+
import java.util.concurrent.CompletableFuture;
21+
import java.util.concurrent.ExecutionException;
22+
import java.util.concurrent.TimeUnit;
23+
import java.util.concurrent.TimeoutException;
24+
import java.util.stream.Collectors;
25+
import org.apache.arrow.memory.BufferAllocator;
26+
import org.apache.arrow.memory.RootAllocator;
27+
import org.apache.arrow.vector.ValueVector;
28+
import org.apache.arrow.vector.VectorSchemaRoot;
29+
import org.apache.arrow.vector.ipc.ArrowStreamReader;
30+
import org.apache.arrow.vector.util.TransferPair;
31+
import org.apache.commons.lang3.exception.ExceptionUtils;
32+
33+
/**
34+
* An abstract class that represents a chunk of query result.
35+
*
36+
* <p>This class provides methods for downloading, processing, and releasing the data in the chunk.
37+
* It also manages the state of the chunk and provides access to the data as Arrow record batches.
38+
*/
39+
public abstract class AbstractArrowResultChunk {
40+
private static final JdbcLogger LOGGER =
41+
JdbcLoggerFactory.getLogger(AbstractArrowResultChunk.class);
42+
43+
protected static final Integer SECONDS_BUFFER_FOR_EXPIRY = 60;
44+
protected final long numRows;
45+
protected final long rowOffset;
46+
protected final long chunkIndex;
47+
protected final StatementId statementId;
48+
protected final BufferAllocator rootAllocator;
49+
50+
/**
51+
* Future to track when the chunk becomes ready for consumption. This includes both the download
52+
* and processing phases. The state of the Future is updated by the {@link ChunkDownloadTask} and
53+
* indicates when the chunk's data is fully processed and available for use.
54+
*/
55+
protected final CompletableFuture<Void> chunkReadyFuture;
56+
57+
protected final ArrowResultChunkStateMachine stateMachine;
58+
protected List<List<ValueVector>> recordBatchList;
59+
protected ExternalLink chunkLink;
60+
protected Instant expiryTime;
61+
protected String errorMessage;
62+
protected List<String> arrowMetadata;
63+
protected int chunkReadyTimeoutSeconds;
64+
65+
static final class ArrowData {
66+
private final List<List<ValueVector>> valueVectors;
67+
private final List<String> metadata;
68+
69+
public ArrowData(List<List<ValueVector>> valueVectors, List<String> metadata) {
70+
this.valueVectors = valueVectors;
71+
this.metadata = metadata;
72+
}
73+
74+
public List<List<ValueVector>> getValueVectors() {
75+
return valueVectors;
76+
}
77+
78+
public List<String> getMetadata() {
79+
return metadata;
80+
}
81+
}
82+
83+
protected AbstractArrowResultChunk(
84+
long numRows,
85+
long rowOffset,
86+
long chunkIndex,
87+
StatementId statementId,
88+
ChunkStatus initialStatus,
89+
ExternalLink chunkLink,
90+
Instant expiryTime,
91+
int chunkReadyTimeoutSeconds) {
92+
this.numRows = numRows;
93+
this.rowOffset = rowOffset;
94+
this.chunkIndex = chunkIndex;
95+
this.statementId = statementId;
96+
this.rootAllocator = new RootAllocator(Integer.MAX_VALUE);
97+
this.chunkReadyFuture = new CompletableFuture<>();
98+
this.chunkLink = chunkLink;
99+
this.expiryTime = expiryTime;
100+
this.stateMachine = new ArrowResultChunkStateMachine(initialStatus, chunkIndex, statementId);
101+
this.chunkReadyTimeoutSeconds = chunkReadyTimeoutSeconds;
102+
}
103+
104+
/**
105+
* Returns the index of this chunk.
106+
*
107+
* @return chunk index
108+
*/
109+
public Long getChunkIndex() {
110+
return chunkIndex;
111+
}
112+
113+
/**
114+
* Checks if the chunk link is invalid or expired.
115+
*
116+
* @return true if link is invalid, false otherwise
117+
*/
118+
public boolean isChunkLinkInvalid() {
119+
return getStatus() == ChunkStatus.PENDING
120+
|| (!DriverUtil.isRunningAgainstFake()
121+
&& expiryTime.minusSeconds(SECONDS_BUFFER_FOR_EXPIRY).isBefore(Instant.now()));
122+
}
123+
124+
/**
125+
* Releases all resources associated with this chunk.
126+
*
127+
* @return true if chunk was released, false if it was already released
128+
*/
129+
public boolean releaseChunk() {
130+
if (getStatus() == ChunkStatus.CHUNK_RELEASED) {
131+
return false;
132+
}
133+
134+
if (getStatus() == ChunkStatus.PROCESSING_SUCCEEDED) {
135+
logAllocatorStats("BeforeRelease");
136+
purgeArrowData(this.recordBatchList);
137+
rootAllocator.close();
138+
}
139+
setStatus(ChunkStatus.CHUNK_RELEASED);
140+
141+
return true;
142+
}
143+
144+
/**
145+
* Downloads and initializes data for this chunk using the provided HTTP client and compression
146+
* codec.
147+
*
148+
* @param httpClient the HTTP client to use for downloading
149+
* @param compressionCodec the compression codec to use for decompression
150+
* @throws DatabricksParsingException if there is an error parsing the data
151+
* @throws IOException if there is an error downloading or reading the data
152+
*/
153+
protected abstract void downloadData(
154+
IDatabricksHttpClient httpClient, CompressionCodec compressionCodec)
155+
throws DatabricksParsingException, IOException;
156+
157+
/** Handles a failure during the download or processing of this chunk. */
158+
protected abstract void handleFailure(Exception exception, ChunkStatus failedStatus)
159+
throws DatabricksParsingException;
160+
161+
/**
162+
* Returns the number of record batches in the chunk.
163+
*
164+
* @return number of record batches
165+
*/
166+
protected int getRecordBatchCountInChunk() {
167+
return getStatus() == ChunkStatus.PROCESSING_SUCCEEDED ? recordBatchList.size() : 0;
168+
}
169+
170+
/**
171+
* Returns the list of record batches, where each record batch is a list of value vectors.
172+
*
173+
* @return List of record batches
174+
*/
175+
protected List<List<ValueVector>> getRecordBatchList() {
176+
return recordBatchList;
177+
}
178+
179+
/**
180+
* Returns the total number of rows in the chunk.
181+
*
182+
* @return number of rows
183+
*/
184+
protected long getNumRows() {
185+
return numRows;
186+
}
187+
188+
/**
189+
* Returns the value vector for a specific record batch and column.
190+
*
191+
* @param recordBatchIndex index of the record batch
192+
* @param columnIndex index of the column
193+
* @return ValueVector for the specified position
194+
*/
195+
protected ValueVector getColumnVector(int recordBatchIndex, int columnIndex) {
196+
return recordBatchList.get(recordBatchIndex).get(columnIndex);
197+
}
198+
199+
/**
200+
* Returns the current status of the chunk.
201+
*
202+
* @return current ChunkStatus
203+
*/
204+
protected ChunkStatus getStatus() {
205+
return stateMachine.getCurrentStatus();
206+
}
207+
208+
/**
209+
* Updates the status of the chunk.
210+
*
211+
* @param targetStatus new status to set
212+
*/
213+
protected void setStatus(ChunkStatus targetStatus) {
214+
try {
215+
stateMachine.transition(targetStatus);
216+
} catch (DatabricksParsingException e) {
217+
LOGGER.warn(
218+
"Failed to transition to state [%s] from state [%s] for chunk [%d] and statement [%s]. Stack trace: %s",
219+
targetStatus, getStatus(), chunkIndex, statementId, ExceptionUtils.getStackTrace(e));
220+
}
221+
}
222+
223+
/**
224+
* Returns an iterator for traversing the rows in this chunk.
225+
*
226+
* @return ArrowResultChunkIterator for this chunk
227+
*/
228+
protected ArrowResultChunkIterator getChunkIterator() {
229+
return new ArrowResultChunkIterator(this);
230+
}
231+
232+
/**
233+
* Sets the external link details for this chunk.
234+
*
235+
* @param chunk the external link information
236+
*/
237+
protected void setChunkLink(ExternalLink chunk) {
238+
chunkLink = chunk;
239+
expiryTime = Instant.parse(chunk.getExpiration());
240+
setStatus(ChunkStatus.URL_FETCHED);
241+
}
242+
243+
protected CompletableFuture<Void> getChunkReadyFuture() {
244+
return chunkReadyFuture;
245+
}
246+
247+
/**
248+
* Waits for the chunk to be ready for consumption.
249+
*
250+
* @throws ExecutionException if the chunk download or processing throws an exception
251+
* @throws InterruptedException if the thread is interrupted while waiting
252+
* @throws TimeoutException if the chunk is not ready within the timeout
253+
*/
254+
protected void waitForChunkReady()
255+
throws ExecutionException, InterruptedException, TimeoutException {
256+
try {
257+
if (chunkReadyTimeoutSeconds <= 0) {
258+
// Wait indefinitely when timeout is 0 or negative
259+
chunkReadyFuture.get();
260+
} else {
261+
chunkReadyFuture.get(chunkReadyTimeoutSeconds, TimeUnit.SECONDS);
262+
}
263+
264+
} catch (InterruptedException e) {
265+
LOGGER.error(
266+
e,
267+
"Chunk download interrupted for chunk index %s and statement %s",
268+
chunkIndex,
269+
statementId);
270+
Thread.currentThread().interrupt();
271+
throw e;
272+
}
273+
}
274+
275+
/**
276+
* Decompresses the given {@link InputStream} and initializes {@link #recordBatchList} from
277+
* decompressed stream.
278+
*
279+
* @param inputStream the input stream to decompress
280+
* @throws DatabricksSQLException if decompression fails
281+
* @throws IOException if reading from the stream fails
282+
*/
283+
protected void initializeData(InputStream inputStream)
284+
throws DatabricksSQLException, IOException {
285+
LOGGER.debug("Parsing data for chunk index %s and statement %s", chunkIndex, statementId);
286+
ArrowData arrowData = getRecordBatchList(inputStream, rootAllocator, statementId, chunkIndex);
287+
recordBatchList = arrowData.getValueVectors();
288+
arrowMetadata = arrowData.getMetadata();
289+
LOGGER.debug("Data parsed for chunk index %s and statement %s", chunkIndex, statementId);
290+
setStatus(ChunkStatus.PROCESSING_SUCCEEDED);
291+
}
292+
293+
protected List<String> getArrowMetadata() {
294+
return arrowMetadata;
295+
}
296+
297+
/**
298+
* Reads Arrow format data from an input stream and converts it into a list of record batches.
299+
* Each record batch is represented as a list of {@link ValueVector}s.
300+
*/
301+
private ArrowData getRecordBatchList(
302+
InputStream inputStream,
303+
BufferAllocator rootAllocator,
304+
StatementId statementId,
305+
long chunkIndex)
306+
throws IOException {
307+
List<List<ValueVector>> recordBatchList = new ArrayList<>();
308+
List<String> metadata = new ArrayList<>();
309+
try (ArrowStreamReader arrowStreamReader = new ArrowStreamReader(inputStream, rootAllocator)) {
310+
VectorSchemaRoot vectorSchemaRoot = arrowStreamReader.getVectorSchemaRoot();
311+
boolean fetchedMetadata = false;
312+
while (arrowStreamReader.loadNextBatch()) {
313+
if (!fetchedMetadata) {
314+
metadata = getMetadataInformationFromSchemaRoot(vectorSchemaRoot);
315+
fetchedMetadata = true;
316+
}
317+
recordBatchList.add(getVectorsFromSchemaRoot(vectorSchemaRoot, rootAllocator));
318+
vectorSchemaRoot.clear();
319+
}
320+
} catch (ClosedByInterruptException e) {
321+
// release resources if thread is interrupted when reading arrow data
322+
LOGGER.error(
323+
e,
324+
"Data parsing interrupted for chunk index [%s] and statement [%s]. Error [%s]",
325+
chunkIndex,
326+
statementId,
327+
e.getMessage());
328+
purgeArrowData(recordBatchList);
329+
} catch (IOException e) {
330+
LOGGER.error(
331+
"Error while reading arrow data, purging the local list and rethrowing the exception.");
332+
purgeArrowData(recordBatchList);
333+
throw e;
334+
}
335+
336+
return new ArrowData(recordBatchList, metadata);
337+
}
338+
339+
private List<String> getMetadataInformationFromSchemaRoot(VectorSchemaRoot vectorSchemaRoot) {
340+
return vectorSchemaRoot.getFieldVectors().stream()
341+
.map(fieldVector -> fieldVector.getField().getMetadata().get(ARROW_METADATA_KEY))
342+
.collect(Collectors.toList());
343+
}
344+
345+
/**
346+
* Transfers the data from the given {@link VectorSchemaRoot} to a list of {@link ValueVector}s.
347+
*/
348+
private List<ValueVector> getVectorsFromSchemaRoot(
349+
VectorSchemaRoot vectorSchemaRoot, BufferAllocator rootAllocator) {
350+
return vectorSchemaRoot.getFieldVectors().stream()
351+
.map(
352+
fieldVector -> {
353+
TransferPair transferPair = fieldVector.getTransferPair(rootAllocator);
354+
transferPair.transfer();
355+
return transferPair.getTo();
356+
})
357+
.collect(Collectors.toList());
358+
}
359+
360+
private void logAllocatorStats(String event) {
361+
long allocatedMemory = rootAllocator.getAllocatedMemory();
362+
long peakMemory = rootAllocator.getPeakMemoryAllocation();
363+
long headRoom = rootAllocator.getHeadroom();
364+
long initReservation = rootAllocator.getInitReservation();
365+
366+
LOGGER.debug(
367+
"Chunk allocator stats Log - Event: %s, Chunk Index: %s, Allocated Memory: %s, Peak Memory: %s, Headroom: %s, Init Reservation: %s",
368+
event, chunkIndex, allocatedMemory, peakMemory, headRoom, initReservation);
369+
}
370+
371+
/** Releases all Arrow-related resources and clears the record batch list. */
372+
private void purgeArrowData(List<List<ValueVector>> recordBatchList) {
373+
recordBatchList.forEach(vectors -> vectors.forEach(ValueVector::close));
374+
recordBatchList.clear();
375+
}
376+
}

0 commit comments

Comments
 (0)