diff --git a/downstreamadapter/dispatcher/basic_dispatcher_info.go b/downstreamadapter/dispatcher/basic_dispatcher_info.go index 23b41e0f2a..7a899dbd14 100644 --- a/downstreamadapter/dispatcher/basic_dispatcher_info.go +++ b/downstreamadapter/dispatcher/basic_dispatcher_info.go @@ -241,6 +241,14 @@ func (d *BasicDispatcher) offerBlockStatus(status *heartbeatpb.TableSpanBlockSta d.sharedInfo.OfferBlockStatus(status) } +func (d *BasicDispatcher) offerRetryBlockStatus(status *heartbeatpb.TableSpanBlockStatus, canceled <-chan struct{}) bool { + return d.sharedInfo.blockStatusBuffer.offerRetryStatus(status, canceled) +} + +func (d *BasicDispatcher) cancelRetryBlockStatus(status *heartbeatpb.TableSpanBlockStatus) { + d.sharedInfo.blockStatusBuffer.cancelRetryStatus(status) +} + // offerDoneBlockStatus keeps DONE on the dedicated minimal-key path so // duplicate completions are filtered before another protobuf allocation. func (d *BasicDispatcher) offerDoneBlockStatus(blockTs uint64, isSyncPoint bool) { @@ -330,6 +338,7 @@ func (s *SharedInfo) Close() { if s.blockExecutor != nil { s.blockExecutor.Close() } + s.blockStatusBuffer.Close() keyspace := s.changefeedID.Keyspace() changefeedID := s.changefeedID.Name() metrics.HandleDDLHistogram.DeleteLabelValues(keyspace, changefeedID) diff --git a/downstreamadapter/dispatcher/block_status_buffer.go b/downstreamadapter/dispatcher/block_status_buffer.go index 54e3b400c8..20cdcaafec 100644 --- a/downstreamadapter/dispatcher/block_status_buffer.go +++ b/downstreamadapter/dispatcher/block_status_buffer.go @@ -14,6 +14,7 @@ package dispatcher import ( + "container/list" "context" "sync" @@ -39,6 +40,12 @@ type blockStatusQueueEntry struct { doneKey *blockStatusKey } +type retryBlockStatus struct { + status *heartbeatpb.TableSpanBlockStatus + canceled <-chan struct{} + element *list.Element +} + // BlockStatusBuffer keeps block statuses ordered while coalescing identical // pending WAITING and DONE statuses in dispatcher-local memory. // @@ -48,8 +55,15 @@ type blockStatusQueueEntry struct { type BlockStatusBuffer struct { queue chan blockStatusQueueEntry - mu sync.Mutex - pending map[blockStatusKey]struct{} + mu sync.Mutex + pending map[blockStatusKey]struct{} + retries *list.List + retryByStatus map[*heartbeatpb.TableSpanBlockStatus]*retryBlockStatus + retryWake chan struct{} + retryStop chan struct{} + retryDone chan struct{} + retrySending bool + closed bool } // NewBlockStatusBuffer creates a bounded local mailbox for dispatcher block @@ -59,8 +73,12 @@ func NewBlockStatusBuffer(size int) *BlockStatusBuffer { size = 1 } return &BlockStatusBuffer{ - queue: make(chan blockStatusQueueEntry, size), - pending: make(map[blockStatusKey]struct{}), + queue: make(chan blockStatusQueueEntry, size), + pending: make(map[blockStatusKey]struct{}), + retries: list.New(), + retryByStatus: make(map[*heartbeatpb.TableSpanBlockStatus]*retryBlockStatus), + retryWake: make(chan struct{}, 1), + retryStop: make(chan struct{}), } } @@ -86,6 +104,142 @@ func (b *BlockStatusBuffer) OfferStatus(status *heartbeatpb.TableSpanBlockStatus b.queue <- blockStatusQueueEntry{status: status} } +// offerRetryStatus queues a full-buffer retry for one dedicated sender instead +// of blocking a shared pool worker. The sender joins the original channel's +// send queue, so new status producers cannot repeatedly overtake the retry. +func (b *BlockStatusBuffer) offerRetryStatus(status *heartbeatpb.TableSpanBlockStatus, canceled <-chan struct{}) bool { + if status == nil { + return true + } + + b.mu.Lock() + defer b.mu.Unlock() + select { + case <-canceled: + return false + default: + } + if b.closed { + return false + } + if _, ok := b.retryByStatus[status]; ok { + return false + } + + if isWaitingBlockStatus(status) { + key := newBlockStatusKey(status) + if _, ok := b.pending[key]; ok { + return true + } + } + + if !b.retrySending && b.retries.Len() == 0 { + select { + case b.queue <- blockStatusQueueEntry{status: status}: + if isWaitingBlockStatus(status) { + b.pending[newBlockStatusKey(status)] = struct{}{} + } + return true + default: + } + } + + if isWaitingBlockStatus(status) { + b.pending[newBlockStatusKey(status)] = struct{}{} + } + retry := &retryBlockStatus{status: status, canceled: canceled} + retry.element = b.retries.PushBack(retry) + b.retryByStatus[status] = retry + if b.retryDone == nil { + b.retryDone = make(chan struct{}) + go b.sendRetries() + } + select { + case b.retryWake <- struct{}{}: + default: + } + return false +} + +func (b *BlockStatusBuffer) sendRetries() { + defer close(b.retryDone) + for { + b.mu.Lock() + if b.closed { + b.mu.Unlock() + return + } + front := b.retries.Front() + if front == nil { + b.mu.Unlock() + select { + case <-b.retryWake: + case <-b.retryStop: + return + } + continue + } + retry := front.Value.(*retryBlockStatus) + b.retries.Remove(front) + retry.element = nil + b.retrySending = true + b.mu.Unlock() + + sent := false + select { + case <-retry.canceled: + case <-b.retryStop: + return + default: + select { + case b.queue <- blockStatusQueueEntry{status: retry.status}: + sent = true + case <-retry.canceled: + case <-b.retryStop: + return + } + } + + b.mu.Lock() + delete(b.retryByStatus, retry.status) + b.retrySending = false + if !sent && isWaitingBlockStatus(retry.status) { + delete(b.pending, newBlockStatusKey(retry.status)) + } + b.mu.Unlock() + } +} + +func (b *BlockStatusBuffer) cancelRetryStatus(status *heartbeatpb.TableSpanBlockStatus) { + b.mu.Lock() + defer b.mu.Unlock() + retry := b.retryByStatus[status] + if retry == nil || retry.element == nil { + return + } + b.retries.Remove(retry.element) + delete(b.retryByStatus, status) + if isWaitingBlockStatus(status) { + delete(b.pending, newBlockStatusKey(status)) + } +} + +// Close stops the dedicated retry sender when its dispatcher manager closes. +func (b *BlockStatusBuffer) Close() { + b.mu.Lock() + if b.closed { + b.mu.Unlock() + return + } + b.closed = true + close(b.retryStop) + done := b.retryDone + b.mu.Unlock() + if done != nil { + <-done + } +} + // OfferDone enqueues a DONE status via the dedicated minimal-key path. Duplicate // DONE statuses are suppressed before protobuf allocation. func (b *BlockStatusBuffer) OfferDone( diff --git a/downstreamadapter/dispatcher/block_status_buffer_test.go b/downstreamadapter/dispatcher/block_status_buffer_test.go index 9bf6291561..3beaf2b24e 100644 --- a/downstreamadapter/dispatcher/block_status_buffer_test.go +++ b/downstreamadapter/dispatcher/block_status_buffer_test.go @@ -23,6 +23,7 @@ import ( commonEvent "github.com/pingcap/ticdc/pkg/common/event" "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/routing" + "github.com/pingcap/ticdc/utils/threadpool" "github.com/pingcap/tidb/pkg/meta/model" "github.com/stretchr/testify/require" ) @@ -96,6 +97,192 @@ func TestBlockStatusBufferAllowsWaitingAgainAfterTake(t *testing.T) { requireNoBlockStatus(t, buffer) } +func TestBlockStatusBufferRetryWhenFull(t *testing.T) { + buffer := NewBlockStatusBuffer(1) + defer buffer.Close() + dispatcherID := common.NewDispatcherID() + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 100, common.DefaultMode)) + retry := newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode) + + require.False(t, buffer.offerRetryStatus(retry, nil)) + require.False(t, buffer.offerRetryStatus(retry, nil)) + require.True(t, buffer.offerRetryStatus(newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode), nil)) + nextRetry := newTestWaitingBlockStatus(dispatcherID, 250, common.DefaultMode) + require.False(t, buffer.offerRetryStatus(nextRetry, nil)) + require.Equal(t, 1, buffer.Len()) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + first := buffer.Take(ctx) + require.NotNil(t, first) + require.Equal(t, uint64(100), first.State.BlockTs) + + second := buffer.Take(ctx) + require.NotNil(t, second) + require.Same(t, retry, second) + require.Same(t, nextRetry, buffer.Take(ctx)) + requireNoBlockStatus(t, buffer) + + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 300, common.DefaultMode)) + none := &heartbeatpb.TableSpanBlockStatus{ + ID: dispatcherID.ToPB(), + State: &heartbeatpb.State{BlockTs: 400, Stage: heartbeatpb.BlockStage_NONE}, + Mode: common.DefaultMode, + } + require.False(t, buffer.offerRetryStatus(none, nil)) + require.NotNil(t, buffer.Take(ctx)) + third := buffer.Take(ctx) + require.NotNil(t, third) + require.Same(t, none, third) +} + +func TestResendTaskDoesNotBlockWorkerWhenBufferFull(t *testing.T) { + buffer := NewBlockStatusBuffer(1) + defer buffer.Close() + dispatcherID := common.NewDispatcherID() + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 100, common.DefaultMode)) + dispatcher := &BasicDispatcher{ + id: dispatcherID, + sharedInfo: &SharedInfo{blockStatusBuffer: buffer}, + } + retry := newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode) + task := &ResendTask{dispatcher: dispatcher, message: retry, canceled: make(chan struct{})} + pool := threadpool.NewThreadPool(1) + defer func() { + // Drain the buffer before Stop so a blocked worker cannot leak if this + // regression fails. + buffer.TryTake() + pool.Stop() + }() + + started := make(chan struct{}) + handle := pool.SubmitFunc(func() time.Time { + close(started) + task.Execute() + return time.Time{} + }, time.Now()) + <-started + handle.Cancel() + workerAvailable := make(chan struct{}) + pool.SubmitFunc(func() time.Time { + close(workerAvailable) + return time.Time{} + }, time.Now()) + select { + case <-workerAvailable: + case <-time.After(time.Second): + require.FailNow(t, "full block status buffer held the resend worker") + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + require.NotNil(t, buffer.Take(ctx)) + status := buffer.Take(ctx) + require.NotNil(t, status) + require.Same(t, retry, status) +} + +func TestIgnoredBlockStatusRetryWhenBufferFull(t *testing.T) { + buffer := NewBlockStatusBuffer(1) + defer buffer.Close() + dispatcherID := common.NewDispatcherID() + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 100, common.DefaultMode)) + retry := newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode) + dispatcher := &BasicDispatcher{ + id: dispatcherID, + sharedInfo: &SharedInfo{blockStatusBuffer: buffer}, + resendTaskMap: newResendTaskMap(), + } + dispatcher.blockEventStatus.setBlockEvent(&commonEvent.DDLEvent{FinishedTs: 200}, heartbeatpb.BlockStage_WAITING) + task := &ResendTask{dispatcher: dispatcher, message: retry, canceled: make(chan struct{})} + dispatcher.resendTaskMap.Set(BlockEventIdentifier{CommitTs: 200}, task) + defer task.Cancel() + + require.False(t, dispatcher.HandleDispatcherStatus(&heartbeatpb.DispatcherStatus{ + IgnoredBlockStatus: &heartbeatpb.IgnoredBlockStatus{CommitTs: 200}, + })) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + require.NotNil(t, buffer.Take(ctx)) + require.Same(t, retry, buffer.Take(ctx)) +} + +func TestBlockStatusBufferRetryProgressWithWaitingProducers(t *testing.T) { + buffer := NewBlockStatusBuffer(1) + defer buffer.Close() + dispatcherID := common.NewDispatcherID() + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 100, common.DefaultMode)) + retry := newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode) + require.False(t, buffer.offerRetryStatus(retry, nil)) + + producerDone := make(chan struct{}) + go func() { + defer close(producerDone) + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 300, common.DefaultMode)) + }() + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + seenRetry := false + for range 3 { + status := buffer.Take(ctx) + require.NotNil(t, status) + if status == retry { + seenRetry = true + } + } + require.True(t, seenRetry) + <-producerDone +} + +func TestBlockStatusBufferCancelsPendingRetry(t *testing.T) { + buffer := NewBlockStatusBuffer(1) + defer buffer.Close() + dispatcherID := common.NewDispatcherID() + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 100, common.DefaultMode)) + retry := newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode) + dispatcher := &BasicDispatcher{ + id: dispatcherID, + sharedInfo: &SharedInfo{blockStatusBuffer: buffer}, + } + task := &ResendTask{dispatcher: dispatcher, message: retry, canceled: make(chan struct{})} + task.Execute() + nextRetry := newTestWaitingBlockStatus(dispatcherID, 300, common.DefaultMode) + require.False(t, buffer.offerRetryStatus(nextRetry, nil)) + task.Cancel() + + require.Eventually(t, func() bool { + buffer.mu.Lock() + defer buffer.mu.Unlock() + _, ok := buffer.retryByStatus[retry] + return !ok + }, time.Second, time.Millisecond) + _, ok := buffer.TryTake() + require.True(t, ok) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + require.Same(t, nextRetry, buffer.Take(ctx)) + requireNoBlockStatus(t, buffer) +} + +func TestBlockStatusBufferCloseUnblocksRetrySender(t *testing.T) { + buffer := NewBlockStatusBuffer(1) + dispatcherID := common.NewDispatcherID() + buffer.OfferStatus(newTestWaitingBlockStatus(dispatcherID, 100, common.DefaultMode)) + retry := newTestWaitingBlockStatus(dispatcherID, 200, common.DefaultMode) + require.False(t, buffer.offerRetryStatus(retry, nil)) + + closed := make(chan struct{}) + go func() { + buffer.Close() + close(closed) + }() + select { + case <-closed: + case <-time.After(time.Second): + require.FailNow(t, "retry sender did not stop with the buffer") + } +} + func TestBlockStatusBufferAllowsDoneAgainAfterTake(t *testing.T) { buffer := NewBlockStatusBuffer(4) dispatcherID := common.NewDispatcherID() diff --git a/downstreamadapter/dispatcher/helper.go b/downstreamadapter/dispatcher/helper.go index 94fea8a5a3..40211f5222 100644 --- a/downstreamadapter/dispatcher/helper.go +++ b/downstreamadapter/dispatcher/helper.go @@ -340,7 +340,8 @@ type HeartBeatInfo struct { // Keeping it narrow avoids reintroducing a broader unified block-status API. type blockStatusOfferer interface { GetId() common.DispatcherID - offerBlockStatus(status *heartbeatpb.TableSpanBlockStatus) + offerRetryBlockStatus(status *heartbeatpb.TableSpanBlockStatus, canceled <-chan struct{}) bool + cancelRetryBlockStatus(status *heartbeatpb.TableSpanBlockStatus) } // ResendTask is responsible for periodically resending the block status to the maintainer. @@ -351,6 +352,8 @@ type ResendTask struct { callback func() // function need to be called when the task is cancelled taskHandle *threadpool.TaskHandle executeCount uint64 + canceled chan struct{} + cancelOnce sync.Once } const resendTimeInterval = 5 * time.Second @@ -363,6 +366,7 @@ func newResendTask(dispatcher blockStatusOfferer, message *heartbeatpb.TableSpan dispatcher: dispatcher, message: message, callback: callback, + canceled: make(chan struct{}), } t.taskHandle = taskScheduler.Submit(t, time.Now().Add(resendTimeInterval)) return t @@ -372,7 +376,9 @@ func newResendTask(dispatcher blockStatusOfferer, message *heartbeatpb.TableSpan // WAITING/NONE retries stay allocation-light and byte-for-byte consistent. func (t *ResendTask) Execute() time.Time { log.Debug("resend task", zap.Any("dispatcherID", t.dispatcher.GetId())) - t.dispatcher.offerBlockStatus(t.message) + if !t.dispatcher.offerRetryBlockStatus(t.message, t.canceled) { + return time.Now().Add(resendTimeInterval) + } executeCount := atomic.AddUint64(&t.executeCount, 1) if executeCount%10 == 0 { @@ -385,10 +391,18 @@ func (t *ResendTask) Execute() time.Time { // Cancel stops future retries and runs the optional completion callback once. func (t *ResendTask) Cancel() { - if t.callback != nil { - t.callback() - } - t.taskHandle.Cancel() + t.cancelOnce.Do(func() { + if t.canceled != nil { + close(t.canceled) + } + t.dispatcher.cancelRetryBlockStatus(t.message) + if t.callback != nil { + t.callback() + } + if t.taskHandle != nil { + t.taskHandle.Cancel() + } + }) } var ( diff --git a/maintainer/barrier_test.go b/maintainer/barrier_test.go index 2cbd0516f1..9cce89dfcd 100644 --- a/maintainer/barrier_test.go +++ b/maintainer/barrier_test.go @@ -2215,3 +2215,68 @@ func TestBarrierReturnsTemporaryIgnoreForUnreplicatingWaitingStatus(t *testing.T require.Equal(t, 0, barrier.blockedEvents.Len()) require.Nil(t, stm.GetBlockState()) } + +func TestDBBarrierRecoversIgnoredWaitingStatusAfterDispatcherMove(t *testing.T) { + testutil.SetUpTestServices(t) + + ddlDispatcherID := common.NewDispatcherID() + cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + ddlSpan := replica.NewWorkingSpanReplication(cfID, ddlDispatcherID, + common.DDLSpanSchemaID, + common.KeyspaceDDLSpan(common.DefaultKeyspaceID), &heartbeatpb.TableSpanStatus{ + ID: ddlDispatcherID.ToPB(), + ComponentStatus: heartbeatpb.ComponentState_Working, + CheckpointTs: 1, + }, "node1", false) + spanController := span.NewController(cfID, ddlSpan, nil, nil, nil, common.DefaultKeyspaceID, common.DefaultMode) + operatorController := operator.NewOperatorController(cfID, spanController, 1000, common.DefaultMode) + spanController.AddNewTable(commonEvent.Table{SchemaID: 1, TableID: 1}, 1) + tableDispatcher := spanController.GetTasksByTableID(1)[0] + spanController.BindSpanToNode("", "node1", tableDispatcher) + require.False(t, spanController.IsReplicating(tableDispatcher)) + + barrier := NewBarrier(spanController, operatorController, false, nil, common.DefaultMode, nil) + blockState := &heartbeatpb.State{ + IsBlocked: true, + BlockTs: 10, + Stage: heartbeatpb.BlockStage_WAITING, + BlockTables: &heartbeatpb.InfluencedTables{ + InfluenceType: heartbeatpb.InfluenceType_DB, + SchemaID: 1, + }, + } + msgs := barrier.HandleStatus("node1", &heartbeatpb.BlockStatusRequest{ + ChangefeedID: cfID.ToPB(), + BlockStatuses: []*heartbeatpb.TableSpanBlockStatus{ + {ID: ddlDispatcherID.ToPB(), State: blockState}, + {ID: tableDispatcher.ID.ToPB(), State: blockState}, + }, + }) + require.Len(t, msgs, 1) + resp := msgs[0].Message[0].(*heartbeatpb.HeartBeatResponse) + require.Len(t, resp.DispatcherStatuses, 2) + require.Equal(t, uint64(10), resp.DispatcherStatuses[0].IgnoredBlockStatus.CommitTs) + require.Nil(t, resp.DispatcherStatuses[0].Ack) + event := barrier.blockedEvents.m[getEventKey(10, false)] + require.NotNil(t, event) + require.False(t, event.selected.Load()) + require.NotContains(t, event.reportedDispatchers, tableDispatcher.ID) + + spanController.MarkSpanReplicating(tableDispatcher) + event.lastResendTime = time.Now().Add(-2 * time.Second) + require.Empty(t, barrier.Resend()) + require.False(t, event.selected.Load()) + + msgs = barrier.HandleStatus("node1", &heartbeatpb.BlockStatusRequest{ + ChangefeedID: cfID.ToPB(), + BlockStatuses: []*heartbeatpb.TableSpanBlockStatus{ + {ID: tableDispatcher.ID.ToPB(), State: blockState}, + }, + }) + require.True(t, event.selected.Load()) + require.Equal(t, ddlDispatcherID, event.writerDispatcher) + require.Len(t, msgs, 1) + resp = msgs[0].Message[0].(*heartbeatpb.HeartBeatResponse) + require.Len(t, resp.DispatcherStatuses, 2) + require.Equal(t, heartbeatpb.Action_Write, resp.DispatcherStatuses[1].Action.Action) +}