Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions downstreamadapter/dispatcher/basic_dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,13 +517,20 @@ func (d *BasicDispatcher) GetLastSyncedTs() uint64 {
}

func (d *BasicDispatcher) GetCheckpointTs() uint64 {
// Event handling adds DML to tableProgress before advancing resolvedTs.
// Read resolvedTs first so an empty progress list cannot be combined with
// a newer resolvedTs that includes DML added after the progress read.
resolvedTs := d.GetResolvedTs()
checkpointTs, isEmpty := d.tableProgress.GetCheckpointTs()
failpoint.Inject("afterReadTableProgress", func() {
failpoint.Call("github.com/pingcap/ticdc/downstreamadapter/dispatcher/afterReadTableProgress", d)
})
if checkpointTs == 0 {
// This means the dispatcher has never send events to the sink,
// so we use resolvedTs as checkpointTs
checkpointTs = d.GetResolvedTs()
checkpointTs = resolvedTs
} else if isEmpty {
checkpointTs = max(checkpointTs, d.GetResolvedTs())
checkpointTs = max(checkpointTs, resolvedTs)
}

if d.addTableCheckpointBlocker != nil {
Expand Down
38 changes: 38 additions & 0 deletions downstreamadapter/dispatcher/basic_dispatcher_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,47 @@ package dispatcher
import (
"testing"

"github.com/pingcap/failpoint"
commonEvent "github.com/pingcap/ticdc/pkg/common/event"
"github.com/stretchr/testify/require"
)

func TestCheckpointTsDoesNotCombineOldProgressAndNewResolved(t *testing.T) {
for _, name := range []string{"noPreviousDML", "previousDMLFlushed"} {
t.Run(name, func(t *testing.T) {
d := &BasicDispatcher{tableProgress: NewTableProgress()}
d.resolvedTs.Store(100)
if name == "previousDMLFlushed" {
previous := &commonEvent.DMLEvent{StartTs: 80, CommitTs: 100}
d.tableProgress.Add(previous)
previous.PostFlush()
}
pending := &commonEvent.DMLEvent{StartTs: 90, CommitTs: 101}
injected := false
const point = "github.com/pingcap/ticdc/downstreamadapter/dispatcher/afterReadTableProgress"
require.NoError(t, failpoint.EnableCall(point, func(observed *BasicDispatcher) {
if observed != d {
return
}
injected = true
// Model an event handler enqueueing DML and then publishing resolved ts
// after the checkpoint reader has observed an empty progress list.
d.tableProgress.Add(pending)
d.resolvedTs.Store(800)
}))
t.Cleanup(func() { require.NoError(t, failpoint.Disable(point)) })
checkpoint := d.GetCheckpointTs()
if !injected {
t.Skip("requires failpoint instrumentation")
}
require.Equal(t, uint64(100), checkpoint)
require.NoError(t, failpoint.Disable(point))
pending.PostFlush()
require.Equal(t, uint64(800), d.GetCheckpointTs())
})
}
}

func TestBasicDispatcherStartTsConcurrentAccess(t *testing.T) {
d := &BasicDispatcher{}
const finalStartTs uint64 = 1000
Expand Down
85 changes: 32 additions & 53 deletions downstreamadapter/dispatchermanager/dispatcher_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package dispatchermanager

import (
"context"
"fmt"
"math"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -137,6 +138,9 @@ type DispatcherManager struct {
// heartBeatTask is responsible for collecting the heartbeat info from all the dispatchers
// and report to the maintainer periodicity.
heartBeatTask *HeartBeatTask
// heartbeatMu serializes periodic scans through final-watermark publication
// and map cleanup. Retired dispatchers stay covered until the next scan.
heartbeatMu sync.Mutex

// blockStatusRequestQueue is used to store the block status request from all the dispatchers.
// heartbeat collector will consume the block status request from the queue and report to the maintainer.
Expand Down Expand Up @@ -659,6 +663,8 @@ func (e *DispatcherManager) newEventDispatchers(infos map[common.DispatcherID]di
d.Remove()
return newWritePathClosedError()
}
// Register progress and its generation before event delivery can report Working.
e.dispatcherMap.Set(id, d)
if d.IsTableTriggerDispatcher() {
if util.GetOrZero(e.config.SinkConfig.SendAllBootstrapAtStart) {
d.BootstrapState = dispatcher.BootstrapNotStarted
Expand All @@ -669,11 +675,12 @@ func (e *DispatcherManager) newEventDispatchers(infos map[common.DispatcherID]di
// we don't register table trigger event dispatcher in event collector, when created.
// Table trigger event dispatcher is a special dispatcher,
// it need to wait get the initial table schema store from the maintainer, then will register to event collector to receive events.
failpoint.Inject("beforeRegisterDispatcher", func() {
failpoint.Call("github.com/pingcap/ticdc/downstreamadapter/dispatchermanager/beforeRegisterDispatcher", d)
})
appcontext.GetService[*eventcollector.EventCollector](appcontext.EventCollector).AddDispatcher(d, e.sinkQuota)
}

seq := e.dispatcherMap.Set(id, d)
d.SetSeq(seq)
e.writePathMu.Unlock()

if d.IsTableTriggerDispatcher() {
Expand Down Expand Up @@ -835,47 +842,16 @@ func (e *DispatcherManager) collectComponentStatusWhenChanged(ctx context.Contex
defer delay.Stop()
for {
statusMessage := make([]*heartbeatpb.TableSpanStatus, 0)
// why we need compare with latest watermark? for not backward the watermark?
watermark := e.latestWatermark.Get()
newWatermark := &heartbeatpb.Watermark{
CheckpointTs: watermark.CheckpointTs,
ResolvedTs: watermark.ResolvedTs,
Seq: watermark.Seq,
}
redoWatermark := e.latestRedoWatermark.Get()
newRedoWatermark := &heartbeatpb.Watermark{
CheckpointTs: redoWatermark.CheckpointTs,
ResolvedTs: redoWatermark.ResolvedTs,
Seq: redoWatermark.Seq,
}
var seq, redoSeq uint64
select {
case <-ctx.Done():
return
case tableSpanStatus := <-e.sharedInfo.GetStatusesChan():
statusMessage = append(statusMessage, tableSpanStatus.TableSpanStatus)
if common.IsDefaultMode(tableSpanStatus.Mode) {
// Note: tableSpanStatus.Seq is the seq assigned when that dispatcher was created.
// status messages can arrive out-of-order and Seq has no ordering relationship with
// per-dispatcher checkpoint/resolved ts.
//
// - Keep Watermark.Seq monotonic to avoid maintainer dropping the watermark as stale
// while still applying status updates (statuses are handled regardless of watermark Seq).
// - Still update CheckpointTs with min() regardless of Seq ordering; the periodic
// aggregateDispatcherHeartbeats() is responsible for advancing the watermark.
if newWatermark.Seq < tableSpanStatus.Seq {
newWatermark.Seq = tableSpanStatus.Seq
}
if tableSpanStatus.CheckpointTs != 0 && tableSpanStatus.CheckpointTs < newWatermark.CheckpointTs {
newWatermark.CheckpointTs = tableSpanStatus.CheckpointTs
}
seq = tableSpanStatus.Seq
} else {
// Same rule applies to redo watermark.
if newRedoWatermark.Seq < tableSpanStatus.Seq {
newRedoWatermark.Seq = tableSpanStatus.Seq
}
if tableSpanStatus.CheckpointTs != 0 && tableSpanStatus.CheckpointTs < newRedoWatermark.CheckpointTs {
newRedoWatermark.CheckpointTs = tableSpanStatus.CheckpointTs
}
redoSeq = tableSpanStatus.Seq
}
delay.Reset(10 * time.Millisecond)
loop:
Expand All @@ -884,19 +860,9 @@ func (e *DispatcherManager) collectComponentStatusWhenChanged(ctx context.Contex
case tableSpanStatus := <-e.sharedInfo.GetStatusesChan():
statusMessage = append(statusMessage, tableSpanStatus.TableSpanStatus)
if common.IsDefaultMode(tableSpanStatus.Mode) {
if newWatermark.Seq < tableSpanStatus.Seq {
newWatermark.Seq = tableSpanStatus.Seq
}
if tableSpanStatus.CheckpointTs != 0 && tableSpanStatus.CheckpointTs < newWatermark.CheckpointTs {
newWatermark.CheckpointTs = tableSpanStatus.CheckpointTs
}
seq = max(seq, tableSpanStatus.Seq)
} else {
if newRedoWatermark.Seq < tableSpanStatus.Seq {
newRedoWatermark.Seq = tableSpanStatus.Seq
}
if tableSpanStatus.CheckpointTs != 0 && tableSpanStatus.CheckpointTs < newRedoWatermark.CheckpointTs {
newRedoWatermark.CheckpointTs = tableSpanStatus.CheckpointTs
}
redoSeq = max(redoSeq, tableSpanStatus.Seq)
}
case <-delay.C:
break loop
Expand All @@ -905,8 +871,15 @@ func (e *DispatcherManager) collectComponentStatusWhenChanged(ctx context.Contex
var message heartbeatpb.HeartBeatRequest
message.ChangefeedID = e.changefeedID.ToPB()
message.Statuses = statusMessage
message.Watermark = newWatermark
message.RedoWatermark = newRedoWatermark
// Read the aggregate after collecting statuses. Its generation must cover
// all new dispatchers before their Working statuses can finish operators.
message.Watermark = getStatusWatermark(&e.latestWatermark, e.dispatcherMap, seq)
message.RedoWatermark = getStatusWatermark(&e.latestRedoWatermark, e.redoDispatcherMap, redoSeq)
if message.Watermark == nil || message.RedoWatermark == nil {
e.handleError(ctx, errors.ErrInternalCheckFailed.GenWithStackByArgs(
fmt.Sprintf("dispatcher watermark generation gap: required=%d, redoRequired=%d", seq, redoSeq)))
return
}
e.heartbeatRequestQueue.Enqueue(&HeartBeatRequestWithTargetID{TargetID: e.GetMaintainerID(), Request: &message})
}
}
Expand All @@ -924,6 +897,8 @@ func (e *DispatcherManager) collectComponentStatusWhenChanged(ctx context.Contex
//
// Returns a HeartBeatRequest containing the aggregated information.
func (e *DispatcherManager) aggregateDispatcherHeartbeats(needCompleteStatus bool) *heartbeatpb.HeartBeatRequest {
e.heartbeatMu.Lock()
defer e.heartbeatMu.Unlock()
message := heartbeatpb.HeartBeatRequest{
ChangefeedID: e.changefeedID.ToPB(),
CompeleteStatus: needCompleteStatus,
Expand All @@ -935,6 +910,7 @@ func (e *DispatcherManager) aggregateDispatcherHeartbeats(needCompleteStatus boo
dispatcherCount := 0

if e.IsRedoReady() {
e.redoDispatcherMap.beginWatermarkScan(&e.latestRedoWatermark)
redoSeq := e.redoDispatcherMap.ForEach(func(id common.DispatcherID, dispatcherItem *dispatcher.RedoDispatcher) {
dispatcherCount++
status, cleanMap, watermark := getDispatcherStatus(id, dispatcherItem, needCompleteStatus)
Expand All @@ -949,9 +925,10 @@ func (e *DispatcherManager) aggregateDispatcherHeartbeats(needCompleteStatus boo
}
})
message.RedoWatermark.Seq = redoSeq
e.latestRedoWatermark.Set(message.RedoWatermark)
message.RedoWatermark = e.redoDispatcherMap.finishWatermarkScan(&e.latestRedoWatermark, message.RedoWatermark)
}

e.dispatcherMap.beginWatermarkScan(&e.latestWatermark)
seq := e.dispatcherMap.ForEach(func(id common.DispatcherID, dispatcherItem *dispatcher.EventDispatcher) {
dispatcherCount++
status, cleanMap, watermark := getDispatcherStatus(id, dispatcherItem, needCompleteStatus)
Expand All @@ -967,9 +944,11 @@ func (e *DispatcherManager) aggregateDispatcherHeartbeats(needCompleteStatus boo
})

message.Watermark.Seq = seq
e.latestWatermark.Set(message.Watermark)
message.Watermark = e.dispatcherMap.finishWatermarkScan(&e.latestWatermark, message.Watermark)

// if the event dispatcher manager is closing, we don't to remove the stopped dispatchers.
// Publish final watermarks before deleting stopped dispatchers. The serialized
// next scan can then exclude them and release their cached progress bounds.
// If the event dispatcher manager is closing, keep the stopped dispatchers.
if !e.closing.Load() {
for _, m := range toCleanMap {
dispatcherCount--
Expand Down
33 changes: 22 additions & 11 deletions downstreamadapter/dispatchermanager/dispatcher_manager_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,34 @@ import (

func getDispatcherStatus(id common.DispatcherID, dispatcherItem dispatcher.Dispatcher, needCompleteStatus bool) (*heartbeatpb.TableSpanStatus, *cleanMap, *heartbeatpb.Watermark) {
heartBeatInfo := &dispatcher.HeartBeatInfo{}
// the merged dispatcher in preparing state, don't need to join the calculation of the heartbeat
// the dispatcher still not know the startTs of it, and the dispatchers to be merged are still in the calculation of the checkpointTs
if dispatcherItem.GetComponentStatus() == heartbeatpb.ComponentState_Preparing || dispatcherItem.GetComponentStatus() == heartbeatpb.ComponentState_MergeReady {
return nil, nil, nil
}
dispatcherItem.GetHeartBeatInfo(heartBeatInfo)
provisional := heartBeatInfo.ComponentStatus == heartbeatpb.ComponentState_Preparing ||
heartBeatInfo.ComponentStatus == heartbeatpb.ComponentState_MergeReady
// If the dispatcher is in removing state, we need to check if it's closed successfully.
// If it's closed successfully, we could clean it up.
// TODO: we need to consider how to deal with the checkpointTs of the removed dispatcher if the message will be discarded.
if heartBeatInfo.IsRemoving {
watermark, ok := dispatcherItem.TryClose()
if ok {
nodeWatermark := &watermark
if provisional {
// An unactivated merge target has no final startTs. Its removal
// must still complete without contributing provisional progress.
nodeWatermark = nil
}
// If the dispatcher is removed successfully, we need to add the tableSpan into message whether needCompleteStatus is true or not.
return &heartbeatpb.TableSpanStatus{
ID: id.ToPB(),
ComponentStatus: heartbeatpb.ComponentState_Stopped,
CheckpointTs: watermark.CheckpointTs,
Mode: dispatcherItem.GetMode(),
}, &cleanMap{dispatcherItem.GetId(), dispatcherItem.GetSchemaID(), dispatcherItem.GetMode()}, &watermark
}, &cleanMap{dispatcherItem.GetId(), dispatcherItem.GetSchemaID(), dispatcherItem.GetMode()}, nodeWatermark
}
}
// The source dispatchers still constrain progress until the merge target is active.
if provisional {
return nil, nil, nil
}
if needCompleteStatus {
if dispatcherItem.GetComponentStatus() == heartbeatpb.ComponentState_Initializing {
log.Debug("dispatcher is initializing",
Expand Down Expand Up @@ -205,8 +212,7 @@ func registerMergeDispatcher[T dispatcher.Dispatcher](changefeedID common.Change
memQuota uint64,
) {
mergedDispatcher.SetComponentStatus(heartbeatpb.ComponentState_Preparing)
seq := dispatcherMap.Set(mergedDispatcherID, mergedDispatcher)
mergedDispatcher.SetSeq(seq)
dispatcherMap.Set(mergedDispatcherID, mergedDispatcher)
schemaIDToDispatchers.Set(mergedDispatcher.GetSchemaID(), mergedDispatcherID)
metricDispatcherCount.Inc()

Expand Down Expand Up @@ -238,9 +244,16 @@ func removeDispatcher[T dispatcher.Dispatcher](e *DispatcherManager,
changefeedID := e.changefeedID
statusesChan := e.sharedInfo.GetStatusesChan()

// Publish removal intent under the same lock used by merge activation.
e.writePathMu.Lock()
dispatcherItem, ok := dispatcherMap.Get(id)
alreadyRemoving := ok && dispatcherItem.GetTryRemoving()
if ok && !alreadyRemoving {
dispatcherItem.SetTryRemoving()
}
e.writePathMu.Unlock()
if ok {
if dispatcherItem.GetTryRemoving() {
if alreadyRemoving {
log.Info("dispatcher is already in removing state, skip repeated remove request",
zap.Stringer("changefeedID", changefeedID),
zap.Stringer("dispatcherID", id))
Expand All @@ -264,8 +277,6 @@ func removeDispatcher[T dispatcher.Dispatcher](e *DispatcherManager,

e.submitRemoveDispatcherTask(dispatcherItem)

dispatcherItem.SetTryRemoving()

log.Info("submitted async remove task",
zap.Stringer("changefeedID", changefeedID),
zap.Stringer("dispatcherID", id))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"math"
"time"

"github.com/pingcap/failpoint"
"github.com/pingcap/log"
"github.com/pingcap/ticdc/downstreamadapter/dispatcher"
"github.com/pingcap/ticdc/downstreamadapter/eventcollector"
Expand Down Expand Up @@ -220,15 +221,18 @@ func (e *DispatcherManager) newRedoDispatchers(infos map[common.DispatcherID]dis
rd.Remove()
return newWritePathClosedError()
}
// Register progress and its generation before event delivery can report Working.
e.redoDispatcherMap.Set(rd.GetId(), rd)
if rd.IsTableTriggerDispatcher() {
e.SetTableTriggerRedoDispatcher(rd)
} else {
e.redoSchemaIDToDispatchers.Set(schemaIds[idx], id)
failpoint.Inject("beforeRegisterDispatcher", func() {
failpoint.Call("github.com/pingcap/ticdc/downstreamadapter/dispatchermanager/beforeRegisterDispatcher", rd)
})
appcontext.GetService[*eventcollector.EventCollector](appcontext.EventCollector).AddDispatcher(rd, e.redoQuota)
}

redoSeq := e.redoDispatcherMap.Set(rd.GetId(), rd)
rd.SetSeq(redoSeq)
e.writePathMu.Unlock()

if rd.IsTableTriggerDispatcher() {
Expand Down
Loading
Loading