Repository navigation
Defer IoTConsensus insert serialization until after local apply #19432
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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(); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The local apply is complete and stateMachineLock has been released before the writer-thread fallback materializes bytes. The synchronous call also ensures the caller cannot reuse the plan node first. |
||
| } | ||
| if (recordConsensusWriteTime) { | ||
| ioTConsensusServerMetrics.recordConsensusWriteTime( | ||
| System.nanoTime() - consensusWriteStartTime); | ||
| } | ||
| } finally { | ||
| persistLatestWriterMeta(false); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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(); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Deferred requests skip eager encoding here. When subscription delivery did not retain the source node, this flag releases it as soon as serialization produces the replication buffer. |
||
| } | ||
| 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) { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When no peer queue accepts the entry, no batch will materialize its deferred bytes. Releasing the source here avoids retaining it while the dispatcher fills the index gap from WAL. |
||
| request.clearRequests(); | ||
| } | ||
| } else if (!keepRequestsForSubscription) { | ||
| // A single-replica region has no dispatcher thread, but still does not need the raw request | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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() { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test covers deferred cleanup after bytes are built and verifies source release, retained buffer availability, and stable queue-reservation accounting. |
||
| 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); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This regression test verifies the write-thread serialization happens after it releases stateMachineLock and that an accepted subscription retains both the source request and encoded bytes. |
||
| 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<IndexedConsensusRequest> 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<Peer> 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; | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The queued request is the pipe wrapper, so the estimate includes both the wrapped insert payload and the wrapper instance rather than undercounting replication queue memory. |
||
| } | ||
|
|
||
| @Override | ||
| public boolean isGeneratedByPipe() { | ||
| return insertNode.isGeneratedByPipe(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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() { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Insert plan nodes opt into deferred replication encoding so their serialized form can reflect the node after local type inference and application. |
||
| return true; | ||
| } | ||
|
|
||
| public abstract void checkDataType(AbstractMemTable memTable) | ||
| throws DataTypeInconsistentException; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test protects the pipe wrapper contract by checking that it inherits deferred serialization and accounts for its own instance memory. |
||
| 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(); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This lifecycle hook lets replication-only requests release source plan nodes once serialized buffers are available, while keeping those buffers for retries and preserving the original queue reservation.