Repository navigation
[PECO-910] Implement parallel downloader for chunks as per configurable in-memory chunks - #16
Conversation
yunbodeng-db
left a comment
There was a problem hiding this comment.
Sorry about the delay. I am concerned about the complexity. Are they all necessary?
| * @param chunkIndex chunkIndex for which chunk should be fetched | ||
| */ | ||
| Optional<ExternalLink> getResultChunk(String statementId, long chunkIndex); | ||
| Collection<ExternalLink> getResultChunk(String statementId, long chunkIndex); |
| @@ -0,0 +1,16 @@ | |||
| package com.databricks.jdbc.client; | |||
|
|
|||
| public class DatabricksHttpException extends Exception { | |||
There was a problem hiding this comment.
Derive from RuntimeException? Or this is on purpose?
There was a problem hiding this comment.
Yeah, I am thinking to catch all these on higher level and then wrap inside a subclass of SQL Exception with proper error codes. This exception will be used in lower level code of our implementation.
| @@ -0,0 +1,16 @@ | |||
| package com.databricks.jdbc.client; | |||
|
|
|||
| public class DatabricksHttpException extends Exception { | |||
|
|
||
| public class DatabricksHttpException extends Exception { | ||
|
|
||
| private Throwable cause; |
| import org.apache.http.HttpResponse; | ||
| import org.apache.http.client.methods.HttpUriRequest; | ||
|
|
||
| public interface IDatabricksHttpClient { |
| } | ||
| setStatus(DownloadStatus.DOWNLOAD_IN_PROGRESS); | ||
| } | ||
| try { |
There was a problem hiding this comment.
It's a big try/catch block, can you separate into transport, parsing at least? I assume exceptions to catch would also be different and more specific than Exception.
There was a problem hiding this comment.
Yes, added separate parsing exception, and will handle both http and parsing separately with relevant error codes in separate PR.
| ExternalLink chunk = session.getDatabricksClient().getResultChunk(statementId, nextChunkLinkToDownload).get(); | ||
| chunkIndexToChunksMap.get(chunk.getChunkIndex()).setChunkUrl(chunk); | ||
| nextChunkLinkToDownload++; | ||
| Collection<ExternalLink> chunks = session.getDatabricksClient().getResultChunk( |
There was a problem hiding this comment.
This pattern is pretty complex. Do you care about the boundary of "result chunk", e.g. when getResultChunk should be called so you can track some recovery at this boundary? Do you have to download all
I view this a typical producer and consumer pattern.
The producer of getResultChunk should hide the details but expose Iterable or Iterator. If it runs out of links, it knows to get next batch of links.
The consumer, "singleChunkDownloader" takes a chunkUrl and download all the files. I do not know if you care about the in-memory "thread" objects (not data), if not, you can get all the chunk links and submit to the thread pool with the managed thread count. If you care about the total number of pending tasks, this pattern is also easy to modify - you must have a thread monitor and only submit a singleChunkDownloader when there is a free spot.
I think this way the two components are decoupled and you can independently set control on either side and the tests would be easier to write independently too.
There was a problem hiding this comment.
Actually, I was thinking of producer consumer from different angle: singleChunkDownloader as producer and chunkIterator (that consumes data based on resultSet.next()) as consumer. So, the idea is:
In the result, we will have initial links (currently only the first, but later can be a list of first few links)
We will download chunks based on number of chunk data we can keep in memory. As soon as a spot is available, we download the next chunk until we don't have any further spots for in-memory chunks. A spot would become available as resultSet.next() iterates over a chunk boundary, and at that time we release the previous chunk, and initiate download for new chunks (it should download only one chunk as only one chunk got released).
Regarding links, currently the SQLExec getResultData() API returns only one link at a time, but they would extend that to return a collection at a time. So, we can prefetch all remaining links asynchronously, and while data fetch we can directly fetch the Arrow data if a spot is available. If it happens that the link has been expired, we would refetch the link again before downloading the data.
Since link information is small, we thought fetch all links initially would not add much to memory or complexity (as done async by separate executor service).
There was a problem hiding this comment.
I think it overcomplicates? The server has planned the file size so the client can predict the parallelism and the correspondent memory allocation. Alluding to async and prefetch makes me wonder if you can actually start fetching immediately when a spot is freed up - don't you need to wait for other rows to finish so you can prepare a batch to return because the rows to return to the client has to be in order and has to be synchronized?
Sorry if I have not understood cloud fetch well.
There was a problem hiding this comment.
Added simplified download logic. So, now the link would be fetched as part of chunk download task, additional executor service is not needed, nor will be need to notify from link downloader task.
Now, there is a single downloader thread which schedules chunk download (which also include link download), and a consumer which consumes chunks. If current chunk is not available, it would wait, and the downloader would notify after processing a download.
Similarly, if all available prefetch slots are taken, the downloader would wait, and the consumer would notify when it crosses a chunk boundary.
| if (chunkOptional.isPresent()) { | ||
| ExternalLink chunk = chunkOptional.get(); | ||
| chunkIndexToChunksMap.get(chunk.getChunkIndex()).setChunkUrl(chunk); | ||
| initChunksDownload(); |
There was a problem hiding this comment.
This nested thread scheduling is very complex and fragile. I do not think getting links can be bottleneck and has to be async. I think I understand what you want to achieve but I do not see its value like I said previously. Also Java unfortunately does not support this kind of async pattern well.
There was a problem hiding this comment.
Refactored this to simplified producer consumer pattern
| while (totalChunksInMemory < allowedChunksInMemory) { | ||
| // links are not yet ready | ||
| if (!isChunkDownloadable(chunk.getStatus())) { | ||
| break; |
There was a problem hiding this comment.
If a chunk can be unavailable, there is no information provided to the caller and the caller will think initDownloader was a success. Are we missing some downloads if they are not ready?
There was a problem hiding this comment.
Yes, that is correct. This will happen in following cases:
- Link is not ready (link not downloaded)
- Data is already downloaded
In either case we will abort further download. It means that in-memory spots were available, still we were not able to download some chunks. Would only happen when we started download when we had link only for first chunk (during the result set initialization). We will not do anything, and simply abort further downloads.
Now, download will start again as initLinksDownloader has downloaded all links, and called initDownload again. Now, we will fill the available in-memory spots and download the arrow data.
Later, as we would always have links, this situation can still happen that link is there but is expired. In that case also, we will abort the download, but trigger link download again for the chunk. This will refresh the chunk link, and then trigger the download again which will then resume the chunk data download.
| StatementExecutionService statementExecutionService; | ||
|
|
||
| @Mock | ||
| IDatabricksHttpClient mockHttpClient; |
There was a problem hiding this comment.
The test change is surprising small. Are we covering all the edge cases where the chunks are downloaded across different API calls?
Barring from error or exception handling which would be very complex in the current pattern.
There was a problem hiding this comment.
will add more exhaustive tests in separate PR
| try { | ||
| return httpClient.execute(request); | ||
| } catch (IOException e) { | ||
| String errorMsg = String.format("Caught error while executing http request: [%s]", request); |
There was a problem hiding this comment.
If you log the raw request, do you need to sanitize? Does it include headers which potentially carry secrets and other sensitive info?
There was a problem hiding this comment.
You're right. Added a sanitizer utility, will add better sanitization in separate PR. For now clearing all headers.
| } | ||
| return null; | ||
| } | ||
|
|
| } | ||
| if (totalChunksInMemory < allowedChunksInMemory) { | ||
| ArrowResultChunk chunk = chunkIndexToChunksMap.get(nextChunkToDownload); | ||
| this.chunkDownloaderExecutorService.submit(new SingleChunkDownloader(chunk, httpClient, session)); |
There was a problem hiding this comment.
You need a timeout in case the thread is stuck.
There was a problem hiding this comment.
If the user is not traversing rows, it means next chunk is not needed, and the thread would need to wait. Thus the wait time can be really long. We will explicitly notify when either statement or resultset or connection is closed.
| } | ||
| } | ||
|
|
||
| boolean enterLock() { |
There was a problem hiding this comment.
enterLock and releaseLock are confusing names.
How about startDownload and finishDownload?
There was a problem hiding this comment.
Can you explain to me again - this pattern suggests re-entrance problem but why we would have re-entrance problem?
chunkUrl is supposed to be readonly but I understand you take into account if the url expired, you want to reload but in essence, it's the same chunk and nobody else could own it?
There was a problem hiding this comment.
Actually, I had thought that the same chunk download could be submitted by multiple threads, but now that won't be the case. Removed locks.
| if (!chunk.isChunkLinkValid()) { | ||
| chunk.refreshChunkLink(session); | ||
| } | ||
| if (chunk.enterLock()) { |
There was a problem hiding this comment.
I am a little puzzled on why you would need to manage a single chunk with a state machine as well. I thought if you're ever going to add retry, you would retry here and give up if your retry strategy exhausted. And a failure of a single chunk can lead to retry the whole chunks or just bail which would be fine to me as well.
Managing the states reminds me when we worked on server that you would really distribute the workload to multiple tasks and each task is supposed to be independent and resilient. But this client library is not like that. We would not need the resilience of a truly distributed system.
We really should keep the client simple as possible since the complexity is really in the release and deployment to a client environment which we would not have access too.
There was a problem hiding this comment.
Not clear to me either. Why will there be multiple threads trying to download the same chunk?
There was a problem hiding this comment.
Agreed, discussed with Prasad, and removed locks.
| ExternalLink chunk = session.getDatabricksClient().getResultChunk(statementId, nextChunkLinkToDownload).get(); | ||
| chunkIndexToChunksMap.get(chunk.getChunkIndex()).setChunkUrl(chunk); | ||
| nextChunkLinkToDownload++; | ||
| Collection<ExternalLink> chunks = session.getDatabricksClient().getResultChunk( |
There was a problem hiding this comment.
I think it overcomplicates? The server has planned the file size so the client can predict the parallelism and the correspondent memory allocation. Alluding to async and prefetch makes me wonder if you can actually start fetching immediately when a spot is freed up - don't you need to wait for other rows to finish so you can prepare a batch to return because the rows to return to the client has to be in order and has to be synchronized?
Sorry if I have not understood cloud fetch well.
| private static final int DEFAULT_HTTP_CONNECTION_TIMEOUT = 60 * 1000; // ms | ||
| private static final int DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT = 300 * 1000; // ms | ||
|
|
||
| private static DatabricksHttpClient instance = null; |
There was a problem hiding this comment.
can't you directly set the instance here:
instance = new DatabricksHttpClient();
| } | ||
|
|
||
| public static synchronized DatabricksHttpClient getInstance() { | ||
| if (instance == null) { |
There was a problem hiding this comment.
This can be removed if you set instance directly while declaring it.
| vectors.add(transferPair.getTo()); | ||
| } | ||
| this.recordBatchList.add(vectors); | ||
| vectorSchemaRoot.clear(); |
There was a problem hiding this comment.
Should this clear be within the while block or outside of it?
There was a problem hiding this comment.
I will check with Madhav on this. He has implemented this, not sure if Arrow requires this.
| try { | ||
| VectorSchemaRoot vectorSchemaRoot = arrowStreamReader.getVectorSchemaRoot(); | ||
| while (arrowStreamReader.loadNextBatch()) { | ||
| ArrayList<ValueVector> vectors = new ArrayList<>(); |
There was a problem hiding this comment.
You can consider using java functional style:
vectors = vectorSchemaRoot.getFieldVectors().stream()
.map ( fieldVector -> {
TransferPair transferPair = fieldVector.getTransferPair(rootAllocator);
transferPair.transfer();
return transferPair.getTo();
}
).collect(Collectors.toList())
| void refreshChunkLink(IDatabricksSession session) { | ||
| Optional<ExternalLink> chunkOptional = session.getDatabricksClient() | ||
| .getResultChunks(statementId, chunkIndex).stream().findFirst(); | ||
| if (chunkOptional.isPresent()) { |
There was a problem hiding this comment.
functional style:
session.getDatabricksClient()
.getResultChunks(statementId, chunkIndex).stream().findFirst()
.ifPresent(chunk -> setChunkUrl(chunk));
| // TODO: Add impl, avoiding UnsupportedOperationException for test case | ||
| boolean isChunkDownloadable(ArrowResultChunk.DownloadStatus status) { | ||
| return status == ArrowResultChunk.DownloadStatus.URL_FETCHED | ||
| || status == ArrowResultChunk.DownloadStatus.CANCELLED |
There was a problem hiding this comment.
how is it downloadable if the status is cancelled or failed?
There was a problem hiding this comment.
I was thinking to consider explicit retry scenario. When already downloaded, or download in progress, or link not set are definitely not to be downloaded. But if failed earlier, and we are trying to explicitly retry, this can be attempted again.
| Collection<ExternalLink> chunks = session.getDatabricksClient().getResultChunks( | ||
| statementId, nextChunkLinkToDownload); | ||
| for (ExternalLink chunkLink : chunks) { | ||
| chunkIndexToChunksMap.get(chunkLink.getChunkIndex()).setChunkUrl(chunkLink); |
There was a problem hiding this comment.
can call setChunkLink(chunkLink.getChunkIndex(), chunkLink)
| } catch (InterruptedException e) { | ||
| // Handle interruption | ||
| } | ||
| if (totalChunksInMemory < allowedChunksInMemory) { |
There was a problem hiding this comment.
is this check needed? if you have come out of while, totalChunksInMemory will be less than allowedChunksInMemory
There was a problem hiding this comment.
Yeah, not needed. This function is single threaded.
| this.chunkDownloaderExecutorService.submit(new SingleChunkDownloader(chunk, httpClient, session)); | ||
| totalChunksInMemory++; | ||
| nextChunkToDownload++; | ||
| chunk = chunkIndexToChunksMap.get(nextChunkToDownload); |
| if (!chunk.isChunkLinkValid()) { | ||
| chunk.refreshChunkLink(session); | ||
| } | ||
| if (chunk.enterLock()) { |
There was a problem hiding this comment.
Not clear to me either. Why will there be multiple threads trying to download the same chunk?
| @Override | ||
| public void run() { | ||
| // Starts the chunk download from given already downloaded position | ||
| while(!this.isClosed && (nextChunkToDownload < totalChunks)) { |
There was a problem hiding this comment.
I think you can wait on an object only if you have ownership of the lock in a synchronized block. Also the thread notifying has to take a lock before notifying. See example here - https://www.edureka.co/blog/java-wait-and-notify/#:~:text=This%20Wait()%20method%20tells,from%20the%20wait()%20method.
There was a problem hiding this comment.
Added changes to fix this
| @@ -179,18 +181,19 @@ void releaseAllChunks() { | |||
| @Override | |||
| public void run() { | |||
There was a problem hiding this comment.
I have a further simplification - this need not start a new thread. It will just submit the first allowedChunksInMemory to the chunkdownloaderexecutor service and exit the function. The releaseChunk function will pick the nextChunkToBeDownloaded and submit it to the executor service. The downloadMonitor is not needed. You just need a lock on nextChunkToDownload in the releaseChunk function.
| @@ -102,43 +103,42 @@ public Thread newThread(final Runnable r) { | |||
| * @return the chunk at given index | |||
| */ | |||
| public ArrowResultChunk getChunk(long chunkIndex) { | |||
There was a problem hiding this comment.
I am just wondering if this should be getNextChunk() interface. Why should it take in a chunkIndex? Its always called in order by ArrowResultChunk. This class should internally manage the current least index of the chunk being downloaded. Also, once download is complete, the monitor will get notified only if the chunk downloaded is the currentChunk. Otherwise, now the thread will get up and go back to sleep in some cases.
This will also simplify your logic in ArrowStreamResult next() function, where this is some special casing for first chunk vs rest. I think special case can be avoided.
There was a problem hiding this comment.
Also, why is chunkIndexToChunksMap a map? We are storing info about all chunks, then it could be a simple array isn't it since chunkIndex is anyway contiguous.
One problem currently is that if the number of chunks is very large, memory usage will high to hold the map. Is this because the resultManifest anyway holds info about all the chunks and so there is no point in optimizing memory footprint?
There was a problem hiding this comment.
Also, we don't need to use a monitor variable separate from the variable you are trying to protect.. it will help the reader understand what the wait is about. For example, if you do the change I suggested above, the variable to be protected is currentChunk (status of currentChunk). So it will take the lock on currentChunk and if status of currentChunk is not ready, it will wait on that itself.
There was a problem hiding this comment.
Further simplified the code by keeping currentRowIndex into chunkDownloader instead of ArrowStreamResult. Added other suggestions.
Still keeping map instead of list, as during initialization of map, index keys we are getting from chunk, not incremental values. The server may send non contiguous values (though that may not happen practically).
We are not considering any memory constraint here, result manifest anyways contains all the chunk metadata, so should not be an issue for us.
| } | ||
|
|
||
| void downloadProcessed() { | ||
| synchronized (consumerMonitor) { |
There was a problem hiding this comment.
As per the suggestion, this should check if the download completed is the current chunk and notify only for current chunk.
There was a problem hiding this comment.
Why even check for current chunk? Notify for chunk which is downloaded. If no other thread is waiting, it will be no-op.
There was a problem hiding this comment.
releaseChunk also need not take an index
| return this.chunkIterator.nextRow(); | ||
| } | ||
|
|
||
| @Override |
There was a problem hiding this comment.
Nit: I don't see this method in the base interface - IExecutionResult. So is it really overriding?
If it is not there, you can remove this function. Otherwise this check happens twice inside next() function above and can be streamlined.
There was a problem hiding this comment.
It is there in IExecutionResult:
/**
- Returns if there is next row in the result set
*/
boolean hasNext();
| @Override | ||
| public boolean next() { | ||
| if (isClosed()) { | ||
| if (!hasNext()) { |
There was a problem hiding this comment.
This check can be removed, since similar check happens below
There was a problem hiding this comment.
No, we are directly returning from false cases here. Below all are true cases.
| ++this.currentRowIndex; | ||
| if(this.chunkIterator.nextRow()) { | ||
|
|
||
| this.currentRowIndex++; |
There was a problem hiding this comment.
Move this to two places below where true is being returned.
There was a problem hiding this comment.
It will always return true from here. False we have already checked in hasNext() above.
There was a problem hiding this comment.
The check "(this.chunkIterator == null || !this.chunkIterator.hasNextRow())" is happening inside hasNext and below as well. So I was suggesting to just remove the hasNext call above (earlier I thought that function itself was not needed, but realize now that it is part of the interface) and modify the code below to further check for chunkDownloader.hasNext.
But this is not a major point, so we can let it be as it is.
|
|
||
| this.currentRowIndex++; | ||
| if (this.chunkIterator == null || !this.chunkIterator.hasNextRow()) { | ||
| this.chunkDownloader.next(); |
There was a problem hiding this comment.
Here you can check if this.chunkDownloader.hasNext and return false if there is no next.
There was a problem hiding this comment.
No need. We have already checked all false cases by calling hasNext() above. Now we are only interested in if we want to cross chunk boundary or traverse within a chunk. Added comments for better comprehension.
| || chunkDownloader.hasNextChunk()); | ||
| } | ||
|
|
||
| @Override |
There was a problem hiding this comment.
I think we are not shutting down the executor service anywhere. This will lead to thread leakage. chunkDownloader.releaseAllChunks should shutdown the executor service. See this for sample usage:
https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/util/concurrent/ExecutorService.html
There was a problem hiding this comment.
Yes, that was a TODO. Adding now.
| if (this.chunkIterator == null || !this.chunkIterator.hasNextRow()) { | ||
| this.chunkDownloader.next(); | ||
| ArrowResultChunk resultChunk = this.chunkDownloader.getChunk(); | ||
| this.chunkIterator = resultChunk.getChunkIterator(); |
There was a problem hiding this comment.
Nit: The chunkIterator pattern is slightly different from other iterators. It seems to be already set on the first element without calling next. Usually the pattern for java iterators and also for the chunkDownloader is to call hasNext and then next before even the first element can be read. If you make this consistent with it, then overall the loop becomes simpler:
while ((this.chunkIterator == null) || !this.chunkIterator.hasNextRow()) {
if (this.chunkDownloader.hasNextChunk()) {
this.chunkDownloader.next();
this.chunkIterator = chunkDownloader.getChunk().getChunkIterator();
} else {
return false;
}
}
this.currentRowIndex++;
return chunkIterator.nextRow();
There was a problem hiding this comment.
Changed the code of chunkIterator for regular java iterator behavior. Now, first time next() has to be called for fetching first row from interator.
| private void initDownloader() { | ||
| // Start the downloader for arrow data | ||
| new Thread(this, "chunk-downloader-" + statementId).start(); | ||
| boolean hasNextChunk() { |
There was a problem hiding this comment.
hasNextChunk and next() are not thread safe and we don't intend them to be. They will be called from a single thread from ArrowStreamResult. So synchronization on currentChunkIndex can be removed from here and in next() below.
There was a problem hiding this comment.
Valid point. They will be called from same thread. Removed synchronization.
| public void releaseChunk(int chunkIndex) { | ||
| if (chunkIndexToChunksMap.get(chunkIndex).releaseChunk()) { | ||
| synchronized (downloadMonitor) { | ||
| public void releaseChunk() { |
There was a problem hiding this comment.
Since next() will be called by a single thread, so will releaseChunk and downloadNextChunks() below. So synchronization on totalChunksInMemory is not needed either.
| consumerMonitor.notify(); | ||
| void downloadProcessed(long chunkIndex) { | ||
| ArrowResultChunk chunk = chunkIndexToChunksMap.get(chunkIndex); | ||
| synchronized (chunk) { |
There was a problem hiding this comment.
This is good. My earlier suggestion of checking for chunkIndex == currentChunkIndex before notifying would have led to subtle issues of notify getting lost since currentChunkIndex itself is being modified by the next() function in a different thread.
Another option is to synchronize on currentChunkIndex in getChunk, next and here in downloadProcessed before checking for chunkIndex == currentChunkIndex . But your logic is also fine.
prasadmd0
left a comment
There was a problem hiding this comment.
Looks good. Ready for approval once shutdown is changed to shutdownNow.
| ++this.currentRowIndex; | ||
| if(this.chunkIterator.nextRow()) { | ||
|
|
||
| this.currentRowIndex++; |
There was a problem hiding this comment.
The check "(this.chunkIterator == null || !this.chunkIterator.hasNextRow())" is happening inside hasNext and below as well. So I was suggesting to just remove the hasNext call above (earlier I thought that function itself was not needed, but realize now that it is part of the interface) and modify the code below to further check for chunkDownloader.hasNext.
But this is not a major point, so we can let it be as it is.
| */ | ||
| void releaseAllChunks() { | ||
| this.isClosed = true; | ||
| this.chunkDownloaderExecutorService.shutdown(); |
There was a problem hiding this comment.
There is an edge case if close() is called on the result set before the results are read. Some executor threads may be waiting for memory to be available and they will remain blocked. Calling shutdownNow() may be better here.
https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/util/concurrent/ExecutorService.html#shutdownNow()
See this article which talks about close being called before processing resultset for sql server jdbc server - https://learn.microsoft.com/en-us/sql/connect/jdbc/using-adaptive-buffering?view=sql-server-ver16
There was a problem hiding this comment.
Makes sense. Thanks for sharing pointer on sql server.
Added download logic, test case for parallel download of chunks. In separate PR, will add retry logic and error handling.