This is an automated email from the ASF dual-hosted git repository.
JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 4424bd54afa Fill the response that completes a fragmented TsBlock with
following blocks
4424bd54afa is described below
commit 4424bd54afaf07a1b48f43d3792054a74ae088e4
Author: Weihao Li <[email protected]>
AuthorDate: Tue Dec 1 09:19:19 2026 +0800
Fill the response that completes a fragmented TsBlock with following blocks
---
.../iotdb/rpc/IoTDBRpcDataSetFragmentTest.java | 98 ++++++-
.../plan/execution/IQueryExecution.java | 8 +
.../plan/execution/PendingResultFragment.java | 26 +-
.../queryengine/plan/execution/QueryExecution.java | 13 +
.../apache/iotdb/db/utils/QueryDataSetUtils.java | 54 +++-
.../plan/execution/PendingResultFragmentTest.java | 15 +-
.../iotdb/db/utils/QueryDataSetUtilsTest.java | 288 ++++++++++++++++++++-
.../iotdb/db/utils/ResultChunkingEndToEndTest.java | 85 +++++-
8 files changed, 544 insertions(+), 43 deletions(-)
diff --git
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java
index c68553cb013..ad884975e9d 100644
---
a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java
+++
b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java
@@ -52,7 +52,7 @@ public class IoTDBRpcDataSetFragmentTest {
@Test
public void testAssembleOneOversizedTsBlockAcrossResponses() throws
Exception {
- byte[] bytes = serializeInt64Block();
+ byte[] bytes = serializeInt64Block(10L);
int totalLength = bytes.length;
int split = totalLength / 2;
@@ -78,8 +78,8 @@ public class IoTDBRpcDataSetFragmentTest {
@Test
public void testCompleteBlocksAndTrailingFragmentInOneResponse() throws
Exception {
- byte[] first = serializeInt64Block();
- byte[] second = serializeInt64Block();
+ byte[] first = serializeInt64Block(10L);
+ byte[] second = serializeInt64Block(10L);
int split = second.length / 2;
IClientRPCService.Iface client = mockClient();
@@ -105,9 +105,85 @@ public class IoTDBRpcDataSetFragmentTest {
assertFalse(dataSet.next());
}
+ @Test
+ public void
testCompleteFragmentWithFollowingBlocksAndTrailingFragmentInOneResponse()
+ throws Exception {
+ byte[] first = serializeInt64Block(10L);
+ byte[] second = serializeInt64Block(30L);
+ byte[] third = serializeInt64Block(50L);
+ int firstSplit = first.length / 2;
+ // a different split point, so that reusing the previous offset is caught
+ int thirdSplit = third.length / 3;
+ assertTrue(firstSplit != thirdSplit);
+
+ IClientRPCService.Iface client = mockClient();
+ when(client.fetchResultsV2(any(TSFetchResultsReq.class)))
+ .thenReturn(
+ fragmentResponse(ByteBuffer.wrap(first, 0, firstSplit),
firstSplit, first.length, true),
+ response(
+ List.of(
+ ByteBuffer.wrap(first, firstSplit, first.length -
firstSplit),
+ ByteBuffer.wrap(second),
+ ByteBuffer.wrap(third, 0, thirdSplit)),
+ thirdSplit,
+ third.length,
+ true),
+ fragmentResponse(
+ ByteBuffer.wrap(third, thirdSplit, third.length - thirdSplit),
-1, -1, false));
+
+ IoTDBRpcDataSet dataSet = newDataSet(client);
+
+ // the response that completes the first fragment also carries the next
block, and one
+ // response can end with a new fragment again
+ long[] expected = {10L, 20L, 30L, 40L, 50L, 60L};
+ for (long value : expected) {
+ assertTrue(dataSet.next());
+ assertEquals(value, dataSet.getLong(COLUMN));
+ }
+ assertFalse(dataSet.next());
+
+ ArgumentCaptor<TSFetchResultsReq> captor =
ArgumentCaptor.forClass(TSFetchResultsReq.class);
+ verify(client, times(3)).fetchResultsV2(captor.capture());
+ assertEquals(0, captor.getAllValues().get(0).getOffset());
+ assertEquals(firstSplit, captor.getAllValues().get(1).getOffset());
+ assertEquals(thirdSplit, captor.getAllValues().get(2).getOffset());
+ }
+
+ @Test
+ public void testFragmentTailThenWholeBlockInNextResponse() throws Exception {
+ byte[] first = serializeInt64Block(10L);
+ byte[] second = serializeInt64Block(30L);
+ int split = first.length / 2;
+
+ IClientRPCService.Iface client = mockClient();
+ when(client.fetchResultsV2(any(TSFetchResultsReq.class)))
+ .thenReturn(
+ fragmentResponse(ByteBuffer.wrap(first, 0, split), split,
first.length, true),
+ // the tail completes the fragment without starting a new one: the
server held the
+ // following block back for the next response
+ response(List.of(ByteBuffer.wrap(first, split, first.length -
split)), -1, -1, true),
+ response(List.of(ByteBuffer.wrap(second)), -1, -1, false));
+
+ IoTDBRpcDataSet dataSet = newDataSet(client);
+
+ long[] expected = {10L, 20L, 30L, 40L};
+ for (long value : expected) {
+ assertTrue(dataSet.next());
+ assertEquals(value, dataSet.getLong(COLUMN));
+ }
+ assertFalse(dataSet.next());
+
+ // nothing is pending on the client after the tail, so the third request
starts from offset 0
+ ArgumentCaptor<TSFetchResultsReq> captor =
ArgumentCaptor.forClass(TSFetchResultsReq.class);
+ verify(client, times(3)).fetchResultsV2(captor.capture());
+ assertEquals(0, captor.getAllValues().get(0).getOffset());
+ assertEquals(split, captor.getAllValues().get(1).getOffset());
+ assertEquals(0, captor.getAllValues().get(2).getOffset());
+ }
+
@Test
public void testLegacyResponseWithoutOffset() throws Exception {
- byte[] bytes = serializeInt64Block();
+ byte[] bytes = serializeInt64Block(10L);
IClientRPCService.Iface client = mockClient();
when(client.fetchResultsV2(any(TSFetchResultsReq.class)))
.thenReturn(response(List.of(ByteBuffer.wrap(bytes)), -1, -1, false));
@@ -123,7 +199,7 @@ public class IoTDBRpcDataSetFragmentTest {
@Test
public void testBlocksInExecuteResponseAreConsumedBeforeFetching() throws
Exception {
- byte[] bytes = serializeInt64Block();
+ byte[] bytes = serializeInt64Block(10L);
IClientRPCService.Iface client = mockClient();
IoTDBRpcDataSet dataSet =
new IoTDBRpcDataSet(
@@ -156,7 +232,7 @@ public class IoTDBRpcDataSetFragmentTest {
@Test(expected = IllegalArgumentException.class)
public void testRejectMissingTotalLengthForFirstFragment() throws Exception {
- byte[] bytes = serializeInt64Block();
+ byte[] bytes = serializeInt64Block(10L);
IClientRPCService.Iface client = mockClient();
when(client.fetchResultsV2(any(TSFetchResultsReq.class)))
.thenReturn(
@@ -169,7 +245,7 @@ public class IoTDBRpcDataSetFragmentTest {
@Test(expected = IllegalArgumentException.class)
public void testRejectNonIncreasingFragmentOffset() throws Exception {
- byte[] bytes = serializeInt64Block();
+ byte[] bytes = serializeInt64Block(10L);
int split = bytes.length / 2;
IClientRPCService.Iface client = mockClient();
// the offset must equal the accumulated length, otherwise the dataset
must refuse to continue
@@ -230,14 +306,14 @@ public class IoTDBRpcDataSetFragmentTest {
return resp;
}
- /** [time=1, s1=10], [time=2, s1=20] as an INT64 column. */
- private static byte[] serializeInt64Block() throws Exception {
+ /** [time=1, s1=valueBase], [time=2, s1=valueBase+10] as an INT64 column. */
+ private static byte[] serializeInt64Block(long valueBase) throws Exception {
TsBlockBuilder builder = new
TsBlockBuilder(Collections.singletonList(TSDataType.INT64));
builder.getTimeColumnBuilder().writeLong(1L);
- builder.getColumnBuilder(0).writeLong(10L);
+ builder.getColumnBuilder(0).writeLong(valueBase);
builder.declarePosition();
builder.getTimeColumnBuilder().writeLong(2L);
- builder.getColumnBuilder(0).writeLong(20L);
+ builder.getColumnBuilder(0).writeLong(valueBase + 10L);
builder.declarePosition();
TsBlock tsBlock = builder.build();
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java
index c848b7b2cad..381af85f626 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java
@@ -45,6 +45,14 @@ public interface IQueryExecution {
Optional<ByteBuffer> getByteBufferBatchResult() throws IoTDBException;
+ /**
+ * Returns whether {@link #getByteBufferBatchResult()} can provide a batch
without waiting for the
+ * producer. Executions whose results are already materialized never block,
hence the default.
+ */
+ default boolean isResultAvailable() {
+ return true;
+ }
+
/** Returns the pending fragment holder, or null if this execution does not
fragment results. */
default PendingResultFragment getPendingResultFragment() {
return null;
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java
index 80040958f50..a91be355554 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java
@@ -24,7 +24,13 @@ import java.nio.ByteBuffer;
/**
* The tail of a serialized TsBlock that did not fit into the previous RPC
response and is waiting
* to be sent in the following response(s). The block is already serialized
and removed from the
- * result handle, so this fragment only holds a reference to it and never
copies the payload.
+ * result handle, so this fragment only holds a reference to it and never
copies the payload. The
+ * block's row count is recorded so that the response completing the fragment
can keep packing new
+ * blocks into the same response while respecting the fetch size.
+ *
+ * <p>The fragment also holds a block that has not been sent at all ({@code
nextOffset} 0) when the
+ * response that completed another fragment had no room left for it: such a
block is delivered whole
+ * by the next response from a fresh payload instead of being fragmented.
*
* <p>The memory of the pending block is reserved from the query memory pool
through an {@link
* Account} owned by the query, and released when the fragment is {@link
#clear() cleared}. The
@@ -53,13 +59,17 @@ public class PendingResultFragment {
private ByteBuffer block;
private int nextOffset;
+ private int rowCount;
public PendingResultFragment(Account account) {
this.account = account;
}
- /** Records that {@code block} has been sent up to {@code nextOffset} bytes.
*/
- public void reset(ByteBuffer block, int nextOffset) {
+ /**
+ * Records that {@code block}, with {@code rowCount} rows, has been sent up
to {@code nextOffset}
+ * bytes.
+ */
+ public void reset(ByteBuffer block, int nextOffset, int rowCount) {
boolean newBlock;
boolean hadPending;
synchronized (this) {
@@ -67,6 +77,7 @@ public class PendingResultFragment {
newBlock = block != this.block;
this.block = block;
this.nextOffset = nextOffset;
+ this.rowCount = rowCount;
}
if (!newBlock || account == null) {
return;
@@ -93,6 +104,14 @@ public class PendingResultFragment {
return nextOffset;
}
+ /**
+ * Returns the row count of the pending block, so that the response
completing it can account for
+ * its rows when packing more blocks into the same response.
+ */
+ public synchronized int getRowCount() {
+ return rowCount;
+ }
+
/**
* Discards the pending fragment and releases the memory of the pending
block, cancelling a
* reservation that is still waiting. It is also called right after a
complete block has been
@@ -102,6 +121,7 @@ public class PendingResultFragment {
synchronized (this) {
block = null;
nextOffset = 0;
+ rowCount = 0;
}
if (account != null) {
account.release();
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java
index 97c8d25699b..956570acdb3 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java
@@ -737,6 +737,19 @@ public class QueryExecution implements IQueryExecution {
return pendingResultFragment;
}
+ /**
+ * Mirrors the waiting conditions of {@link #getResult}: a batch can be
obtained without waiting
+ * once the result handle is finished or aborted, or once the future
returned by {@link
+ * ISourceHandle#isBlocked()} completes, since the request thread is the
only consumer.
+ */
+ @Override
+ public boolean isResultAvailable() {
+ return resultHandle == null
+ || resultHandle.isFinished()
+ || resultHandle.isAborted()
+ || resultHandle.isBlocked().isDone();
+ }
+
private ByteBuffer getSerializedTsBlock() throws IoTDBException {
return resultHandle.getSerializedTsBlock();
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java
index dc6e755977f..9c96409c68a 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java
@@ -272,7 +272,15 @@ public class QueryDataSetUtils {
* Fetches query results with a bounded payload size. A serialized TsBlock
larger than {@code
* maxPayloadSize} is cut into fragments: the response only carries the
bytes that fit into the
* payload, and the remaining bytes are kept in {@link
PendingResultFragment} on the query
- * execution, to be sent by the following request carrying the returned
offset.
+ * execution, to be sent by the following request carrying the returned
offset. The response that
+ * completes a pending fragment keeps packing subsequent TsBlocks that are
already available while
+ * the payload and the fetch size still have room, so a fragmented block
does not cost an extra
+ * round trip; a block that does not fit into the remaining space is left
whole for the next
+ * response instead of being fragmented.
+ *
+ * <p>{@code fetchSize} is a soft bound, like {@link
#convertQueryResultByFetchSize(
+ * IQueryExecution, int)}: it is checked before pulling each block, so one
response can exceed it
+ * by up to the rows of the last block it carries.
*/
public static ResultChunk convertQueryResultByFetchSize(
IQueryExecution queryExecution, int fetchSize, int requestOffset, int
maxPayloadSize)
@@ -298,8 +306,14 @@ public class QueryDataSetUtils {
return ResultChunk.complete(pair.left, pair.right);
}
ByteBuffer pendingBlock = pendingFragment.getBlock();
+ // whether this response continues a pending fragment; such a response is
not delayed by
+ // blocks that are still being produced, and it keeps a whole block that
does not fit into the
+ // remaining payload for the next response instead of fragmenting it
+ boolean continuation = false;
if (pendingBlock != null) {
+ continuation = true;
int nextOffset = pendingFragment.getNextOffset();
+ int pendingRowCount = pendingFragment.getRowCount();
if (requestOffset != nextOffset) {
throw new IllegalArgumentException(
String.format(
@@ -310,15 +324,22 @@ public class QueryDataSetUtils {
}
int fragmentSize = Math.min(remainingPayloadSize, pendingBlock.limit() -
nextOffset);
res.add(slice(pendingBlock, nextOffset, fragmentSize));
- if (nextOffset + fragmentSize == pendingBlock.limit()) {
- pendingFragment.clear();
- // Do not fetch new blocks in the same response, otherwise the
response would carry the
- // tail of the big block plus up to fetchSize new rows, whose row
count is not accounted
- // for. One response either continues a fragmented block or delivers
new blocks.
- return ResultChunk.complete(res, !queryExecution.hasNextResult());
+ if (nextOffset + fragmentSize < pendingBlock.limit()) {
+ pendingFragment.reset(pendingBlock, nextOffset + fragmentSize,
pendingRowCount);
+ // A block held whole starts its fragment in this response, and the
client has no
+ // reassembly buffer for it yet, so it needs the total length; when a
fragment is
+ // continued, the client already holds the total length of the
response that started it.
+ return ResultChunk.fragment(
+ res, nextOffset + fragmentSize, nextOffset == 0 ?
pendingBlock.limit() : -1, false);
}
- pendingFragment.reset(pendingBlock, nextOffset + fragmentSize);
- return ResultChunk.fragment(res, nextOffset + fragmentSize, -1, false);
+ // The tail completes the fragmented block, but it usually leaves room
in this response.
+ // The rows of the completed block count against fetchSize, then the
response continues with
+ // new blocks instead of ending here, so an ordinary block that got
fragmented does not cost
+ // an extra round trip.
+ rowCount = pendingRowCount;
+ pendingFragment.clear();
+ remainingPayloadSize -= fragmentSize;
+ memorySize += fragmentSize;
} else if (requestOffset != 0) {
throw new IllegalArgumentException(
String.format(
@@ -328,6 +349,12 @@ public class QueryDataSetUtils {
}
while (rowCount < fetchSize && memorySize < MAX_RETURN_SIZE &&
remainingPayloadSize > 0) {
+ // A continuation already carries the tail the client waits for;
blocking here on a block
+ // that is still being produced would delay that response, so end it and
let the following
+ // request wait for the block instead.
+ if (continuation && !queryExecution.isResultAvailable()) {
+ break;
+ }
Optional<ByteBuffer> optionalByteBuffer =
queryExecution.getByteBufferBatchResult();
if (!optionalByteBuffer.isPresent()) {
break;
@@ -346,9 +373,16 @@ public class QueryDataSetUtils {
remainingPayloadSize -= blockSize;
memorySize += blockSize;
pendingFragment.clear();
+ } else if (continuation) {
+ // The block does not fit into what is left of this response. Keep it
whole for the next
+ // response instead of fragmenting it: fragmenting it here would leave
the next response
+ // the same leftover space, and so fragment every following block
again. A block larger
+ // than a whole payload is fragmented by the next response as usual.
+ pendingFragment.reset(byteBuffer, 0, positionCount);
+ return ResultChunk.complete(res, false);
} else {
res.add(slice(byteBuffer, 0, remainingPayloadSize));
- pendingFragment.reset(byteBuffer, remainingPayloadSize);
+ pendingFragment.reset(byteBuffer, remainingPayloadSize, positionCount);
return ResultChunk.fragment(res, remainingPayloadSize, blockSize,
false);
}
}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java
index e1118399c53..817f6a8a237 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java
@@ -41,19 +41,21 @@ public class PendingResultFragmentTest {
PendingResultFragment fragment = new PendingResultFragment(account);
ByteBuffer block = ByteBuffer.allocate(100);
- fragment.reset(block, 30);
+ fragment.reset(block, 30, 2);
assertEquals(List.of(100L), account.reserved);
assertEquals(0, account.releases);
// continuing the same block must not reserve again
- fragment.reset(block, 60);
+ fragment.reset(block, 60, 2);
assertEquals(List.of(100L), account.reserved);
assertSame(block, fragment.getBlock());
assertEquals(60, fragment.getNextOffset());
+ assertEquals(2, fragment.getRowCount());
fragment.clear();
assertEquals(1, account.releases);
assertNull(fragment.getBlock());
+ assertEquals(0, fragment.getRowCount());
}
@Test
@@ -61,19 +63,20 @@ public class PendingResultFragmentTest {
RecordingAccount account = new RecordingAccount();
PendingResultFragment fragment = new PendingResultFragment(account);
- fragment.reset(ByteBuffer.allocate(100), 30);
- fragment.reset(ByteBuffer.allocate(50), 10);
+ fragment.reset(ByteBuffer.allocate(100), 30, 1);
+ fragment.reset(ByteBuffer.allocate(50), 10, 3);
// the previous reservation is released before the new one is taken
assertEquals(List.of(100L, 50L), account.reserved);
assertEquals(1, account.releases);
assertEquals(50L, account.accounted);
+ assertEquals(3, fragment.getRowCount());
}
@Test
public void testNullAccountDisablesAccounting() {
PendingResultFragment fragment = new PendingResultFragment(null);
- fragment.reset(ByteBuffer.allocate(100), 30);
+ fragment.reset(ByteBuffer.allocate(100), 30, 1);
fragment.clear();
assertNull(fragment.getBlock());
}
@@ -88,7 +91,7 @@ public class PendingResultFragmentTest {
new Thread(
() -> {
try {
- fragment.reset(ByteBuffer.allocate(100), 30);
+ fragment.reset(ByteBuffer.allocate(100), 30, 1);
} catch (IllegalStateException expected) {
// the reservation was cancelled by the cleanup
failure.set(expected);
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java
index febb7014600..bed8791683e 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java
@@ -41,6 +41,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -48,6 +49,8 @@ import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class QueryDataSetUtilsTest {
@@ -299,6 +302,7 @@ public class QueryDataSetUtilsTest {
Mockito.when(queryExecution.getByteBufferBatchResult())
.thenReturn(Optional.of(serialized.duplicate()), Optional.empty());
Mockito.when(queryExecution.hasNextResult()).thenReturn(false);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
QueryDataSetUtils.ResultChunk firstChunk =
QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
@@ -341,6 +345,7 @@ public class QueryDataSetUtilsTest {
Mockito.when(queryExecution.getByteBufferBatchResult())
.thenReturn(Optional.of(smallBlock),
Optional.of(serialized.duplicate()), Optional.empty());
Mockito.when(queryExecution.hasNextResult()).thenReturn(false);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
QueryDataSetUtils.ResultChunk firstChunk =
QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
@@ -364,7 +369,8 @@ public class QueryDataSetUtilsTest {
}
@Test
- public void testContinuationCompletionDoesNotFetchNewBlocks() throws
IoTDBException, IOException {
+ public void testContinuationCompletesFragmentAndDeliversFollowingBlocks()
+ throws IoTDBException, IOException {
TsBlock tsBlock = buildTsBlock();
ByteBuffer serialized = new TsBlockSerde().serialize(tsBlock);
int blockSize = serialized.remaining();
@@ -378,31 +384,295 @@ public class QueryDataSetUtilsTest {
Optional.of(serialized.duplicate()),
Optional.of(serialized.duplicate()),
Optional.empty());
- Mockito.when(queryExecution.hasNextResult()).thenReturn(true, false);
+ Mockito.when(queryExecution.hasNextResult()).thenReturn(false);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
QueryDataSetUtils.ResultChunk firstChunk =
QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
assertFalse(firstChunk.isFinished());
assertEquals(payloadSize, firstChunk.getNextOffset());
+ assertEquals(tsBlock.getPositionCount(), pendingFragment.getRowCount());
+
+ // The response that completes the fragmented block continues with the
following blocks while
+ // the payload and the fetch size still have room, instead of ending here
and costing an extra
+ // round trip.
+ QueryDataSetUtils.ResultChunk continuationChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, 10, firstChunk.getNextOffset(), 2 * blockSize);
+ assertTrue(continuationChunk.isFinished());
+ assertFalse(continuationChunk.hasNextOffset());
+ assertEquals(2, continuationChunk.getQueryResult().size());
+ // the tail of the fragmented block comes first
+ assertEquals(blockSize - payloadSize,
continuationChunk.getQueryResult().get(0).remaining());
+ // then the following block, delivered by the same response
+ assertEquals(blockSize,
continuationChunk.getQueryResult().get(1).remaining());
+ assertNull(pendingFragment.getBlock());
+ }
+
+ @Test
+ public void testContinuationCountsPendingRowsAgainstFetchSize()
+ throws IoTDBException, IOException {
+ TsBlock tsBlock = buildTsBlock();
+ ByteBuffer serialized = new TsBlockSerde().serialize(tsBlock);
+ int blockSize = serialized.remaining();
+ int payloadSize = blockSize / 2;
+
+ IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class);
+ PendingResultFragment pendingFragment = new PendingResultFragment(null);
+
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
+ Mockito.when(queryExecution.getByteBufferBatchResult())
+ .thenReturn(
+ Optional.of(serialized.duplicate()),
+ Optional.of(serialized.duplicate()),
+ Optional.empty());
+ Mockito.when(queryExecution.hasNextResult()).thenReturn(true, false);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
+
+ // fetchSize equals the rows of one block
+ QueryDataSetUtils.ResultChunk firstChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, tsBlock.getPositionCount(), 0, payloadSize);
+ assertFalse(firstChunk.isFinished());
+ assertEquals(tsBlock.getPositionCount(), pendingFragment.getRowCount());
- // The response that completes the fragmented block must not fetch new
blocks, otherwise its
- // row count would exceed fetchSize (the tail of the big block is not
accounted).
+ // The rows of the completed block already fill the fetch size, so the
continuation response
+ // stops after the tail even though the payload still has room.
QueryDataSetUtils.ResultChunk continuationChunk =
QueryDataSetUtils.convertQueryResultByFetchSize(
- queryExecution, 10, firstChunk.getNextOffset(), blockSize);
+ queryExecution, tsBlock.getPositionCount(),
firstChunk.getNextOffset(), 2 * blockSize);
assertFalse(continuationChunk.isFinished());
assertFalse(continuationChunk.hasNextOffset());
assertEquals(1, continuationChunk.getQueryResult().size());
assertEquals(blockSize - payloadSize,
continuationChunk.getQueryResult().get(0).remaining());
- assertTrue(pendingFragment.getBlock() == null);
+ assertNull(pendingFragment.getBlock());
+
+ // The following block is delivered by the next request.
+ QueryDataSetUtils.ResultChunk nextChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, tsBlock.getPositionCount(), 0, 2 * blockSize);
+ assertTrue(nextChunk.isFinished());
+ assertFalse(nextChunk.hasNextOffset());
+ assertEquals(1, nextChunk.getQueryResult().size());
+ assertEquals(blockSize, nextChunk.getQueryResult().get(0).remaining());
+ }
+
+ @Test
+ public void testContinuationHoldsWholeBlockThatFitsFreshResponse()
+ throws IoTDBException, IOException {
+ ByteBuffer first = serializeTextBlock(64 * 1024);
+ ByteBuffer second = serializeTextBlock(64 * 1024);
+ ByteBuffer third = serializeTextBlock(64 * 1024);
+ int blockSize = first.remaining();
+ // 1.2 blocks: the first block fits with 0.2 left, so the second one is
fragmented at 0.2;
+ // the continuation completes it with 0.8 left, and the third block (1.0)
fits into a fresh
+ // payload but not into the remaining space
+ int payloadSize = blockSize + blockSize / 5;
+
+ IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class);
+ PendingResultFragment pendingFragment = new PendingResultFragment(null);
+
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
+ Mockito.when(queryExecution.getByteBufferBatchResult())
+ .thenReturn(
+ Optional.of(first.duplicate()),
+ Optional.of(second.duplicate()),
+ Optional.of(third.duplicate()),
+ Optional.empty());
+ Mockito.when(queryExecution.hasNextResult()).thenReturn(false);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
+
+ QueryDataSetUtils.ResultChunk firstChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
+ assertFalse(firstChunk.isFinished());
+ assertTrue(firstChunk.hasNextOffset());
+ assertEquals(payloadSize - blockSize, firstChunk.getNextOffset());
+ assertEquals(blockSize, firstChunk.getTotalLength());
+
+ // The continuation must not fragment the third block at the remaining
space: it keeps it whole
+ // for the next response, which sees a fresh payload.
+ QueryDataSetUtils.ResultChunk continuationChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, 10, firstChunk.getNextOffset(), payloadSize);
+ assertFalse(continuationChunk.isFinished());
+ assertFalse(continuationChunk.hasNextOffset());
+ assertEquals(1, continuationChunk.getQueryResult().size());
+ assertEquals(
+ blockSize - (payloadSize - blockSize),
+ continuationChunk.getQueryResult().get(0).remaining());
+ assertNotNull(pendingFragment.getBlock());
+ assertEquals(0, pendingFragment.getNextOffset());
+ assertEquals(1, pendingFragment.getRowCount());
- // New blocks are delivered by the following request only
+ // The next request delivers the held block whole.
QueryDataSetUtils.ResultChunk nextChunk =
- QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
blockSize);
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
assertTrue(nextChunk.isFinished());
assertFalse(nextChunk.hasNextOffset());
assertEquals(1, nextChunk.getQueryResult().size());
assertEquals(blockSize, nextChunk.getQueryResult().get(0).remaining());
+ assertNull(pendingFragment.getBlock());
+ }
+
+ @Test
+ public void
testResumingHeldBlockLargerThanPayloadStartsFragmentWithTotalLength()
+ throws IoTDBException, IOException {
+ ByteBuffer first = serializeTextBlock(96 * 1024);
+ ByteBuffer second = serializeTextBlock(96 * 1024);
+ int blockSize = first.remaining();
+ // the payload is smaller than a block, so the second block held by the
continuation starts
+ // a fragment of its own in the response that resumes it; the extra bytes
leave room for the
+ // odd serialized size, so that the continuation does complete the first
tail
+ int payloadSize = blockSize / 2 + 16;
+
+ IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class);
+ PendingResultFragment pendingFragment = new PendingResultFragment(null);
+
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
+ Mockito.when(queryExecution.getByteBufferBatchResult())
+ .thenReturn(
+ Optional.of(first.duplicate()), Optional.of(second.duplicate()),
Optional.empty());
+ Mockito.when(queryExecution.hasNextResult()).thenReturn(false);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
+
+ QueryDataSetUtils.ResultChunk firstChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
+ assertFalse(firstChunk.isFinished());
+ assertEquals(payloadSize, firstChunk.getNextOffset());
+ assertEquals(blockSize, firstChunk.getTotalLength());
+
+ // the continuation completes the first block and holds the second one
whole
+ QueryDataSetUtils.ResultChunk continuationChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, 10, firstChunk.getNextOffset(), payloadSize);
+ assertFalse(continuationChunk.isFinished());
+ assertFalse(continuationChunk.hasNextOffset());
+ assertNotNull(pendingFragment.getBlock());
+ assertEquals(0, pendingFragment.getNextOffset());
+
+ // Resuming the held block: it does not fit into the payload either, so
this response starts
+ // its fragment. The client has no reassembly buffer for it, so the total
length is required.
+ QueryDataSetUtils.ResultChunk resumedChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
+ assertFalse(resumedChunk.isFinished());
+ assertTrue(resumedChunk.hasNextOffset());
+ assertEquals(payloadSize, resumedChunk.getNextOffset());
+ assertTrue(resumedChunk.hasTotalLength());
+ assertEquals(blockSize, resumedChunk.getTotalLength());
+ assertEquals(1, resumedChunk.getQueryResult().size());
+ assertEquals(payloadSize,
resumedChunk.getQueryResult().get(0).remaining());
+
+ // the following continuation completes the block without repeating the
total length
+ QueryDataSetUtils.ResultChunk tailChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, 10, resumedChunk.getNextOffset(), payloadSize);
+ assertTrue(tailChunk.isFinished());
+ assertFalse(tailChunk.hasNextOffset());
+ assertEquals(blockSize - payloadSize,
tailChunk.getQueryResult().get(0).remaining());
+ assertNull(pendingFragment.getBlock());
+ }
+
+ @Test
+ public void testOrdinaryBlocksAreNotRepeatedlySplit() throws IoTDBException,
IOException {
+ // the scenario from the review: two smaller blocks followed by six blocks
of exactly one
+ // payload, which must not make every following block a fragment
+ List<ByteBuffer> blocks = new ArrayList<>();
+ blocks.add(serializeTextBlock(96 * 1024));
+ blocks.add(serializeTextBlock(96 * 1024));
+ for (int i = 0; i < 6; i++) {
+ blocks.add(serializeTextBlock(128 * 1024));
+ }
+ int payloadSize = blocks.get(2).remaining();
+ assertTrue(blocks.get(0).remaining() < payloadSize);
+
+ IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class);
+ PendingResultFragment pendingFragment = new PendingResultFragment(null);
+
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
+ Mockito.when(queryExecution.getByteBufferBatchResult())
+ .thenAnswer(
+ invocation ->
+ blocks.isEmpty() ? Optional.empty() :
Optional.of(blocks.remove(0).duplicate()));
+ Mockito.when(queryExecution.hasNextResult())
+ .thenAnswer(invocation -> !blocks.isEmpty() ||
pendingFragment.getBlock() != null);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
+
+ List<QueryDataSetUtils.ResultChunk> chunks = new ArrayList<>();
+ int offset = 0;
+ while (true) {
+ QueryDataSetUtils.ResultChunk chunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10,
offset, payloadSize);
+ chunks.add(chunk);
+ for (ByteBuffer block : chunk.getQueryResult()) {
+ assertTrue(block.remaining() <= payloadSize);
+ }
+ if (chunk.isFinished()) {
+ break;
+ }
+ offset = chunk.hasNextOffset() ? chunk.getNextOffset() : 0;
+ }
+
+ // one response per block, and only the second block (which landed near
the end of the first
+ // response) is split, so the client reassembles exactly one block
+ assertEquals(8, chunks.size());
+ assertEquals(1,
chunks.stream().filter(QueryDataSetUtils.ResultChunk::hasNextOffset).count());
+ // the response that completes the split block does not start another one
+ assertEquals(2, chunks.get(0).getQueryResult().size());
+ assertEquals(1, chunks.get(1).getQueryResult().size());
+ for (int i = 2; i < chunks.size(); i++) {
+ assertEquals(1, chunks.get(i).getQueryResult().size());
+ assertEquals(payloadSize,
chunks.get(i).getQueryResult().get(0).remaining());
+ }
+ }
+
+ @Test
+ public void testContinuationReturnsWithoutWaitingForUnavailableBlocks()
+ throws IoTDBException, IOException {
+ TsBlock tsBlock = buildTsBlock();
+ ByteBuffer serialized = new TsBlockSerde().serialize(tsBlock);
+ int blockSize = serialized.remaining();
+ int payloadSize = blockSize / 2;
+
+ IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class);
+ PendingResultFragment pendingFragment = new PendingResultFragment(null);
+
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
+ Mockito.when(queryExecution.getByteBufferBatchResult())
+ .thenReturn(
+ Optional.of(serialized.duplicate()),
+ Optional.of(serialized.duplicate()),
+ Optional.empty());
+ Mockito.when(queryExecution.hasNextResult()).thenReturn(true, false);
+
+ QueryDataSetUtils.ResultChunk firstChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
payloadSize);
+ assertFalse(firstChunk.isFinished());
+ assertEquals(payloadSize, firstChunk.getNextOffset());
+
+ // The next block is still being produced: the continuation must return
the tail immediately
+ // instead of waiting for it.
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(false);
+ QueryDataSetUtils.ResultChunk continuationChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(
+ queryExecution, 10, firstChunk.getNextOffset(), 2 * blockSize);
+ assertFalse(continuationChunk.isFinished());
+ assertFalse(continuationChunk.hasNextOffset());
+ assertEquals(1, continuationChunk.getQueryResult().size());
+ assertEquals(blockSize - payloadSize,
continuationChunk.getQueryResult().get(0).remaining());
+ Mockito.verify(queryExecution,
Mockito.times(1)).getByteBufferBatchResult();
+
+ // The following request waits for the block and delivers it.
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
+ QueryDataSetUtils.ResultChunk nextChunk =
+ QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0,
2 * blockSize);
+ assertTrue(nextChunk.isFinished());
+ assertEquals(1, nextChunk.getQueryResult().size());
+ assertEquals(blockSize, nextChunk.getQueryResult().get(0).remaining());
+ }
+
+ private ByteBuffer serializeTextBlock(int valueSize) throws IOException {
+ byte[] value = new byte[valueSize];
+ Arrays.fill(value, (byte) 'x');
+ TsBlockBuilder builder = new
TsBlockBuilder(Collections.singletonList(TSDataType.TEXT));
+ builder.getTimeColumnBuilder().writeLong(1L);
+ builder.getColumnBuilder(0).writeBinary(new Binary(value));
+ builder.declarePosition();
+ return new TsBlockSerde().serialize(builder.build());
}
@Test
@@ -430,7 +700,7 @@ public class QueryDataSetUtilsTest {
@Test(expected = IllegalArgumentException.class)
public void testConvertQueryResultByFetchSizeRejectsMismatchedOffset()
throws IoTDBException {
PendingResultFragment pendingFragment = new PendingResultFragment(null);
- pendingFragment.reset(ByteBuffer.wrap(new byte[10]), 5);
+ pendingFragment.reset(ByteBuffer.wrap(new byte[10]), 5, 0);
IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class);
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java
index 525cb4b2e17..3f119527e35 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java
@@ -125,6 +125,66 @@ public class ResultChunkingEndToEndTest {
assertEquals("the pending fragment must be cleared in the end", null,
server.getPendingBlock());
}
+ @Test(timeout = 60_000)
+ public void testHeldBlockLargerThanPayloadRoundTrip() throws Exception {
+ // the continuation holds the second block, which is larger than a whole
payload, and the
+ // response resuming it has to start its fragment with a total length for
the client
+ int[] textSizes = {300 * 1024, 400 * 1024, 8};
+ char[] fills = {'a', 'b', 'c'};
+ List<ByteBuffer> blocks = new ArrayList<>();
+ for (int i = 0; i < textSizes.length; i++) {
+ blocks.add(
+ new TsBlockSerde()
+ .serialize(buildTsBlockWithText(1_000L * (i + 1), fills[i],
textSizes[i])));
+ }
+
+ ServerSideSimulation server = new ServerSideSimulation(blocks, 100);
+
+ IClientRPCService.Iface client = mock(IClientRPCService.Iface.class);
+ when(client.closeOperation(any(TSCloseOperationReq.class)))
+ .thenReturn(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS));
+ when(client.fetchResultsV2(any(TSFetchResultsReq.class)))
+ .thenAnswer(invocation ->
server.handleFetchResults(invocation.getArgument(0)));
+
+ IoTDBRpcDataSet dataSet =
+ new IoTDBRpcDataSet(
+ "",
+ List.of(COLUMN, TEXT_COLUMN),
+ List.of(TSDataType.INT64.name(), TSDataType.TEXT.name()),
+ null,
+ true,
+ true,
+ 1L,
+ 2L,
+ client,
+ 3L,
+ null,
+ 100,
+ 0,
+ ZoneId.systemDefault(),
+ RpcUtils.DEFAULT_TIME_FORMAT,
+ 1_000_000,
+ true,
+ new ArrayList<>(Arrays.asList(0, 1)));
+
+ for (int i = 0; i < textSizes.length; i++) {
+ assertTrue(dataSet.next());
+ String value = dataSet.getString(TEXT_COLUMN);
+ assertEquals(textSizes[i], value.length());
+ assertEquals(fills[i], value.charAt(0));
+ }
+ assertFalse(dataSet.next());
+
+ assertEquals("the held block must cost no extra response", 4,
server.rpcCount.get());
+ for (int payload : server.payloadSizes) {
+ assertTrue(
+ String.format("one response payload %d exceeds the bound %d",
payload, MAX_PAYLOAD_SIZE),
+ payload <= MAX_PAYLOAD_SIZE);
+ }
+ assertTrue(server.releaseCount.get() > 0);
+ assertEquals("the pending fragment must be cleared in the end", null,
server.getPendingBlock());
+ }
+
@Test(timeout = 60_000)
public void testSmallResultUsesOneResponseWithoutFragment() throws Exception
{
TsBlockBuilder builder = new TsBlockBuilder(List.of(TSDataType.INT64));
@@ -197,12 +257,17 @@ public class ResultChunkingEndToEndTest {
private ServerSideSimulation(ByteBuffer serialized, int positionCount, int
totalLength)
throws Exception {
- this.serialized = serialized;
- this.positionCount = positionCount;
- this.totalLength = totalLength;
- this.remainingBlocks.add(serialized);
+ this(List.of(serialized), positionCount);
+ }
+
+ private ServerSideSimulation(List<ByteBuffer> blocks, int fetchSize)
throws Exception {
+ this.serialized = null;
+ this.positionCount = fetchSize;
+ this.totalLength = -1;
+ this.remainingBlocks.addAll(blocks);
this.queryExecution = Mockito.mock(IQueryExecution.class);
Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
+ Mockito.when(queryExecution.isResultAvailable()).thenReturn(true);
Mockito.when(queryExecution.getByteBufferBatchResult())
.thenAnswer(
invocation ->
@@ -247,6 +312,18 @@ public class ResultChunkingEndToEndTest {
}
}
+ /** [time=time, v=time/1000, text=textSize bytes of {@code fill}]. */
+ private static TsBlock buildTsBlockWithText(long time, char fill, int
textSize) {
+ byte[] value = new byte[textSize];
+ Arrays.fill(value, (byte) fill);
+ TsBlockBuilder builder = new
TsBlockBuilder(Arrays.asList(TSDataType.INT64, TSDataType.TEXT));
+ builder.getTimeColumnBuilder().writeLong(time);
+ builder.getColumnBuilder(0).writeLong(time / 1000);
+ builder.getColumnBuilder(1).writeBinary(new Binary(value));
+ builder.declarePosition();
+ return builder.build();
+ }
+
/** [time=1, v=10, text="small"], [time=2, v=20, text=<LARGE_VALUE_SIZE
bytes>]. */
private static TsBlock buildTsBlockWithLargeValue() {
byte[] largeValue = new byte[LARGE_VALUE_SIZE];