Skip to content

[PECO-910] Implement parallel downloader for chunks as per configurable in-memory chunks - #16

Merged
gopalldb merged 17 commits into
developmentfrom
download
Sep 15, 2023
Merged

gopalldb merged 17 commits into
developmentfrom
download

Conversation

@gopalldb

Copy link
Copy Markdown
Collaborator

Added download logic, test case for parallel download of chunks. In separate PR, will add retry logic and error handling.

@yunbodeng-db yunbodeng-db left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getResultChunks()?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@@ -0,0 +1,16 @@
package com.databricks.jdbc.client;

public class DatabricksHttpException extends Exception {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Derive from RuntimeException? Or this is on purpose?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add doc for the class.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


public class DatabricksHttpException extends Exception {

private Throwable cause;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private final Throwable cause;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;

public interface IDatabricksHttpClient {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add doc.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

}
setStatus(DownloadStatus.DOWNLOAD_IN_PROGRESS);
}
try {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactored this to simplified producer consumer pattern

while (totalChunksInMemory < allowedChunksInMemory) {
// links are not yet ready
if (!isChunkDownloadable(chunk.getStatus())) {
break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that is correct. This will happen in following cases:

  1. Link is not ready (link not downloaded)
  2. 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you log the raw request, do you need to sanitize? Does it include headers which potentially carry secrets and other sensitive info?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. Added a sanitizer utility, will add better sanitization in separate PR. For now clearing all headers.

}
return null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant blank lines.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

}
if (totalChunksInMemory < allowedChunksInMemory) {
ArrowResultChunk chunk = chunkIndexToChunksMap.get(nextChunkToDownload);
this.chunkDownloaderExecutorService.submit(new SingleChunkDownloader(chunk, httpClient, session));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need a timeout in case the thread is stuck.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enterLock and releaseLock are confusing names.
How about startDownload and finishDownload?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not clear to me either. Why will there be multiple threads trying to download the same chunk?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't you directly set the instance here:
instance = new DatabricksHttpClient();

}

public static synchronized DatabricksHttpClient getInstance() {
if (instance == null) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be removed if you set instance directly while declaring it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

vectors.add(transferPair.getTo());
}
this.recordBatchList.add(vectors);
vectorSchemaRoot.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this clear be within the while block or outside of it?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())
       

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

void refreshChunkLink(IDatabricksSession session) {
Optional<ExternalLink> chunkOptional = session.getDatabricksClient()
.getResultChunks(statementId, chunkIndex).stream().findFirst();
if (chunkOptional.isPresent()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

functional style:

session.getDatabricksClient()
        .getResultChunks(statementId, chunkIndex).stream().findFirst()
.ifPresent(chunk -> setChunkUrl(chunk));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

// TODO: Add impl, avoiding UnsupportedOperationException for test case
boolean isChunkDownloadable(ArrowResultChunk.DownloadStatus status) {
return status == ArrowResultChunk.DownloadStatus.URL_FETCHED
|| status == ArrowResultChunk.DownloadStatus.CANCELLED

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how is it downloadable if the status is cancelled or failed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can call setChunkLink(chunkLink.getChunkIndex(), chunkLink)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

} catch (InterruptedException e) {
// Handle interruption
}
if (totalChunksInMemory < allowedChunksInMemory) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this check needed? if you have come out of while, totalChunksInMemory will be less than allowedChunksInMemory

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, not needed. This function is single threaded.

this.chunkDownloaderExecutorService.submit(new SingleChunkDownloader(chunk, httpClient, session));
totalChunksInMemory++;
nextChunkToDownload++;
chunk = chunkIndexToChunksMap.get(nextChunkToDownload);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this statement needed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

if (!chunk.isChunkLinkValid()) {
chunk.refreshChunkLink(session);
}
if (chunk.enterLock()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added changes to fix this

@@ -179,18 +181,19 @@ void releaseAllChunks() {
@Override
public void run() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@@ -102,43 +103,42 @@ public Thread newThread(final Runnable r) {
* @return the chunk at given index
*/
public ArrowResultChunk getChunk(long chunkIndex) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per the suggestion, this should check if the download completed is the current chunk and notify only for current chunk.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why even check for current chunk? Notify for chunk which is downloaded. If no other thread is waiting, it will be no-op.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

releaseChunk also need not take an index

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

@gopalldb
gopalldb requested a review from prasadmd0 September 12, 2023 05:12
return this.chunkIterator.nextRow();
}

@Override

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check can be removed, since similar check happens below

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, we are directly returning from false cases here. Below all are true cases.

++this.currentRowIndex;
if(this.chunkIterator.nextRow()) {

this.currentRowIndex++;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this to two places below where true is being returned.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will always return true from here. False we have already checked in hasNext() above.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you can check if this.chunkDownloader.hasNext and return false if there is no next.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since next() will be called by a single thread, so will releaseChunk and downloadNextChunks() below. So synchronization on totalChunksInMemory is not needed either.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

consumerMonitor.notify();
void downloadProcessed(long chunkIndex) {
ArrowResultChunk chunk = chunkIndexToChunksMap.get(chunkIndex);
synchronized (chunk) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gopalldb
gopalldb requested a review from prasadmd0 September 12, 2023 13:59

@prasadmd0 prasadmd0 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Ready for approval once shutdown is changed to shutdownNow.

++this.currentRowIndex;
if(this.chunkIterator.nextRow()) {

this.currentRowIndex++;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. Thanks for sharing pointer on sql server.

@gopalldb
gopalldb requested a review from prasadmd0 September 13, 2023 10:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants