diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java index 92dbb89ecaf8c..c9ee35070d2a4 100644 --- a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java +++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java @@ -49,6 +49,7 @@ public class IndexedConsensusRequest implements IConsensusRequest { private long memorySize = 0; private long retainedMemorySize = 0; private boolean serializedRequestsBuilt = false; + private boolean clearRequestsAfterSerialization; private long queueReservedMemorySize = -1L; private boolean containsUserData = false; private final AtomicLong referenceCnt = new AtomicLong(); @@ -80,6 +81,9 @@ public synchronized void buildSerializedRequests() { this.retainedMemorySize += buffer.capacity() + r.getMemorySize(); }); serializedRequestsBuilt = true; + if (clearRequestsAfterSerialization) { + clearRequests(); + } } @Override @@ -147,6 +151,17 @@ public synchronized void clearRequests() { requests.clear(); } + /** + * Clears source requests after deferred serialization when no subscription queue needs them. The + * serialized buffers remain available to replication retries. + */ + public synchronized void clearRequestsAfterSerialization() { + clearRequestsAfterSerialization = true; + if (serializedRequestsBuilt) { + clearRequests(); + } + } + public long getSearchIndex() { return searchIndex; } diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java index dda7c2b022944..c78621cbb602d 100644 --- a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java +++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java @@ -291,6 +291,8 @@ public void stop() { public TSStatus write(IConsensusRequest request) { long consensusWriteStartTime = System.nanoTime(); stateMachineLock.lock(); + IndexedConsensusRequest requestToSerialize = null; + boolean recordConsensusWriteTime = false; try { long getStateMachineLockTime = System.nanoTime(); // statistic the time of acquiring stateMachine lock @@ -345,6 +347,7 @@ public TSStatus write(IConsensusRequest request) { indexedConsensusRequest.getPhysicalTime(), thisNode.getNodeId(), indexedConsensusRequest.getLocalSeq()); + requestToSerialize = indexedConsensusRequest; // The index is used when constructing batch in LogDispatcher. If its value // increases but the corresponding request does not exist or is not put into // the queue, the dispatcher will try to find the request in WAL. This behavior @@ -388,13 +391,23 @@ public TSStatus write(IConsensusRequest request) { subscriptionQueueRegistry.size(), System.identityHashCode(this)); } - // statistic the time of total write process - ioTConsensusServerMetrics.recordConsensusWriteTime( - System.nanoTime() - consensusWriteStartTime); + recordConsensusWriteTime = true; return result; } finally { stateMachineLock.unlock(); - persistLatestWriterMeta(false); + try { + // Deferred requests are materialized after releasing the per-region lock and before the + // caller can reuse the applied plan node. + if (requestToSerialize != null) { + requestToSerialize.buildSerializedRequests(); + } + if (recordConsensusWriteTime) { + ioTConsensusServerMetrics.recordConsensusWriteTime( + System.nanoTime() - consensusWriteStartTime); + } + } finally { + persistLatestWriterMeta(false); + } } } diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java index 7cb5e7a63e038..49d21b17af87f 100644 --- a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java +++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java @@ -241,32 +241,38 @@ public void offer(IndexedConsensusRequest request) { public void offer(IndexedConsensusRequest request, boolean keepRequestsForSubscription) { // we don't need to serialize and offer request when replicaNum is 1. if (!threads.isEmpty()) { - // A request that deferred its serialization keeps only its source objects, which stay small, - // so that the entries waiting in the queues to be replicated do not retain their payloads. - // Such requests materialize their bytes when a batch is built instead. + // The memory manager accounts for deferred source objects until batch construction + // materializes their bytes. final boolean serializationDeferred = request.hasDeferredRequests(); if (!serializationDeferred) { request.buildSerializedRequests(); } if (!keepRequestsForSubscription && !serializationDeferred) { request.clearRequests(); + } else if (!keepRequestsForSubscription) { + request.clearRequestsAfterSerialization(); } + boolean offeredToAnyThread = false; synchronized (this) { - threads.forEach( - thread -> { - logger.debug( - IoTConsensusMessages.PUSH_LOG_TO_QUEUE, - impl.getThisNode().getGroupId(), - thread.getPeer().getEndpoint().getIp(), - thread.getPendingEntriesSize()); - if (!thread.offer(request)) { - logger.debug( - IoTConsensusMessages.LOG_QUEUE_FULL, - impl.getThisNode().getGroupId(), - thread.getPeer(), - request.getSearchIndex()); - } - }); + for (LogDispatcherThread thread : threads) { + logger.debug( + IoTConsensusMessages.PUSH_LOG_TO_QUEUE, + impl.getThisNode().getGroupId(), + thread.getPeer().getEndpoint().getIp(), + thread.getPendingEntriesSize()); + if (thread.offer(request)) { + offeredToAnyThread = true; + } else { + logger.debug( + IoTConsensusMessages.LOG_QUEUE_FULL, + impl.getThisNode().getGroupId(), + thread.getPeer(), + request.getSearchIndex()); + } + } + } + if (!keepRequestsForSubscription && serializationDeferred && !offeredToAnyThread) { + request.clearRequests(); } } else if (!keepRequestsForSubscription) { // A single-replica region has no dispatcher thread, but still does not need the raw request diff --git a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequestTest.java b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequestTest.java index 9a1878f4c3833..56993764f457f 100644 --- a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequestTest.java +++ b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequestTest.java @@ -70,6 +70,25 @@ public void testQueueReservationSurvivesDeferredSerialization() { Assert.assertEquals(64L, request.getQueueReservedMemorySize()); } + // A serialized replication request releases its source object when no subscription retains it. + @Test + public void testDeferredSourceCanBeClearedAfterSerialization() { + final CountingRequest deferred = new CountingRequest(true); + final IndexedConsensusRequest request = + new IndexedConsensusRequest(1L, 1L, Collections.singletonList(deferred)); + Assert.assertEquals(64L, request.getQueueReservedMemorySize()); + + request.clearRequestsAfterSerialization(); + request.buildSerializedRequests(); + + Assert.assertTrue(request.getRequests().isEmpty()); + Assert.assertEquals(1, deferred.serializationCount); + Assert.assertEquals(64L, request.getMemorySize()); + Assert.assertEquals(32L, request.getRetainedMemorySize()); + Assert.assertEquals(64L, request.getQueueReservedMemorySize()); + Assert.assertEquals(1, request.getSerializedRequests().size()); + } + @Test public void testRequestThatSerializesEagerlyIsNotTreatedAsDeferred() { final CountingRequest eager = new CountingRequest(false); diff --git a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java index 41677b98700b6..82b813538a835 100644 --- a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java +++ b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java @@ -46,23 +46,28 @@ import org.junit.rules.TemporaryFolder; import java.lang.reflect.Field; +import java.nio.ByteBuffer; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Spliterator; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; @@ -109,6 +114,66 @@ public void testNewPeerImmediatelyProtectsWALAndCatchupTimesOut() throws Excepti } } + // A deferred local write is serialized after the state machine lock is released, before callers + // can reuse the request, and subscription consumers still receive its serialized bytes. + @Test + public void testDeferredWriteIsSerializedAfterStateMachineLockRelease() throws Exception { + final FakeConsensusReqReader reader = mock(FakeConsensusReqReader.class); + final ScheduledExecutorService background = Executors.newSingleThreadScheduledExecutor(); + final Peer self = new Peer(new DataRegionId(1), 0, new TEndPoint("127.0.0.1", 6667)); + final TestStateMachine stateMachine = + new TestStateMachine() { + @Override + public synchronized DataSet read(IConsensusRequest ignored) { + return reader; + } + + @Override + public TSStatus write(IConsensusRequest ignored) { + return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()); + } + }; + final IoTConsensusServerImpl server = + new IoTConsensusServerImpl( + temporaryFolder.getRoot().getAbsolutePath(), + null, + DirectoryStrategyType.SEQUENCE_STRATEGY, + self, + Collections.singletonList(self), + stateMachine, + background, + null, + null, + IoTConsensusConfig.newBuilder().build()); + final Field stateMachineLockField = + IoTConsensusServerImpl.class.getDeclaredField("stateMachineLock"); + stateMachineLockField.setAccessible(true); + final ReentrantLock stateMachineLock = (ReentrantLock) stateMachineLockField.get(server); + final DeferredRequest request = new DeferredRequest(stateMachineLock); + final BlockingQueue subscriptionQueue = new LinkedBlockingQueue<>(); + server.registerSubscriptionQueue( + subscriptionQueue, + new SubscriptionWalRetentionPolicy( + "test", + SubscriptionWalRetentionPolicy.UNBOUNDED, + SubscriptionWalRetentionPolicy.UNBOUNDED), + () -> 0L); + + try { + assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), server.write(request).getCode()); + assertTrue(request.isSerialized()); + assertFalse(request.wasSerializedWhileLockHeld()); + final IndexedConsensusRequest deliveredRequest = subscriptionQueue.poll(); + assertNotNull(deliveredRequest); + assertFalse(deliveredRequest.getSerializedRequests().isEmpty()); + assertTrue(deliveredRequest.getRequests().contains(request)); + } finally { + server.deregisterSubscriptionQueue(subscriptionQueue); + server.stop(); + background.shutdownNow(); + } + } + @Test public void testMissingWALCannotProduceAnAcknowledgableBatch() throws Exception { FakeConsensusReqReader reader = mock(FakeConsensusReqReader.class); @@ -384,4 +449,39 @@ private static void assertValidSnapshot(List snapshot) { assertTrue(snapshot.get(index - 1).compareTo(snapshot.get(index)) < 0); } } + + private static class DeferredRequest implements IConsensusRequest { + private final ReentrantLock stateMachineLock; + private boolean serialized; + private boolean serializedWhileLockHeld; + + private DeferredRequest(ReentrantLock stateMachineLock) { + this.stateMachineLock = stateMachineLock; + } + + @Override + public ByteBuffer serializeToByteBuffer() { + serialized = true; + serializedWhileLockHeld = stateMachineLock.isHeldByCurrentThread(); + return ByteBuffer.allocate(Integer.BYTES); + } + + @Override + public long getMemorySize() { + return Integer.BYTES; + } + + @Override + public boolean isSerializationDeferred() { + return true; + } + + private boolean isSerialized() { + return serialized; + } + + private boolean wasSerializedWhileLockHeld() { + return serializedWhileLockHeld; + } + } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/pipe/PipeEnrichedInsertNode.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/pipe/PipeEnrichedInsertNode.java index 0f527ab45424c..23802c63b138e 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/pipe/PipeEnrichedInsertNode.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/pipe/PipeEnrichedInsertNode.java @@ -39,6 +39,7 @@ import org.apache.tsfile.enums.TSDataType; import org.apache.tsfile.file.metadata.IDeviceID; +import org.apache.tsfile.utils.RamUsageEstimator; import org.apache.tsfile.utils.ReadWriteIOUtils; import org.apache.tsfile.write.schema.MeasurementSchema; @@ -61,6 +62,9 @@ */ public class PipeEnrichedInsertNode extends InsertNode { + private static final long INSTANCE_SIZE = + RamUsageEstimator.shallowSizeOfInstance(PipeEnrichedInsertNode.class); + private final InsertNode insertNode; public PipeEnrichedInsertNode(final InsertNode insertNode) { @@ -72,6 +76,11 @@ public InsertNode getInsertNode() { return insertNode; } + @Override + public long getMemorySize() { + return insertNode.getMemorySize() + INSTANCE_SIZE; + } + @Override public boolean isGeneratedByPipe() { return insertNode.isGeneratedByPipe(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertNode.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertNode.java index 0f2bc190120f2..31ed03cbf7dc5 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertNode.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertNode.java @@ -565,6 +565,15 @@ public long getMemorySize() { return memorySize; } + /** + * IoTConsensus applies inserts under its per-region state machine lock. Deferring replication + * serialization lets encoding run after that lock has been released. + */ + @Override + public boolean isSerializationDeferred() { + return true; + } + public abstract void checkDataType(AbstractMemTable memTable) throws DataTypeInconsistentException; } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/pipe/PipeEnrichedInsertNodeSerdeTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/pipe/PipeEnrichedInsertNodeSerdeTest.java index 827621087d97f..306975b55c3d9 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/pipe/PipeEnrichedInsertNodeSerdeTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/pipe/PipeEnrichedInsertNodeSerdeTest.java @@ -33,6 +33,17 @@ import java.nio.ByteBuffer; public class PipeEnrichedInsertNodeSerdeTest { + + // Deferred replication of a pipe-enriched insert must reserve the wrapped insert and wrapper. + @Test + public void testDeferredRequestKeepsWrappedInsertMemoryEstimate() throws IllegalPathException { + InsertRowNode insertRowNode = getInsertRowNode(); + PipeEnrichedInsertNode pipeEnrichedInsertNode = new PipeEnrichedInsertNode(insertRowNode); + + Assert.assertTrue(pipeEnrichedInsertNode.isSerializationDeferred()); + Assert.assertTrue(pipeEnrichedInsertNode.getMemorySize() > insertRowNode.getMemorySize()); + } + @Test public void testSerializeAndDeserialize() throws IllegalPathException { InsertRowNode insertRowNode = getInsertRowNode(); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/write/InsertRowNodeSerdeTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/write/InsertRowNodeSerdeTest.java index 5a5f2d9d35d8c..1c6ebcb079fe4 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/write/InsertRowNodeSerdeTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/node/write/InsertRowNodeSerdeTest.java @@ -24,6 +24,7 @@ import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType; import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory; +import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest; import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowNode; import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.RelationalInsertRowNode; import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALByteBufferForTest; @@ -39,9 +40,36 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.Collections; public class InsertRowNodeSerdeTest { + // Type inference after queue creation must be reflected when IoTConsensus later serializes it. + @Test + public void testInsertRequestSerializationIsDeferred() throws IllegalPathException { + InsertRowNode insertRowNode = getInsertRowNodeWithStringValue(); + IndexedConsensusRequest request = + new IndexedConsensusRequest(1L, 1L, Collections.singletonList(insertRowNode)); + + Assert.assertTrue(request.hasDeferredRequests()); + Assert.assertTrue(request.getSerializedRequests().isEmpty()); + + insertRowNode.setDataTypes( + new TSDataType[] { + TSDataType.DOUBLE, + TSDataType.FLOAT, + TSDataType.INT64, + TSDataType.INT32, + TSDataType.BOOLEAN, + }); + insertRowNode.setValues(new Object[] {1.0, 2.0f, 10000L, 100, false}); + insertRowNode.setNeedInferType(false); + request.buildSerializedRequests(); + + Assert.assertEquals( + insertRowNode, PlanNodeType.deserialize(request.getSerializedRequests().get(0))); + } + @Test public void testSerializeAndDeserialize() throws IllegalPathException { InsertRowNode insertRowNode = getInsertRowNode(); diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/request/IConsensusRequest.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/request/IConsensusRequest.java index 490c88f2b3f32..e3145f63f57f6 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/request/IConsensusRequest.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/request/IConsensusRequest.java @@ -53,10 +53,10 @@ default boolean isForwardable() { * Returns whether this request materializes its bytes only when it is about to be sent, instead * of when it is handed over to the replication layer. * - *

A deferred request keeps just its source objects while it waits in the replication queues, - * so it must be able to rebuild the very same bytes on demand and must stay small. Consensus - * implementations may postpone {@link #serializeToByteBuffer()} for such requests and keep the - * source objects alive until then. + *

A deferred request keeps its source objects while it waits in the replication queues, so + * {@link #getMemorySize()} must account for them and the request must be able to rebuild the same + * bytes on demand. Consensus implementations may postpone {@link #serializeToByteBuffer()} for + * such requests and keep the source objects alive until then. */ default boolean isSerializationDeferred() { return false;