From 7d1a6a694d210962d7dd4ed98f9cccacdfcf0cb0 Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 11:44:37 +0800 Subject: [PATCH 1/7] reduce memory usage and pause kafka partition --- cmd/consumer/conductor/conductor.go | 210 ++++++++++++++---- cmd/consumer/conductor/conductor_test.go | 138 +++++++++++- cmd/consumer/source/kafka.go | 16 ++ cmd/consumer/source/mock/source_mock.go | 47 ++++ cmd/consumer/source/source.go | 7 + pkg/sink/codec/avro/decoder.go | 8 +- pkg/sink/codec/canal/canal_json_decoder.go | 8 +- pkg/sink/codec/canal/canal_json_test.go | 22 ++ .../codec/canal/canal_json_txn_decoder.go | 8 +- pkg/sink/codec/csv/csv_decoder.go | 8 +- pkg/sink/codec/debezium/decoder.go | 12 +- pkg/sink/codec/open/decoder.go | 8 +- pkg/sink/codec/simple/decoder.go | 8 +- 13 files changed, 444 insertions(+), 56 deletions(-) diff --git a/cmd/consumer/conductor/conductor.go b/cmd/consumer/conductor/conductor.go index df4cfcc5b1..2c403547a0 100644 --- a/cmd/consumer/conductor/conductor.go +++ b/cmd/consumer/conductor/conductor.go @@ -63,6 +63,13 @@ type waitingDML struct { pending *simple.PendingMessage partition int32 offset int64 + bytes int64 +} + +type queuedDML struct { + row *event.DMLEvent + partition int32 + bytes int64 } const ( @@ -70,6 +77,15 @@ const ( roundRows = 1024 // roundBytes bounds the encoded bytes handed to the writer in one round. roundBytes = 2 << 20 + // maxTotalPendingBytes targets the aggregate per-partition pause threshold + // across all partitions of a partitioned source. + maxTotalPendingBytes int64 = 128 << 20 + // maxPartitionPauseBytes caps any single partition's buffer before pausing. + maxPartitionPauseBytes int64 = 8 << 20 + // minPartitionPauseBytes sets the floor for each partition's pause threshold. + minPartitionPauseBytes int64 = 1 << 20 + // dmlEventOverheadBytes approximates per-event metadata beyond row chunk bytes. + dmlEventOverheadBytes int64 = 512 // progressLogInterval controls how often consumer progress and throughput are logged. progressLogInterval = 10 * time.Second ) @@ -83,6 +99,7 @@ type Conductor struct { schemas *codecCommon.TableInfoProvider notifier source.SchemaNotifier + pauser source.Pauser // decoder assembles woken Simple DMLs serially via DecodePending. decoder *decode.Group @@ -91,8 +108,14 @@ type Conductor struct { // partitionWatermarks holds each partition's resolved timestamp; watermark is // their global minimum once every partition has reported. - partitionWatermarks []uint64 - watermark uint64 + partitionWatermarks []uint64 + partitionPendingBytes []int64 + pausedPartitions []bool + pausedCount int + pendingDMLBytes int64 + partitionPauseBytes int64 + partitionResumeBytes int64 + watermark uint64 // pendingDML indexes all buffered per-table queues; readyHeap holds only // queues whose head row is not blocked behind pendingDDL (ordered by CommitTs). @@ -110,19 +133,28 @@ type Conductor struct { // New creates a conductor driven by reader metadata, decoder schema state, and // pending-DML assembly. func New(reader source.Reader, schemas *codecCommon.TableInfoProvider, decoder *decode.Group) *Conductor { + partitions := reader.Partitions() + pauseBytes, resumeBytes := partitionBufferLimits(partitions) c := &Conductor{ - schemas: schemas, - decoder: decoder, - confirmable: make(chan struct{}, 1), - positions: make(map[int32][]sourcePosition), - partitionWatermarks: make([]uint64, reader.Partitions()), - pendingDML: make(map[int64]*tableQueue), - waiting: make(map[waitingSchemaKey][]waitingDML), + schemas: schemas, + decoder: decoder, + confirmable: make(chan struct{}, 1), + positions: make(map[int32][]sourcePosition), + partitionWatermarks: make([]uint64, partitions), + partitionPendingBytes: make([]int64, partitions), + pausedPartitions: make([]bool, partitions), + partitionPauseBytes: pauseBytes, + partitionResumeBytes: resumeBytes, + pendingDML: make(map[int64]*tableQueue), + waiting: make(map[waitingSchemaKey][]waitingDML), } if notifier, ok := reader.(source.SchemaNotifier); ok { c.notifier = notifier } + if pauser, ok := reader.(source.Pauser); ok { + c.pauser = pauser + } return c } @@ -175,6 +207,7 @@ func (c *Conductor) run(ctx context.Context, tasks <-chan *decode.Future, w *wri } return err } + c.syncPartitionPacing() c.observeCheckpoint(c.confirmCheckpoint(w.Checkpoint())) c.recordPosition(marker, future.Payload) @@ -207,9 +240,13 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti zap.Uint64("effectiveWatermark", c.effectiveWatermark()), zap.Uint64("checkpoint", checkpoint), zap.Int("pendingDMLTables", len(c.pendingDML)), + zap.Int64("pendingDMLBytes", c.pendingDMLBytes), zap.Int("pendingDDL", len(c.pendingDDL)), zap.Int("pendingDecode", c.waitingCount), } + if c.pausedCount > 0 { + fields = append(fields, zap.Int("pausedPartitions", c.pausedCount)) + } if inFlightEvents != 0 { fields = append(fields, zap.Int("inFlightEvents", inFlightEvents), @@ -253,13 +290,24 @@ func (c *Conductor) accept(future *decode.Future) uint64 { for _, e := range future.Events { marker = max(marker, c.acceptEvent(e, future.Payload)) } - marker = max(marker, c.acceptPending(future.Pending, future.Payload)) + marker = max(marker, c.acceptPending(future.Pending, future.Payload, future.Bytes)) c.releaseSchemas() return marker } -func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload) uint64 { - var marker uint64 +func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload, payloadBytes int64) uint64 { + var ( + marker uint64 + perItemBytes int64 + offset int64 + ) + partition := payloadPartition(payload) + if payload != nil { + offset = payload.Offset + } + if len(items) > 0 { + perItemBytes = max(payloadBytes/int64(len(items)), dmlEventOverheadBytes) + } for _, pending := range items { if released := c.schemas.ReleasedWatermark(); released != 0 && pending.CommitTs <= released { continue @@ -267,7 +315,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc marker = max(marker, pending.CommitTs) if tableInfo := c.schemas.Read(pending.Schema, pending.Table, pending.SchemaVersion); tableInfo != nil { - c.queueDML(c.decoder.DecodePending(pending, tableInfo, payload.Partition, payload.Offset)) + c.queueDML(c.decoder.DecodePending(pending, tableInfo, partition, offset), partition) continue } @@ -278,9 +326,11 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc } c.waiting[key] = append(c.waiting[key], waitingDML{ pending: pending, - partition: payload.Partition, - offset: payload.Offset, + partition: partition, + offset: offset, + bytes: perItemBytes, }) + c.addPartitionBytes(partition, perItemBytes) c.waitingCount++ if pending.CommitTs != 0 && (c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs) { c.minWaitingTs = pending.CommitTs @@ -308,7 +358,8 @@ func (c *Conductor) wakeWaiting(info *common.TableInfo) { delete(c.waiting, key) c.waitingCount -= len(items) for _, item := range items { - c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset)) + c.subPartitionBytes(item.partition, item.bytes) + c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset), item.partition) } c.recomputeMinWaiting() } @@ -328,10 +379,10 @@ func (c *Conductor) recomputeMinWaiting() { func (c *Conductor) acceptEvent(e event.Event, payload *source.Payload) uint64 { switch e := e.(type) { case *event.DMLEvent: - c.queueDML(e) + c.queueDML(e, payloadPartition(payload)) return e.CommitTs case *event.ResolvedEvent: - c.advanceWatermark(e.ResolvedTs, payload.Partition) + c.advanceWatermark(e.ResolvedTs, payloadPartition(payload)) case *event.DDLEvent: c.wakeWaiting(e.TableInfo) for _, info := range e.MultipleTableInfos { @@ -384,7 +435,7 @@ func (c *Conductor) recordPosition(marker uint64, payload *source.Payload) { // tableQueue holds one table's pending DMLs ordered by (CommitTs, dmlRowOrder). type tableQueue struct { tableID int64 - rows []*event.DMLEvent + rows []queuedDML dropped int // heapIndex records the index in readyHeap, or -1 when blocked behind pendingDDL. heapIndex int @@ -396,11 +447,11 @@ func (h tableHeap) Len() int { return len(h) } func (h tableHeap) Less(i, j int) bool { a, b := h[i], h[j] - if a.rows[0].CommitTs != b.rows[0].CommitTs { - return a.rows[0].CommitTs < b.rows[0].CommitTs + if a.rows[0].row.CommitTs != b.rows[0].row.CommitTs { + return a.rows[0].row.CommitTs < b.rows[0].row.CommitTs } - if oa, ob := dmlRowOrder(a.rows[0]), dmlRowOrder(b.rows[0]); oa != ob { + if oa, ob := dmlRowOrder(a.rows[0].row), dmlRowOrder(b.rows[0].row); oa != ob { return oa < ob } @@ -462,13 +513,13 @@ func dmlBefore(a, b *event.DMLEvent) bool { return dmlRowOrder(a) < dmlRowOrder(b) } -func insertDML(rows []*event.DMLEvent, item *event.DMLEvent) ([]*event.DMLEvent, bool) { - if len(rows) == 0 || !dmlBefore(item, rows[len(rows)-1]) { +func insertDML(rows []queuedDML, item queuedDML) ([]queuedDML, bool) { + if len(rows) == 0 || !dmlBefore(item.row, rows[len(rows)-1].row) { return append(rows, item), len(rows) == 0 } index := sort.Search(len(rows), func(i int) bool { - return dmlBefore(item, rows[i]) + return dmlBefore(item.row, rows[i].row) }) return slices.Insert(rows, index, item), index == 0 @@ -479,7 +530,7 @@ func (c *Conductor) rowBlockedByDDL(item *event.DMLEvent) bool { } func (c *Conductor) syncTable(q *tableQueue) { - blocked := c.rowBlockedByDDL(q.rows[0]) + blocked := c.rowBlockedByDDL(q.rows[0].row) inHeap := q.heapIndex >= 0 if blocked == !inHeap { if !blocked { @@ -497,14 +548,24 @@ func (c *Conductor) syncTable(q *tableQueue) { } // queueDML records a decoded row until the writer can accept it. -func (c *Conductor) queueDML(item *event.DMLEvent) { +func (c *Conductor) queueDML(item *event.DMLEvent, partition int32) { + bytes := dmlMemoryBytes(item) + c.pendingDMLBytes += bytes + c.addPartitionBytes(partition, bytes) + + entry := queuedDML{ + row: item, + partition: partition, + bytes: bytes, + } + tableID := item.PhysicalTableID q := c.pendingDML[tableID] if q == nil { q = &tableQueue{ tableID: tableID, - rows: []*event.DMLEvent{item}, + rows: []queuedDML{entry}, heapIndex: -1, } c.pendingDML[tableID] = q @@ -517,7 +578,7 @@ func (c *Conductor) queueDML(item *event.DMLEvent) { // A source may deliver an earlier timestamp or split DELETE before resolution. var headChanged bool - q.rows, headChanged = insertDML(q.rows, item) + q.rows, headChanged = insertDML(q.rows, entry) if headChanged { c.syncTable(q) } @@ -537,7 +598,7 @@ func (c *Conductor) queueDDL(ddlEvent *event.DDLEvent) { // Rows already buffered above the DDL commit timestamp wait for it. var blocked []*tableQueue for _, q := range c.readyHeap { - if q.rows[0].CommitTs > ts { + if q.rows[0].row.CommitTs > ts { blocked = append(blocked, q) } } @@ -553,7 +614,7 @@ func (c *Conductor) nextReady() (*event.DDLEvent, *event.DMLEvent) { if len(c.pendingDDL) != 0 { head := c.pendingDDL[0] if head.GetCommitTs() <= c.effectiveWatermark() && - (len(c.readyHeap) == 0 || c.readyHeap[0].rows[0].CommitTs > head.GetCommitTs()) { + (len(c.readyHeap) == 0 || c.readyHeap[0].rows[0].row.CommitTs > head.GetCommitTs()) { return head, nil } } @@ -567,7 +628,7 @@ func (c *Conductor) nextDML() *event.DMLEvent { return nil } - head := c.readyHeap[0].rows[0] + head := c.readyHeap[0].rows[0].row if head.CommitTs > c.effectiveWatermark() { return nil } @@ -577,9 +638,12 @@ func (c *Conductor) nextDML() *event.DMLEvent { func (c *Conductor) popDML(row *event.DMLEvent) { q := c.pendingDML[row.PhysicalTableID] - q.rows[0] = nil + entry := q.rows[0] + q.rows[0] = queuedDML{} q.rows = q.rows[1:] q.dropped++ + c.pendingDMLBytes -= entry.bytes + c.subPartitionBytes(entry.partition, entry.bytes) if len(q.rows) == 0 { if q.heapIndex >= 0 { @@ -605,7 +669,7 @@ func (c *Conductor) popDDL() *event.DDLEvent { } for _, q := range c.pendingDML { - if q.heapIndex < 0 && !c.rowBlockedByDDL(q.rows[0]) { + if q.heapIndex < 0 && !c.rowBlockedByDDL(q.rows[0].row) { heap.Push(&c.readyHeap, q) } } @@ -634,10 +698,10 @@ func (c *Conductor) drainTransaction(row *event.DMLEvent, w *writer.Writer) (int return rows, bytes } q := c.pendingDML[tableID] - if q == nil || q.heapIndex < 0 || q.rows[0].CommitTs != commitTs { + if q == nil || q.heapIndex < 0 || q.rows[0].row.CommitTs != commitTs { return rows, bytes } - row = q.rows[0] + row = q.rows[0].row } } @@ -706,7 +770,7 @@ func (c *Conductor) advanceWatermark(ts uint64, partition int32) { return } - if int(partition) >= len(c.partitionWatermarks) { + if partition < 0 || int(partition) >= len(c.partitionWatermarks) { return } @@ -729,7 +793,7 @@ func (c *Conductor) advanceWatermark(ts uint64, partition int32) { func (c *Conductor) advanceWriter(w *writer.Writer) { var pending uint64 if len(c.readyHeap) != 0 { - pending = earliest(pending, c.readyHeap[0].rows[0].CommitTs) + pending = earliest(pending, c.readyHeap[0].rows[0].row.CommitTs) } if len(c.pendingDDL) != 0 { pending = earliest(pending, c.pendingDDL[0].GetCommitTs()) @@ -738,6 +802,76 @@ func (c *Conductor) advanceWriter(w *writer.Writer) { w.Advance(c.effectiveWatermark(), pending) } +func partitionBufferLimits(partitions int32) (pauseBytes, resumeBytes int64) { + if partitions <= 1 { + return maxPartitionPauseBytes, maxPartitionPauseBytes / 2 + } + pauseBytes = min(maxPartitionPauseBytes, max(minPartitionPauseBytes, maxTotalPendingBytes/int64(partitions))) + return pauseBytes, pauseBytes / 2 +} + +func payloadPartition(payload *source.Payload) int32 { + if payload == nil { + return -1 + } + return payload.Partition +} + +func dmlMemoryBytes(item *event.DMLEvent) int64 { + if item == nil || item.Rows == nil { + return dmlEventOverheadBytes + } + return dmlEventOverheadBytes + item.Rows.MemoryUsage() +} + +func (c *Conductor) addPartitionBytes(partition int32, bytes int64) { + if partition >= 0 && int(partition) < len(c.partitionPendingBytes) { + c.partitionPendingBytes[partition] += bytes + } +} + +func (c *Conductor) subPartitionBytes(partition int32, bytes int64) { + if partition < 0 || int(partition) >= len(c.partitionPendingBytes) { + return + } + c.partitionPendingBytes[partition] = max(0, c.partitionPendingBytes[partition]-bytes) +} + +// syncPartitionPacing pauses partitions whose resolved progress leads the slowest +// partition and whose buffered bytes exceed the per-partition threshold, and +// resumes partitions when they drain or are needed to advance progress. +func (c *Conductor) syncPartitionPacing() { + if c.pauser == nil || len(c.partitionWatermarks) <= 1 { + return + } + + minWatermark := slices.Min(c.partitionWatermarks) + var toPause, toResume []int32 + for p, resolved := range c.partitionWatermarks { + ahead := resolved > minWatermark && (c.minWaitingTs == 0 || resolved >= c.minWaitingTs) + if c.pausedPartitions[p] { + if !ahead || c.partitionPendingBytes[p] <= c.partitionResumeBytes { + c.pausedPartitions[p] = false + c.pausedCount-- + toResume = append(toResume, int32(p)) + } + continue + } + if ahead && c.partitionPendingBytes[p] >= c.partitionPauseBytes { + c.pausedPartitions[p] = true + c.pausedCount++ + toPause = append(toPause, int32(p)) + } + } + + if len(toResume) > 0 { + c.pauser.Resume(toResume) + } + if len(toPause) > 0 { + c.pauser.Pause(toPause) + } +} + func (c *Conductor) confirmCheckpoint(checkpoint uint64) uint64 { if len(c.pendingDDL) == 0 { return checkpoint diff --git a/cmd/consumer/conductor/conductor_test.go b/cmd/consumer/conductor/conductor_test.go index 0fee44ed5b..363472e649 100644 --- a/cmd/consumer/conductor/conductor_test.go +++ b/cmd/consumer/conductor/conductor_test.go @@ -472,8 +472,8 @@ func TestConductorEffectiveWatermarkPendingDecode(t *testing.T) { q := c.pendingDML[t1Info.TableName.TableID] require.NotNil(t, q) require.Len(t, q.rows, 2) - require.Equal(t, uint64(200), q.rows[0].CommitTs) - q.rows[0].AddPostFlushFunc(record("t1:dml@200")) + require.Equal(t, uint64(200), q.rows[0].row.CommitTs) + q.rows[0].row.AddPostFlushFunc(record("t1:dml@200")) require.NoError(t, c.flush(t.Context(), w)) require.NoError(t, w.Drain(t.Context())) @@ -920,3 +920,137 @@ func TestConductorRunAdvancesCheckpointWhenAsyncWriterCompletesIdle(t *testing.T group.Close() require.Equal(t, uint64(100), w.Checkpoint()) } + +type mockPauserReader struct { + *sourcemock.MockReader + *sourcemock.MockPauser +} + +func newTestPauseDML(tableID int64, info *common.TableInfo, commitTs uint64) *event.DMLEvent { + dml := newInsertDML(info, commitTs, 1, 2) + dml.PhysicalTableID = tableID + return dml +} + +func TestConductorPartitionPacingAndResumeOnDrain(t *testing.T) { + ctrl := gomock.NewController(t) + mr := sourcemock.NewMockReader(ctrl) + mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() + mp := sourcemock.NewMockPauser(ctrl) + gomock.InOrder( + mp.EXPECT().Pause([]int32{0}).Times(1), + mp.EXPECT().Resume([]int32{0}).Times(1), + ) + + c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) + c.partitionPauseBytes = 2000 + c.partitionResumeBytes = 1000 + w := startBlackholeWriter(t) + defer func() { + require.NoError(t, w.Drain(t.Context())) + }() + + info := newTestTableInfo(1, "t1", 100, "id", "v") + // Queue a DDL at 150 so DMLs at 200 on partition 0 stay buffered behind it. + ddl := newTestAlterDDL(info, 150, "ALTER TABLE test.t1 ADD COLUMN c INT") + c.acceptEvent(ddl, &source.Payload{Partition: 0}) + + // Partition 2 is the lagging partition (resolved == 0 == minWatermark): high buffered bytes must NOT pause it. + for range 5 { + c.acceptEvent(newTestPauseDML(1, info, 110), &source.Payload{Partition: 2}) + } + c.advanceWatermark(100, 1) + c.syncPartitionPacing() + require.False(t, c.pausedPartitions[2]) + require.False(t, c.pausedPartitions[1]) + + // Partition 0 exceeds partitionPauseBytes and leads minWatermark (partition 2 at 0) -> pauses partition 0. + c.advanceWatermark(250, 0) + for range 5 { + c.acceptEvent(newTestPauseDML(1, info, 200), &source.Payload{Partition: 0}) + } + require.GreaterOrEqual(t, c.partitionPendingBytes[0], c.partitionPauseBytes) + c.syncPartitionPacing() + require.True(t, c.pausedPartitions[0]) + require.False(t, c.pausedPartitions[1]) + require.False(t, c.pausedPartitions[2]) + require.Equal(t, 1, c.pausedCount) + + // Lagging partition catches up past 200 and buffered events flush -> partition 0 drains and resumes. + c.advanceWatermark(220, 1) + c.advanceWatermark(220, 2) + require.NoError(t, c.flush(t.Context(), w)) + c.syncPartitionPacing() + require.LessOrEqual(t, c.partitionPendingBytes[0], c.partitionResumeBytes) + require.False(t, c.pausedPartitions[0]) + require.Zero(t, c.pausedCount) +} + +func TestConductorPartitionResumesWhenMinWatermarkCatchesUp(t *testing.T) { + ctrl := gomock.NewController(t) + mr := sourcemock.NewMockReader(ctrl) + mr.EXPECT().Partitions().Return(int32(2)).AnyTimes() + mp := sourcemock.NewMockPauser(ctrl) + gomock.InOrder( + mp.EXPECT().Pause([]int32{0}).Times(1), + mp.EXPECT().Resume([]int32{0}).Times(1), + ) + + c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) + c.partitionPauseBytes = 2000 + c.partitionResumeBytes = 1000 + + info := newTestTableInfo(1, "t1", 100, "id", "v") + c.advanceWatermark(100, 1) + c.advanceWatermark(200, 0) + for range 5 { + c.acceptEvent(newTestPauseDML(1, info, 200), &source.Payload{Partition: 0}) + } + c.syncPartitionPacing() + require.True(t, c.pausedPartitions[0]) + + // Partition 1 catches up to 200 without draining partition 0; minWatermark == 200 forces resume. + c.advanceWatermark(200, 1) + require.Greater(t, c.partitionPendingBytes[0], c.partitionResumeBytes) + c.syncPartitionPacing() + require.False(t, c.pausedPartitions[0]) + require.Zero(t, c.pausedCount) +} + +func TestConductorPartitionResumesBehindMinWaitingTs(t *testing.T) { + ctrl := gomock.NewController(t) + mr := sourcemock.NewMockReader(ctrl) + mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() + mp := sourcemock.NewMockPauser(ctrl) + gomock.InOrder( + mp.EXPECT().Pause([]int32{0}).Times(1), + mp.EXPECT().Resume([]int32{0}).Times(1), + ) + + c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) + c.partitionPauseBytes = 2000 + c.partitionResumeBytes = 1000 + + info := newTestTableInfo(1, "t1", 100, "id", "v") + c.advanceWatermark(10, 2) + c.advanceWatermark(100, 1) + c.advanceWatermark(150, 0) + for range 5 { + c.acceptEvent(newTestPauseDML(1, info, 140), &source.Payload{Partition: 0}) + } + c.syncPartitionPacing() + require.True(t, c.pausedPartitions[0]) + + // A Simple DML waiting for schema at CommitTs=200 arrives on partition 1; + // partition 0 is only at 150 (< 200) and may hold that schema DDL, so it resumes. + c.acceptPending([]*simple.PendingMessage{{ + Schema: "test", + Table: "t2", + SchemaVersion: 200, + CommitTs: 200, + }}, &source.Payload{Partition: 1, Offset: 1}, 512) + require.Equal(t, uint64(200), c.minWaitingTs) + c.syncPartitionPacing() + require.False(t, c.pausedPartitions[0]) + require.Zero(t, c.pausedCount) +} diff --git a/cmd/consumer/source/kafka.go b/cmd/consumer/source/kafka.go index 3cfa914cae..2e8e4f9196 100644 --- a/cmd/consumer/source/kafka.go +++ b/cmd/consumer/source/kafka.go @@ -36,6 +36,8 @@ import ( "go.uber.org/zap" ) +var _ Pauser = (*kafkaReader)(nil) + // kafkaReader consumes records from a Kafka topic and verifies partition routing. type kafkaReader struct { protocol config.Protocol @@ -108,6 +110,20 @@ func (c *kafkaReader) Partitions() int32 { return c.partitions } +func (c *kafkaReader) Pause(ids []int32) { + if len(ids) == 0 { + return + } + c.client.PauseFetchPartitions(map[string][]int32{c.topic: ids}) +} + +func (c *kafkaReader) Resume(ids []int32) { + if len(ids) == 0 { + return + } + c.client.ResumeFetchPartitions(map[string][]int32{c.topic: ids}) +} + func (c *kafkaReader) Read(ctx context.Context) ([]*Payload, error) { fetches := c.client.PollRecords(ctx, readBatchRows) if err := fetches.Err(); err != nil { diff --git a/cmd/consumer/source/mock/source_mock.go b/cmd/consumer/source/mock/source_mock.go index 23c2c7c5f7..8516469931 100644 --- a/cmd/consumer/source/mock/source_mock.go +++ b/cmd/consumer/source/mock/source_mock.go @@ -146,3 +146,50 @@ func (mr *MockSchemaNotifierMockRecorder) MarkProcessed(tables, timestamp interf mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkProcessed", reflect.TypeOf((*MockSchemaNotifier)(nil).MarkProcessed), tables, timestamp) } + +// MockPauser is a mock of Pauser interface. +type MockPauser struct { + ctrl *gomock.Controller + recorder *MockPauserMockRecorder +} + +// MockPauserMockRecorder is the mock recorder for MockPauser. +type MockPauserMockRecorder struct { + mock *MockPauser +} + +// NewMockPauser creates a new mock instance. +func NewMockPauser(ctrl *gomock.Controller) *MockPauser { + mock := &MockPauser{ctrl: ctrl} + mock.recorder = &MockPauserMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPauser) EXPECT() *MockPauserMockRecorder { + return m.recorder +} + +// Pause mocks base method. +func (m *MockPauser) Pause(ids []int32) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Pause", ids) +} + +// Pause indicates an expected call of Pause. +func (mr *MockPauserMockRecorder) Pause(ids interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Pause", reflect.TypeOf((*MockPauser)(nil).Pause), ids) +} + +// Resume mocks base method. +func (m *MockPauser) Resume(ids []int32) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Resume", ids) +} + +// Resume indicates an expected call of Resume. +func (mr *MockPauserMockRecorder) Resume(ids interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resume", reflect.TypeOf((*MockPauser)(nil).Resume), ids) +} diff --git a/cmd/consumer/source/source.go b/cmd/consumer/source/source.go index b2aed277b8..14f1b303f1 100644 --- a/cmd/consumer/source/source.go +++ b/cmd/consumer/source/source.go @@ -86,6 +86,13 @@ type SchemaNotifier interface { MarkProcessed(tables []event.SchemaTableName, timestamp uint64) } +// Pauser is implemented by sources that can pause and resume reading +// individual input streams to bound conductor memory. +type Pauser interface { + Pause(ids []int32) + Resume(ids []int32) +} + // Kind identifies the upstream transport. type Kind string diff --git a/pkg/sink/codec/avro/decoder.go b/pkg/sink/codec/avro/decoder.go index f19d48f63f..9d140c8622 100644 --- a/pkg/sink/codec/avro/decoder.go +++ b/pkg/sink/codec/avro/decoder.go @@ -335,9 +335,13 @@ func assembleEvent( event.StartTs = uint64(commitTs) event.CommitTs = uint64(commitTs) event.PhysicalTableID = event.TableInfo.TableName.TableID - event.Rows = chunk.NewChunkFromPoolWithCapacity(event.TableInfo.GetFieldSlice(), chunk.InitialCapacity) + rowCap := 1 + if !isDelete && (hasBefore || updateWithoutBefore) { + rowCap = 2 + } + event.Rows = chunk.NewChunkFromPoolWithCapacity(event.TableInfo.GetFieldSlice(), rowCap) event.AddPostFlushFunc(func() { - event.Rows.Destroy(chunk.InitialCapacity, event.TableInfo.GetFieldSlice()) + event.Rows.Destroy(rowCap, event.TableInfo.GetFieldSlice()) }) event.Length++ if isDelete { diff --git a/pkg/sink/codec/canal/canal_json_decoder.go b/pkg/sink/codec/canal/canal_json_decoder.go index a59a220118..249de5cc32 100644 --- a/pkg/sink/codec/canal/canal_json_decoder.go +++ b/pkg/sink/codec/canal/canal_json_decoder.go @@ -326,9 +326,13 @@ func (d *decoder) canalJSONMessage2DMLEvent( result.StartTs = msg.getCommitTs() result.CommitTs = msg.getCommitTs() result.PhysicalTableID = tableInfo.TableName.TableID - result.Rows = chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), chunk.InitialCapacity) + rowCap := 1 + if msg.eventType() == canal.EventType_UPDATE { + rowCap = 2 + } + result.Rows = chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) result.AddPostFlushFunc(func() { - result.Rows.Destroy(chunk.InitialCapacity, tableInfo.GetFieldSlice()) + result.Rows.Destroy(rowCap, tableInfo.GetFieldSlice()) }) result.Length++ diff --git a/pkg/sink/codec/canal/canal_json_test.go b/pkg/sink/codec/canal/canal_json_test.go index c1e2223024..c9d3799822 100644 --- a/pkg/sink/codec/canal/canal_json_test.go +++ b/pkg/sink/codec/canal/canal_json_test.go @@ -1704,6 +1704,28 @@ func TestSharedCacheValidatesLayoutAcrossPartitions(t *testing.T) { require.Same(t, evPK.TableInfo, stillPK) } +func TestCanalJSONDecoderRowChunkCapacity(t *testing.T) { + ctx := t.Context() + cfg := common.NewConfig(config.ProtocolCanalJSON) + cfg.EnableTiDBExtension = true + dec, err := NewDecoder(ctx, cfg, nil, nil) + require.NoError(t, err) + + decodeAndCheckCap := func(payload string, wantCap int) { + dec.AddKeyValue(nil, []byte(payload)) + tp, hasNext := dec.HasNext() + require.True(t, hasNext) + require.Equal(t, common.MessageTypeRow, tp) + dml := dec.NextDMLEvent() + require.Equal(t, wantCap, dml.Rows.Capacity()) + dml.PostFlush() + } + + decodeAndCheckCap(`{"id":0,"database":"test","table":"t","pkNames":["id"],"isDdl":false,"type":"INSERT","es":1,"ts":1,"sql":"","mysqlType":{"id":"int","v":"varchar(32)"},"data":[{"id":"1","v":"a"}],"old":null,"_tidb":{"commitTs":100}}`, 1) + decodeAndCheckCap(`{"id":0,"database":"test","table":"t","pkNames":["id"],"isDdl":false,"type":"UPDATE","es":1,"ts":1,"sql":"","mysqlType":{"id":"int","v":"varchar(32)"},"data":[{"id":"1","v":"b"}],"old":[{"id":"1","v":"a"}],"_tidb":{"commitTs":101}}`, 2) + decodeAndCheckCap(`{"id":0,"database":"test","table":"t","pkNames":["id"],"isDdl":false,"type":"DELETE","es":1,"ts":1,"sql":"","mysqlType":{"id":"int","v":"varchar(32)"},"data":[{"id":"1","v":"b"}],"old":null,"_tidb":{"commitTs":102}}`, 1) +} + func BenchmarkCanalJSONQueryTableInfo50Cols(b *testing.B) { mysqlTypes := make(map[string]string, 50) mysqlTypes["id"] = "int" diff --git a/pkg/sink/codec/canal/canal_json_txn_decoder.go b/pkg/sink/codec/canal/canal_json_txn_decoder.go index 2f96bb84cb..74fdd9b260 100644 --- a/pkg/sink/codec/canal/canal_json_txn_decoder.go +++ b/pkg/sink/codec/canal/canal_json_txn_decoder.go @@ -136,9 +136,13 @@ func (d *txnDecoder) canalJSONMessage2RowChange(msg canalJSONMessageInterface) * result.CommitTs = msg.getCommitTs() result.TableInfo = tableInfo - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), chunk.InitialCapacity) + rowCap := 1 + if msg.eventType() == canal.EventType_UPDATE { + rowCap = 2 + } + chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) result.AddPostFlushFunc(func() { - chk.Destroy(chunk.InitialCapacity, tableInfo.GetFieldSlice()) + chk.Destroy(rowCap, tableInfo.GetFieldSlice()) }) columns := tableInfo.GetColumns() diff --git a/pkg/sink/codec/csv/csv_decoder.go b/pkg/sink/codec/csv/csv_decoder.go index 5362f7a422..9253d1567b 100644 --- a/pkg/sink/codec/csv/csv_decoder.go +++ b/pkg/sink/codec/csv/csv_decoder.go @@ -329,9 +329,13 @@ func csvMsg2RowChangedEvent(csvConfig *common.Config, csvMsg *csvMessage, tableI } } - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), chunk.InitialCapacity) + rowCap := 1 + if deleteData != nil { + rowCap = 2 + } + chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) e.AddPostFlushFunc(func() { - chk.Destroy(chunk.InitialCapacity, tableInfo.GetFieldSlice()) + chk.Destroy(rowCap, tableInfo.GetFieldSlice()) }) if deleteData != nil { // Handle-key changes are split upstream. Keep the keyed delete and diff --git a/pkg/sink/codec/debezium/decoder.go b/pkg/sink/codec/debezium/decoder.go index 699547667c..ed403e0a1f 100644 --- a/pkg/sink/codec/debezium/decoder.go +++ b/pkg/sink/codec/debezium/decoder.go @@ -192,8 +192,14 @@ func (d *decoder) assembleDMLEventFromPayload( // message does not stop production consumption. startTs = commitTs } + before, ok1 := valuePayload["before"].(map[string]any) + after, ok2 := valuePayload["after"].(map[string]any) + rowCap := 1 + if ok1 && ok2 { + rowCap = 2 + } event := &commonEvent.DMLEvent{ - Rows: chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), chunk.InitialCapacity), + Rows: chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap), StartTs: startTs, CommitTs: commitTs, TableInfo: tableInfo, @@ -201,19 +207,17 @@ func (d *decoder) assembleDMLEventFromPayload( Length: 1, } event.AddPostFlushFunc(func() { - event.Rows.Destroy(chunk.InitialCapacity, tableInfo.GetFieldSlice()) + event.Rows.Destroy(rowCap, tableInfo.GetFieldSlice()) }) columns := tableInfo.GetColumns() binaryHandlingMode := d.config.DebeziumBinaryHandlingMode if d.config.Protocol == config.ProtocolDebeziumAvro { binaryHandlingMode = common.BinaryHandlingModeBase64 } - before, ok1 := valuePayload["before"].(map[string]any) if ok1 { data := assembleColumnData(before, columns, d.config.TimeZone, binaryHandlingMode) common.AppendRow2Chunk(data, columns, event.Rows) } - after, ok2 := valuePayload["after"].(map[string]any) if ok2 { data := assembleColumnData(after, columns, d.config.TimeZone, binaryHandlingMode) common.AppendRow2Chunk(data, columns, event.Rows) diff --git a/pkg/sink/codec/open/decoder.go b/pkg/sink/codec/open/decoder.go index e3b3919504..451a18d010 100644 --- a/pkg/sink/codec/open/decoder.go +++ b/pkg/sink/codec/open/decoder.go @@ -558,9 +558,13 @@ func (b *decoder) assembleDMLEvent(key *messageKey, value *messageRow) *commonEv result.CommitTs = key.Ts result.Length++ - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), chunk.InitialCapacity) + rowCap := 1 + if len(value.Delete) == 0 && len(value.Update) != 0 && len(value.PreColumns) != 0 { + rowCap = 2 + } + chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) result.AddPostFlushFunc(func() { - chk.Destroy(chunk.InitialCapacity, tableInfo.GetFieldSlice()) + chk.Destroy(rowCap, tableInfo.GetFieldSlice()) }) columns := tableInfo.GetColumns() if len(value.Delete) != 0 { diff --git a/pkg/sink/codec/simple/decoder.go b/pkg/sink/codec/simple/decoder.go index 8e860e31c1..b955aa8c10 100644 --- a/pkg/sink/codec/simple/decoder.go +++ b/pkg/sink/codec/simple/decoder.go @@ -543,9 +543,13 @@ func buildDMLEvent(msg *message, tableInfo *commonType.TableInfo, enableRowCheck Length: 1, } - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), chunk.InitialCapacity) + rowCap := 1 + if msg.Type == DMLTypeUpdate { + rowCap = 2 + } + chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) result.AddPostFlushFunc(func() { - chk.Destroy(chunk.InitialCapacity, tableInfo.GetFieldSlice()) + chk.Destroy(rowCap, tableInfo.GetFieldSlice()) }) columns := tableInfo.GetColumns() switch msg.Type { From f37e6b182948faf333ee6bb2108ca8d7969d0bb3 Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 12:00:09 +0800 Subject: [PATCH 2/7] simplify the code further --- cmd/consumer/conductor/conductor.go | 58 ++++++------------- pkg/sink/codec/avro/decoder.go | 8 +-- pkg/sink/codec/canal/canal_json_decoder.go | 8 +-- .../codec/canal/canal_json_txn_decoder.go | 7 +-- pkg/sink/codec/common/decoder.go | 11 ++++ pkg/sink/codec/csv/csv_decoder.go | 7 +-- pkg/sink/codec/debezium/decoder.go | 8 +-- pkg/sink/codec/open/decoder.go | 7 +-- pkg/sink/codec/simple/decoder.go | 7 +-- 9 files changed, 47 insertions(+), 74 deletions(-) diff --git a/cmd/consumer/conductor/conductor.go b/cmd/consumer/conductor/conductor.go index 2c403547a0..dffa367af1 100644 --- a/cmd/consumer/conductor/conductor.go +++ b/cmd/consumer/conductor/conductor.go @@ -112,7 +112,7 @@ type Conductor struct { partitionPendingBytes []int64 pausedPartitions []bool pausedCount int - pendingDMLBytes int64 + queuedDMLBytes int64 partitionPauseBytes int64 partitionResumeBytes int64 watermark uint64 @@ -134,7 +134,11 @@ type Conductor struct { // pending-DML assembly. func New(reader source.Reader, schemas *codecCommon.TableInfoProvider, decoder *decode.Group) *Conductor { partitions := reader.Partitions() - pauseBytes, resumeBytes := partitionBufferLimits(partitions) + var pauseBytes, resumeBytes int64 + if partitions > 1 { + pauseBytes = min(maxPartitionPauseBytes, max(minPartitionPauseBytes, maxTotalPendingBytes/int64(partitions))) + resumeBytes = pauseBytes / 2 + } c := &Conductor{ schemas: schemas, decoder: decoder, @@ -240,7 +244,7 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti zap.Uint64("effectiveWatermark", c.effectiveWatermark()), zap.Uint64("checkpoint", checkpoint), zap.Int("pendingDMLTables", len(c.pendingDML)), - zap.Int64("pendingDMLBytes", c.pendingDMLBytes), + zap.Int64("queuedDMLBytes", c.queuedDMLBytes), zap.Int("pendingDDL", len(c.pendingDDL)), zap.Int("pendingDecode", c.waitingCount), } @@ -299,12 +303,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc var ( marker uint64 perItemBytes int64 - offset int64 ) - partition := payloadPartition(payload) - if payload != nil { - offset = payload.Offset - } if len(items) > 0 { perItemBytes = max(payloadBytes/int64(len(items)), dmlEventOverheadBytes) } @@ -315,7 +314,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc marker = max(marker, pending.CommitTs) if tableInfo := c.schemas.Read(pending.Schema, pending.Table, pending.SchemaVersion); tableInfo != nil { - c.queueDML(c.decoder.DecodePending(pending, tableInfo, partition, offset), partition) + c.queueDML(c.decoder.DecodePending(pending, tableInfo, payload.Partition, payload.Offset), payload.Partition) continue } @@ -326,11 +325,11 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc } c.waiting[key] = append(c.waiting[key], waitingDML{ pending: pending, - partition: partition, - offset: offset, + partition: payload.Partition, + offset: payload.Offset, bytes: perItemBytes, }) - c.addPartitionBytes(partition, perItemBytes) + c.addPartitionBytes(payload.Partition, perItemBytes) c.waitingCount++ if pending.CommitTs != 0 && (c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs) { c.minWaitingTs = pending.CommitTs @@ -379,10 +378,10 @@ func (c *Conductor) recomputeMinWaiting() { func (c *Conductor) acceptEvent(e event.Event, payload *source.Payload) uint64 { switch e := e.(type) { case *event.DMLEvent: - c.queueDML(e, payloadPartition(payload)) + c.queueDML(e, payload.Partition) return e.CommitTs case *event.ResolvedEvent: - c.advanceWatermark(e.ResolvedTs, payloadPartition(payload)) + c.advanceWatermark(e.ResolvedTs, payload.Partition) case *event.DDLEvent: c.wakeWaiting(e.TableInfo) for _, info := range e.MultipleTableInfos { @@ -550,7 +549,7 @@ func (c *Conductor) syncTable(q *tableQueue) { // queueDML records a decoded row until the writer can accept it. func (c *Conductor) queueDML(item *event.DMLEvent, partition int32) { bytes := dmlMemoryBytes(item) - c.pendingDMLBytes += bytes + c.queuedDMLBytes += bytes c.addPartitionBytes(partition, bytes) entry := queuedDML{ @@ -642,7 +641,7 @@ func (c *Conductor) popDML(row *event.DMLEvent) { q.rows[0] = queuedDML{} q.rows = q.rows[1:] q.dropped++ - c.pendingDMLBytes -= entry.bytes + c.queuedDMLBytes -= entry.bytes c.subPartitionBytes(entry.partition, entry.bytes) if len(q.rows) == 0 { @@ -770,7 +769,7 @@ func (c *Conductor) advanceWatermark(ts uint64, partition int32) { return } - if partition < 0 || int(partition) >= len(c.partitionWatermarks) { + if int(partition) >= len(c.partitionWatermarks) { return } @@ -802,39 +801,20 @@ func (c *Conductor) advanceWriter(w *writer.Writer) { w.Advance(c.effectiveWatermark(), pending) } -func partitionBufferLimits(partitions int32) (pauseBytes, resumeBytes int64) { - if partitions <= 1 { - return maxPartitionPauseBytes, maxPartitionPauseBytes / 2 - } - pauseBytes = min(maxPartitionPauseBytes, max(minPartitionPauseBytes, maxTotalPendingBytes/int64(partitions))) - return pauseBytes, pauseBytes / 2 -} - -func payloadPartition(payload *source.Payload) int32 { - if payload == nil { - return -1 - } - return payload.Partition -} - func dmlMemoryBytes(item *event.DMLEvent) int64 { - if item == nil || item.Rows == nil { - return dmlEventOverheadBytes - } return dmlEventOverheadBytes + item.Rows.MemoryUsage() } func (c *Conductor) addPartitionBytes(partition int32, bytes int64) { - if partition >= 0 && int(partition) < len(c.partitionPendingBytes) { + if int(partition) < len(c.partitionPendingBytes) { c.partitionPendingBytes[partition] += bytes } } func (c *Conductor) subPartitionBytes(partition int32, bytes int64) { - if partition < 0 || int(partition) >= len(c.partitionPendingBytes) { - return + if int(partition) < len(c.partitionPendingBytes) { + c.partitionPendingBytes[partition] -= bytes } - c.partitionPendingBytes[partition] = max(0, c.partitionPendingBytes[partition]-bytes) } // syncPartitionPacing pauses partitions whose resolved progress leads the slowest diff --git a/pkg/sink/codec/avro/decoder.go b/pkg/sink/codec/avro/decoder.go index 9d140c8622..9eb98f1385 100644 --- a/pkg/sink/codec/avro/decoder.go +++ b/pkg/sink/codec/avro/decoder.go @@ -37,7 +37,6 @@ import ( "github.com/pingcap/tidb/pkg/parser/ast" "github.com/pingcap/tidb/pkg/parser/mysql" "github.com/pingcap/tidb/pkg/types" - "github.com/pingcap/tidb/pkg/util/chunk" "go.uber.org/zap" ) @@ -339,10 +338,9 @@ func assembleEvent( if !isDelete && (hasBefore || updateWithoutBefore) { rowCap = 2 } - event.Rows = chunk.NewChunkFromPoolWithCapacity(event.TableInfo.GetFieldSlice(), rowCap) - event.AddPostFlushFunc(func() { - event.Rows.Destroy(rowCap, event.TableInfo.GetFieldSlice()) - }) + var release func() + event.Rows, release = common.NewRowsChunk(event.TableInfo.GetFieldSlice(), rowCap) + event.AddPostFlushFunc(release) event.Length++ if isDelete { if hasValue { diff --git a/pkg/sink/codec/canal/canal_json_decoder.go b/pkg/sink/codec/canal/canal_json_decoder.go index 249de5cc32..f44cfc3074 100644 --- a/pkg/sink/codec/canal/canal_json_decoder.go +++ b/pkg/sink/codec/canal/canal_json_decoder.go @@ -38,7 +38,6 @@ import ( "github.com/pingcap/tidb/pkg/parser/mysql" "github.com/pingcap/tidb/pkg/parser/types" tiTypes "github.com/pingcap/tidb/pkg/types" - "github.com/pingcap/tidb/pkg/util/chunk" canal "github.com/pingcap/tiflow/proto/canal" "go.uber.org/zap" "golang.org/x/text/encoding/charmap" @@ -330,10 +329,9 @@ func (d *decoder) canalJSONMessage2DMLEvent( if msg.eventType() == canal.EventType_UPDATE { rowCap = 2 } - result.Rows = chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) - result.AddPostFlushFunc(func() { - result.Rows.Destroy(rowCap, tableInfo.GetFieldSlice()) - }) + var release func() + result.Rows, release = common.NewRowsChunk(tableInfo.GetFieldSlice(), rowCap) + result.AddPostFlushFunc(release) result.Length++ columns := tableInfo.GetColumns() diff --git a/pkg/sink/codec/canal/canal_json_txn_decoder.go b/pkg/sink/codec/canal/canal_json_txn_decoder.go index 74fdd9b260..15c89f400a 100644 --- a/pkg/sink/codec/canal/canal_json_txn_decoder.go +++ b/pkg/sink/codec/canal/canal_json_txn_decoder.go @@ -23,7 +23,6 @@ import ( commonEvent "github.com/pingcap/ticdc/pkg/common/event" "github.com/pingcap/ticdc/pkg/sink/codec/common" "github.com/pingcap/ticdc/pkg/util" - "github.com/pingcap/tidb/pkg/util/chunk" canal "github.com/pingcap/tiflow/proto/canal" "go.uber.org/zap" ) @@ -140,10 +139,8 @@ func (d *txnDecoder) canalJSONMessage2RowChange(msg canalJSONMessageInterface) * if msg.eventType() == canal.EventType_UPDATE { rowCap = 2 } - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) - result.AddPostFlushFunc(func() { - chk.Destroy(rowCap, tableInfo.GetFieldSlice()) - }) + chk, release := common.NewRowsChunk(tableInfo.GetFieldSlice(), rowCap) + result.AddPostFlushFunc(release) columns := tableInfo.GetColumns() switch msg.eventType() { diff --git a/pkg/sink/codec/common/decoder.go b/pkg/sink/codec/common/decoder.go index 9dfd3ae1e4..c697491100 100644 --- a/pkg/sink/codec/common/decoder.go +++ b/pkg/sink/codec/common/decoder.go @@ -15,8 +15,19 @@ package common import ( commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/tidb/pkg/types" + "github.com/pingcap/tidb/pkg/util/chunk" ) +// NewRowsChunk allocates a pooled chunk sized to capacity rows and returns its +// matching destroy callback for DMLEvent.AddPostFlushFunc. +func NewRowsChunk(fields []*types.FieldType, capacity int) (*chunk.Chunk, func()) { + chk := chunk.NewChunkFromPoolWithCapacity(fields, capacity) + return chk, func() { + chk.Destroy(capacity, fields) + } +} + // Decoder is an abstraction for events decoder. type Decoder interface { // AddKeyValue add the received key and values to the decoder, diff --git a/pkg/sink/codec/csv/csv_decoder.go b/pkg/sink/codec/csv/csv_decoder.go index 9253d1567b..39f03bd197 100644 --- a/pkg/sink/codec/csv/csv_decoder.go +++ b/pkg/sink/codec/csv/csv_decoder.go @@ -35,7 +35,6 @@ import ( "github.com/pingcap/tidb/pkg/parser/charset" "github.com/pingcap/tidb/pkg/parser/mysql" "github.com/pingcap/tidb/pkg/types" - "github.com/pingcap/tidb/pkg/util/chunk" "go.uber.org/zap" ) @@ -333,10 +332,8 @@ func csvMsg2RowChangedEvent(csvConfig *common.Config, csvMsg *csvMessage, tableI if deleteData != nil { rowCap = 2 } - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) - e.AddPostFlushFunc(func() { - chk.Destroy(rowCap, tableInfo.GetFieldSlice()) - }) + chk, release := common.NewRowsChunk(tableInfo.GetFieldSlice(), rowCap) + e.AddPostFlushFunc(release) if deleteData != nil { // Handle-key changes are split upstream. Keep the keyed delete and // after-image insert in one event, as for Avro updates without before values. diff --git a/pkg/sink/codec/debezium/decoder.go b/pkg/sink/codec/debezium/decoder.go index ed403e0a1f..da3ee35e64 100644 --- a/pkg/sink/codec/debezium/decoder.go +++ b/pkg/sink/codec/debezium/decoder.go @@ -37,7 +37,6 @@ import ( "github.com/pingcap/tidb/pkg/parser/mysql" ptypes "github.com/pingcap/tidb/pkg/parser/types" "github.com/pingcap/tidb/pkg/types" - "github.com/pingcap/tidb/pkg/util/chunk" "go.uber.org/zap" ) @@ -198,17 +197,16 @@ func (d *decoder) assembleDMLEventFromPayload( if ok1 && ok2 { rowCap = 2 } + rows, release := common.NewRowsChunk(tableInfo.GetFieldSlice(), rowCap) event := &commonEvent.DMLEvent{ - Rows: chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap), + Rows: rows, StartTs: startTs, CommitTs: commitTs, TableInfo: tableInfo, PhysicalTableID: tableInfo.TableName.TableID, Length: 1, } - event.AddPostFlushFunc(func() { - event.Rows.Destroy(rowCap, tableInfo.GetFieldSlice()) - }) + event.AddPostFlushFunc(release) columns := tableInfo.GetColumns() binaryHandlingMode := d.config.DebeziumBinaryHandlingMode if d.config.Protocol == config.ProtocolDebeziumAvro { diff --git a/pkg/sink/codec/open/decoder.go b/pkg/sink/codec/open/decoder.go index 451a18d010..646983012f 100644 --- a/pkg/sink/codec/open/decoder.go +++ b/pkg/sink/codec/open/decoder.go @@ -37,7 +37,6 @@ import ( "github.com/pingcap/tidb/pkg/parser/mysql" "github.com/pingcap/tidb/pkg/parser/types" tiTypes "github.com/pingcap/tidb/pkg/types" - "github.com/pingcap/tidb/pkg/util/chunk" "go.uber.org/zap" ) @@ -562,10 +561,8 @@ func (b *decoder) assembleDMLEvent(key *messageKey, value *messageRow) *commonEv if len(value.Delete) == 0 && len(value.Update) != 0 && len(value.PreColumns) != 0 { rowCap = 2 } - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) - result.AddPostFlushFunc(func() { - chk.Destroy(rowCap, tableInfo.GetFieldSlice()) - }) + chk, release := common.NewRowsChunk(tableInfo.GetFieldSlice(), rowCap) + result.AddPostFlushFunc(release) columns := tableInfo.GetColumns() if len(value.Delete) != 0 { data := collectAllColumnsValue(value.Delete, columns) diff --git a/pkg/sink/codec/simple/decoder.go b/pkg/sink/codec/simple/decoder.go index b955aa8c10..143bf30764 100644 --- a/pkg/sink/codec/simple/decoder.go +++ b/pkg/sink/codec/simple/decoder.go @@ -35,7 +35,6 @@ import ( "github.com/pingcap/tidb/pkg/parser/mysql" ptypes "github.com/pingcap/tidb/pkg/parser/types" "github.com/pingcap/tidb/pkg/types" - "github.com/pingcap/tidb/pkg/util/chunk" "go.uber.org/zap" ) @@ -547,10 +546,8 @@ func buildDMLEvent(msg *message, tableInfo *commonType.TableInfo, enableRowCheck if msg.Type == DMLTypeUpdate { rowCap = 2 } - chk := chunk.NewChunkFromPoolWithCapacity(tableInfo.GetFieldSlice(), rowCap) - result.AddPostFlushFunc(func() { - chk.Destroy(rowCap, tableInfo.GetFieldSlice()) - }) + chk, release := common.NewRowsChunk(tableInfo.GetFieldSlice(), rowCap) + result.AddPostFlushFunc(release) columns := tableInfo.GetColumns() switch msg.Type { case DMLTypeDelete: From 096fd65551d688c27aba64680f9f571d59d62f40 Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 12:20:55 +0800 Subject: [PATCH 3/7] introduce pacer --- cmd/consumer/conductor/conductor.go | 236 +++++------------------ cmd/consumer/conductor/conductor_test.go | 180 +++++++++-------- cmd/consumer/conductor/pacer.go | 138 +++++++++++++ 3 files changed, 284 insertions(+), 270 deletions(-) create mode 100644 cmd/consumer/conductor/pacer.go diff --git a/cmd/consumer/conductor/conductor.go b/cmd/consumer/conductor/conductor.go index dffa367af1..5d41ab893e 100644 --- a/cmd/consumer/conductor/conductor.go +++ b/cmd/consumer/conductor/conductor.go @@ -20,7 +20,6 @@ import ( "cmp" "container/heap" "context" - "math" "slices" "sort" "sync" @@ -63,13 +62,6 @@ type waitingDML struct { pending *simple.PendingMessage partition int32 offset int64 - bytes int64 -} - -type queuedDML struct { - row *event.DMLEvent - partition int32 - bytes int64 } const ( @@ -77,15 +69,6 @@ const ( roundRows = 1024 // roundBytes bounds the encoded bytes handed to the writer in one round. roundBytes = 2 << 20 - // maxTotalPendingBytes targets the aggregate per-partition pause threshold - // across all partitions of a partitioned source. - maxTotalPendingBytes int64 = 128 << 20 - // maxPartitionPauseBytes caps any single partition's buffer before pausing. - maxPartitionPauseBytes int64 = 8 << 20 - // minPartitionPauseBytes sets the floor for each partition's pause threshold. - minPartitionPauseBytes int64 = 1 << 20 - // dmlEventOverheadBytes approximates per-event metadata beyond row chunk bytes. - dmlEventOverheadBytes int64 = 512 // progressLogInterval controls how often consumer progress and throughput are logged. progressLogInterval = 10 * time.Second ) @@ -99,24 +82,13 @@ type Conductor struct { schemas *codecCommon.TableInfoProvider notifier source.SchemaNotifier - pauser source.Pauser + pacer *pacer // decoder assembles woken Simple DMLs serially via DecodePending. decoder *decode.Group // confirmable wakes the confirm goroutine when positions or checkpoint advance. confirmable chan struct{} - // partitionWatermarks holds each partition's resolved timestamp; watermark is - // their global minimum once every partition has reported. - partitionWatermarks []uint64 - partitionPendingBytes []int64 - pausedPartitions []bool - pausedCount int - queuedDMLBytes int64 - partitionPauseBytes int64 - partitionResumeBytes int64 - watermark uint64 - // pendingDML indexes all buffered per-table queues; readyHeap holds only // queues whose head row is not blocked behind pendingDDL (ordered by CommitTs). pendingDML map[int64]*tableQueue @@ -133,32 +105,19 @@ type Conductor struct { // New creates a conductor driven by reader metadata, decoder schema state, and // pending-DML assembly. func New(reader source.Reader, schemas *codecCommon.TableInfoProvider, decoder *decode.Group) *Conductor { - partitions := reader.Partitions() - var pauseBytes, resumeBytes int64 - if partitions > 1 { - pauseBytes = min(maxPartitionPauseBytes, max(minPartitionPauseBytes, maxTotalPendingBytes/int64(partitions))) - resumeBytes = pauseBytes / 2 - } c := &Conductor{ - schemas: schemas, - decoder: decoder, - confirmable: make(chan struct{}, 1), - positions: make(map[int32][]sourcePosition), - partitionWatermarks: make([]uint64, partitions), - partitionPendingBytes: make([]int64, partitions), - pausedPartitions: make([]bool, partitions), - partitionPauseBytes: pauseBytes, - partitionResumeBytes: resumeBytes, - pendingDML: make(map[int64]*tableQueue), - waiting: make(map[waitingSchemaKey][]waitingDML), + schemas: schemas, + pacer: newPacer(reader), + decoder: decoder, + confirmable: make(chan struct{}, 1), + positions: make(map[int32][]sourcePosition), + pendingDML: make(map[int64]*tableQueue), + waiting: make(map[waitingSchemaKey][]waitingDML), } if notifier, ok := reader.(source.SchemaNotifier); ok { c.notifier = notifier } - if pauser, ok := reader.(source.Pauser); ok { - c.pauser = pauser - } return c } @@ -211,7 +170,7 @@ func (c *Conductor) run(ctx context.Context, tasks <-chan *decode.Future, w *wri } return err } - c.syncPartitionPacing() + c.syncPacing() c.observeCheckpoint(c.confirmCheckpoint(w.Checkpoint())) c.recordPosition(marker, future.Payload) @@ -240,16 +199,15 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti zap.Float64("bytesPerSec", bytesPerSec), zap.Int64("totalRows", outRows), zap.Int64("totalBytes", inBytes), - zap.Uint64("watermark", c.watermark), + zap.Uint64("watermark", c.pacer.watermark()), zap.Uint64("effectiveWatermark", c.effectiveWatermark()), zap.Uint64("checkpoint", checkpoint), zap.Int("pendingDMLTables", len(c.pendingDML)), - zap.Int64("queuedDMLBytes", c.queuedDMLBytes), zap.Int("pendingDDL", len(c.pendingDDL)), zap.Int("pendingDecode", c.waitingCount), } - if c.pausedCount > 0 { - fields = append(fields, zap.Int("pausedPartitions", c.pausedCount)) + if c.pacer.pausedCount > 0 { + fields = append(fields, zap.Int("pausedPartitions", c.pacer.pausedCount)) } if inFlightEvents != 0 { fields = append(fields, @@ -265,15 +223,7 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti if c.minWaitingTs != 0 { fields = append(fields, zap.Uint64("minPendingDecode", c.minWaitingTs)) } - if len(c.partitionWatermarks) > 0 { - minPartition := 0 - minWatermark := c.partitionWatermarks[0] - for i, resolved := range c.partitionWatermarks[1:] { - if resolved < minWatermark { - minPartition = i + 1 - minWatermark = resolved - } - } + if minPartition, minWatermark, ok := c.pacer.min(); ok { fields = append(fields, zap.Int("minWatermarkPartition", minPartition), zap.Uint64("minPartitionWatermark", minWatermark)) @@ -294,19 +244,13 @@ func (c *Conductor) accept(future *decode.Future) uint64 { for _, e := range future.Events { marker = max(marker, c.acceptEvent(e, future.Payload)) } - marker = max(marker, c.acceptPending(future.Pending, future.Payload, future.Bytes)) + marker = max(marker, c.acceptPending(future.Pending, future.Payload)) c.releaseSchemas() return marker } -func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload, payloadBytes int64) uint64 { - var ( - marker uint64 - perItemBytes int64 - ) - if len(items) > 0 { - perItemBytes = max(payloadBytes/int64(len(items)), dmlEventOverheadBytes) - } +func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload) uint64 { + var marker uint64 for _, pending := range items { if released := c.schemas.ReleasedWatermark(); released != 0 && pending.CommitTs <= released { continue @@ -314,7 +258,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc marker = max(marker, pending.CommitTs) if tableInfo := c.schemas.Read(pending.Schema, pending.Table, pending.SchemaVersion); tableInfo != nil { - c.queueDML(c.decoder.DecodePending(pending, tableInfo, payload.Partition, payload.Offset), payload.Partition) + c.queueDML(c.decoder.DecodePending(pending, tableInfo, payload.Partition, payload.Offset)) continue } @@ -327,9 +271,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc pending: pending, partition: payload.Partition, offset: payload.Offset, - bytes: perItemBytes, }) - c.addPartitionBytes(payload.Partition, perItemBytes) c.waitingCount++ if pending.CommitTs != 0 && (c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs) { c.minWaitingTs = pending.CommitTs @@ -357,8 +299,7 @@ func (c *Conductor) wakeWaiting(info *common.TableInfo) { delete(c.waiting, key) c.waitingCount -= len(items) for _, item := range items { - c.subPartitionBytes(item.partition, item.bytes) - c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset), item.partition) + c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset)) } c.recomputeMinWaiting() } @@ -378,7 +319,7 @@ func (c *Conductor) recomputeMinWaiting() { func (c *Conductor) acceptEvent(e event.Event, payload *source.Payload) uint64 { switch e := e.(type) { case *event.DMLEvent: - c.queueDML(e, payload.Partition) + c.queueDML(e) return e.CommitTs case *event.ResolvedEvent: c.advanceWatermark(e.ResolvedTs, payload.Partition) @@ -434,7 +375,7 @@ func (c *Conductor) recordPosition(marker uint64, payload *source.Payload) { // tableQueue holds one table's pending DMLs ordered by (CommitTs, dmlRowOrder). type tableQueue struct { tableID int64 - rows []queuedDML + rows []*event.DMLEvent dropped int // heapIndex records the index in readyHeap, or -1 when blocked behind pendingDDL. heapIndex int @@ -446,11 +387,11 @@ func (h tableHeap) Len() int { return len(h) } func (h tableHeap) Less(i, j int) bool { a, b := h[i], h[j] - if a.rows[0].row.CommitTs != b.rows[0].row.CommitTs { - return a.rows[0].row.CommitTs < b.rows[0].row.CommitTs + if a.rows[0].CommitTs != b.rows[0].CommitTs { + return a.rows[0].CommitTs < b.rows[0].CommitTs } - if oa, ob := dmlRowOrder(a.rows[0].row), dmlRowOrder(b.rows[0].row); oa != ob { + if oa, ob := dmlRowOrder(a.rows[0]), dmlRowOrder(b.rows[0]); oa != ob { return oa < ob } @@ -512,13 +453,13 @@ func dmlBefore(a, b *event.DMLEvent) bool { return dmlRowOrder(a) < dmlRowOrder(b) } -func insertDML(rows []queuedDML, item queuedDML) ([]queuedDML, bool) { - if len(rows) == 0 || !dmlBefore(item.row, rows[len(rows)-1].row) { +func insertDML(rows []*event.DMLEvent, item *event.DMLEvent) ([]*event.DMLEvent, bool) { + if len(rows) == 0 || !dmlBefore(item, rows[len(rows)-1]) { return append(rows, item), len(rows) == 0 } index := sort.Search(len(rows), func(i int) bool { - return dmlBefore(item.row, rows[i].row) + return dmlBefore(item, rows[i]) }) return slices.Insert(rows, index, item), index == 0 @@ -529,7 +470,7 @@ func (c *Conductor) rowBlockedByDDL(item *event.DMLEvent) bool { } func (c *Conductor) syncTable(q *tableQueue) { - blocked := c.rowBlockedByDDL(q.rows[0].row) + blocked := c.rowBlockedByDDL(q.rows[0]) inHeap := q.heapIndex >= 0 if blocked == !inHeap { if !blocked { @@ -547,24 +488,14 @@ func (c *Conductor) syncTable(q *tableQueue) { } // queueDML records a decoded row until the writer can accept it. -func (c *Conductor) queueDML(item *event.DMLEvent, partition int32) { - bytes := dmlMemoryBytes(item) - c.queuedDMLBytes += bytes - c.addPartitionBytes(partition, bytes) - - entry := queuedDML{ - row: item, - partition: partition, - bytes: bytes, - } - +func (c *Conductor) queueDML(item *event.DMLEvent) { tableID := item.PhysicalTableID q := c.pendingDML[tableID] if q == nil { q = &tableQueue{ tableID: tableID, - rows: []queuedDML{entry}, + rows: []*event.DMLEvent{item}, heapIndex: -1, } c.pendingDML[tableID] = q @@ -577,7 +508,7 @@ func (c *Conductor) queueDML(item *event.DMLEvent, partition int32) { // A source may deliver an earlier timestamp or split DELETE before resolution. var headChanged bool - q.rows, headChanged = insertDML(q.rows, entry) + q.rows, headChanged = insertDML(q.rows, item) if headChanged { c.syncTable(q) } @@ -597,7 +528,7 @@ func (c *Conductor) queueDDL(ddlEvent *event.DDLEvent) { // Rows already buffered above the DDL commit timestamp wait for it. var blocked []*tableQueue for _, q := range c.readyHeap { - if q.rows[0].row.CommitTs > ts { + if q.rows[0].CommitTs > ts { blocked = append(blocked, q) } } @@ -613,7 +544,7 @@ func (c *Conductor) nextReady() (*event.DDLEvent, *event.DMLEvent) { if len(c.pendingDDL) != 0 { head := c.pendingDDL[0] if head.GetCommitTs() <= c.effectiveWatermark() && - (len(c.readyHeap) == 0 || c.readyHeap[0].rows[0].row.CommitTs > head.GetCommitTs()) { + (len(c.readyHeap) == 0 || c.readyHeap[0].rows[0].CommitTs > head.GetCommitTs()) { return head, nil } } @@ -627,7 +558,7 @@ func (c *Conductor) nextDML() *event.DMLEvent { return nil } - head := c.readyHeap[0].rows[0].row + head := c.readyHeap[0].rows[0] if head.CommitTs > c.effectiveWatermark() { return nil } @@ -637,12 +568,9 @@ func (c *Conductor) nextDML() *event.DMLEvent { func (c *Conductor) popDML(row *event.DMLEvent) { q := c.pendingDML[row.PhysicalTableID] - entry := q.rows[0] - q.rows[0] = queuedDML{} + q.rows[0] = nil q.rows = q.rows[1:] q.dropped++ - c.queuedDMLBytes -= entry.bytes - c.subPartitionBytes(entry.partition, entry.bytes) if len(q.rows) == 0 { if q.heapIndex >= 0 { @@ -668,7 +596,7 @@ func (c *Conductor) popDDL() *event.DDLEvent { } for _, q := range c.pendingDML { - if q.heapIndex < 0 && !c.rowBlockedByDDL(q.rows[0].row) { + if q.heapIndex < 0 && !c.rowBlockedByDDL(q.rows[0]) { heap.Push(&c.readyHeap, q) } } @@ -697,10 +625,10 @@ func (c *Conductor) drainTransaction(row *event.DMLEvent, w *writer.Writer) (int return rows, bytes } q := c.pendingDML[tableID] - if q == nil || q.heapIndex < 0 || q.rows[0].row.CommitTs != commitTs { + if q == nil || q.heapIndex < 0 || q.rows[0].CommitTs != commitTs { return rows, bytes } - row = q.rows[0].row + row = q.rows[0] } } @@ -746,11 +674,12 @@ func (c *Conductor) flush(ctx context.Context, w *writer.Writer) error { } func (c *Conductor) effectiveWatermark() uint64 { + watermark := c.pacer.watermark() if c.minWaitingTs != 0 { - return min(c.watermark, c.minWaitingTs-1) + return min(watermark, c.minWaitingTs-1) } - return c.watermark + return watermark } func (c *Conductor) releaseSchemas() { @@ -759,32 +688,18 @@ func (c *Conductor) releaseSchemas() { } } -// advanceWatermark records resolved progress. Sources without partitions -// publish a global watermark; partitioned sources advance only when every -// partition has been resolved. +// advanceWatermark records resolved progress. func (c *Conductor) advanceWatermark(ts uint64, partition int32) { - if len(c.partitionWatermarks) == 0 { - c.watermark = max(c.watermark, ts) - c.releaseSchemas() - return - } - - if int(partition) >= len(c.partitionWatermarks) { - return - } - - c.partitionWatermarks[partition] = max(c.partitionWatermarks[partition], ts) + c.pacer.advance(partition, ts) + c.releaseSchemas() +} - watermark := uint64(math.MaxUint64) - for _, resolved := range c.partitionWatermarks { - if resolved == 0 { - return - } - watermark = min(watermark, resolved) +func (c *Conductor) syncPacing() { + var headDDLTs uint64 + if len(c.pendingDDL) > 0 { + headDDLTs = c.pendingDDL[0].GetCommitTs() } - - c.watermark = max(c.watermark, watermark) - c.releaseSchemas() + c.pacer.sync(headDDLTs, c.minWaitingTs) } // source.Payload progress can pass decoded events still awaiting delivery. Publish @@ -792,7 +707,7 @@ func (c *Conductor) advanceWatermark(ts uint64, partition int32) { func (c *Conductor) advanceWriter(w *writer.Writer) { var pending uint64 if len(c.readyHeap) != 0 { - pending = earliest(pending, c.readyHeap[0].rows[0].row.CommitTs) + pending = earliest(pending, c.readyHeap[0].rows[0].CommitTs) } if len(c.pendingDDL) != 0 { pending = earliest(pending, c.pendingDDL[0].GetCommitTs()) @@ -801,57 +716,6 @@ func (c *Conductor) advanceWriter(w *writer.Writer) { w.Advance(c.effectiveWatermark(), pending) } -func dmlMemoryBytes(item *event.DMLEvent) int64 { - return dmlEventOverheadBytes + item.Rows.MemoryUsage() -} - -func (c *Conductor) addPartitionBytes(partition int32, bytes int64) { - if int(partition) < len(c.partitionPendingBytes) { - c.partitionPendingBytes[partition] += bytes - } -} - -func (c *Conductor) subPartitionBytes(partition int32, bytes int64) { - if int(partition) < len(c.partitionPendingBytes) { - c.partitionPendingBytes[partition] -= bytes - } -} - -// syncPartitionPacing pauses partitions whose resolved progress leads the slowest -// partition and whose buffered bytes exceed the per-partition threshold, and -// resumes partitions when they drain or are needed to advance progress. -func (c *Conductor) syncPartitionPacing() { - if c.pauser == nil || len(c.partitionWatermarks) <= 1 { - return - } - - minWatermark := slices.Min(c.partitionWatermarks) - var toPause, toResume []int32 - for p, resolved := range c.partitionWatermarks { - ahead := resolved > minWatermark && (c.minWaitingTs == 0 || resolved >= c.minWaitingTs) - if c.pausedPartitions[p] { - if !ahead || c.partitionPendingBytes[p] <= c.partitionResumeBytes { - c.pausedPartitions[p] = false - c.pausedCount-- - toResume = append(toResume, int32(p)) - } - continue - } - if ahead && c.partitionPendingBytes[p] >= c.partitionPauseBytes { - c.pausedPartitions[p] = true - c.pausedCount++ - toPause = append(toPause, int32(p)) - } - } - - if len(toResume) > 0 { - c.pauser.Resume(toResume) - } - if len(toPause) > 0 { - c.pauser.Pause(toPause) - } -} - func (c *Conductor) confirmCheckpoint(checkpoint uint64) uint64 { if len(c.pendingDDL) == 0 { return checkpoint diff --git a/cmd/consumer/conductor/conductor_test.go b/cmd/consumer/conductor/conductor_test.go index 363472e649..1766e790f0 100644 --- a/cmd/consumer/conductor/conductor_test.go +++ b/cmd/consumer/conductor/conductor_test.go @@ -40,6 +40,7 @@ import ( "github.com/pingcap/tidb/pkg/types" "github.com/pingcap/tidb/pkg/util/chunk" "github.com/stretchr/testify/require" + "github.com/tikv/client-go/v2/oracle" ) type mockNotifierReader struct { @@ -472,8 +473,8 @@ func TestConductorEffectiveWatermarkPendingDecode(t *testing.T) { q := c.pendingDML[t1Info.TableName.TableID] require.NotNil(t, q) require.Len(t, q.rows, 2) - require.Equal(t, uint64(200), q.rows[0].row.CommitTs) - q.rows[0].row.AddPostFlushFunc(record("t1:dml@200")) + require.Equal(t, uint64(200), q.rows[0].CommitTs) + q.rows[0].AddPostFlushFunc(record("t1:dml@200")) require.NoError(t, c.flush(t.Context(), w)) require.NoError(t, w.Drain(t.Context())) @@ -926,13 +927,11 @@ type mockPauserReader struct { *sourcemock.MockPauser } -func newTestPauseDML(tableID int64, info *common.TableInfo, commitTs uint64) *event.DMLEvent { - dml := newInsertDML(info, commitTs, 1, 2) - dml.PhysicalTableID = tableID - return dml +func tsAt(sec int64) uint64 { + return oracle.ComposeTS(sec*1000, 0) } -func TestConductorPartitionPacingAndResumeOnDrain(t *testing.T) { +func TestConductorPacingStartupAndWatermarkLead(t *testing.T) { ctrl := gomock.NewController(t) mr := sourcemock.NewMockReader(ctrl) mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() @@ -940,53 +939,52 @@ func TestConductorPartitionPacingAndResumeOnDrain(t *testing.T) { gomock.InOrder( mp.EXPECT().Pause([]int32{0}).Times(1), mp.EXPECT().Resume([]int32{0}).Times(1), + mp.EXPECT().Pause([]int32{0}).Times(1), + mp.EXPECT().Resume([]int32{0}).Times(1), ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) - c.partitionPauseBytes = 2000 - c.partitionResumeBytes = 1000 - w := startBlackholeWriter(t) - defer func() { - require.NoError(t, w.Drain(t.Context())) - }() - - info := newTestTableInfo(1, "t1", 100, "id", "v") - // Queue a DDL at 150 so DMLs at 200 on partition 0 stay buffered behind it. - ddl := newTestAlterDDL(info, 150, "ALTER TABLE test.t1 ADD COLUMN c INT") - c.acceptEvent(ddl, &source.Payload{Partition: 0}) - // Partition 2 is the lagging partition (resolved == 0 == minWatermark): high buffered bytes must NOT pause it. - for range 5 { - c.acceptEvent(newTestPauseDML(1, info, 110), &source.Payload{Partition: 2}) - } - c.advanceWatermark(100, 1) - c.syncPartitionPacing() - require.False(t, c.pausedPartitions[2]) - require.False(t, c.pausedPartitions[1]) - - // Partition 0 exceeds partitionPauseBytes and leads minWatermark (partition 2 at 0) -> pauses partition 0. - c.advanceWatermark(250, 0) - for range 5 { - c.acceptEvent(newTestPauseDML(1, info, 200), &source.Payload{Partition: 0}) - } - require.GreaterOrEqual(t, c.partitionPendingBytes[0], c.partitionPauseBytes) - c.syncPartitionPacing() - require.True(t, c.pausedPartitions[0]) - require.False(t, c.pausedPartitions[1]) - require.False(t, c.pausedPartitions[2]) - require.Equal(t, 1, c.pausedCount) - - // Lagging partition catches up past 200 and buffered events flush -> partition 0 drains and resumes. - c.advanceWatermark(220, 1) - c.advanceWatermark(220, 2) - require.NoError(t, c.flush(t.Context(), w)) - c.syncPartitionPacing() - require.LessOrEqual(t, c.partitionPendingBytes[0], c.partitionResumeBytes) - require.False(t, c.pausedPartitions[0]) - require.Zero(t, c.pausedCount) + // Startup (minWatermark == 0): stream 0 at 10s pauses while stream 2 has not reported. + c.advanceWatermark(tsAt(10), 0) + c.syncPacing() + require.True(t, c.pacer.paused[0]) + require.False(t, c.pacer.paused[1]) + require.False(t, c.pacer.paused[2]) + require.Equal(t, 1, c.pacer.pausedCount) + + // Once all streams report 10s, stream 0 resumes. + c.advanceWatermark(tsAt(10), 1) + c.advanceWatermark(tsAt(10), 2) + c.syncPacing() + require.False(t, c.pacer.paused[0]) + require.Zero(t, c.pacer.pausedCount) + + // Lead of 4s (< 5s) stays unpaused. + c.advanceWatermark(tsAt(14), 0) + c.syncPacing() + require.False(t, c.pacer.paused[0]) + + // Lead of 5s (>= 5s) pauses stream 0. + c.advanceWatermark(tsAt(15), 0) + c.syncPacing() + require.True(t, c.pacer.paused[0]) + + // Slow streams reach 12s (lead = 3s > 2s): hysteresis keeps stream 0 paused. + c.advanceWatermark(tsAt(12), 1) + c.advanceWatermark(tsAt(12), 2) + c.syncPacing() + require.True(t, c.pacer.paused[0]) + + // Slow streams reach 13s (lead = 2s <= 2s): stream 0 resumes. + c.advanceWatermark(tsAt(13), 1) + c.advanceWatermark(tsAt(13), 2) + c.syncPacing() + require.False(t, c.pacer.paused[0]) + require.Zero(t, c.pacer.pausedCount) } -func TestConductorPartitionResumesWhenMinWatermarkCatchesUp(t *testing.T) { +func TestConductorPacingDDLBarrierAndMinWatermarkCatchup(t *testing.T) { ctrl := gomock.NewController(t) mr := sourcemock.NewMockReader(ctrl) mr.EXPECT().Partitions().Return(int32(2)).AnyTimes() @@ -994,30 +992,50 @@ func TestConductorPartitionResumesWhenMinWatermarkCatchesUp(t *testing.T) { gomock.InOrder( mp.EXPECT().Pause([]int32{0}).Times(1), mp.EXPECT().Resume([]int32{0}).Times(1), + mp.EXPECT().Pause([]int32{0}).Times(1), + mp.EXPECT().Resume([]int32{0}).Times(1), ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) - c.partitionPauseBytes = 2000 - c.partitionResumeBytes = 1000 + w := startBlackholeWriter(t) + defer func() { + require.NoError(t, w.Drain(t.Context())) + }() info := newTestTableInfo(1, "t1", 100, "id", "v") - c.advanceWatermark(100, 1) - c.advanceWatermark(200, 0) - for range 5 { - c.acceptEvent(newTestPauseDML(1, info, 200), &source.Payload{Partition: 0}) - } - c.syncPartitionPacing() - require.True(t, c.pausedPartitions[0]) - - // Partition 1 catches up to 200 without draining partition 0; minWatermark == 200 forces resume. - c.advanceWatermark(200, 1) - require.Greater(t, c.partitionPendingBytes[0], c.partitionResumeBytes) - c.syncPartitionPacing() - require.False(t, c.pausedPartitions[0]) - require.Zero(t, c.pausedCount) + // Queue a DDL at 11s; stream 0 advances to 12s while stream 1 is at 10s + // (lead = 2s < 5s, but resolved > headDDLTs so stream 0 pauses). + c.acceptEvent(newTestAlterDDL(info, tsAt(11), "ALTER TABLE test.t1 ADD COLUMN c INT"), &source.Payload{Partition: 0}) + c.advanceWatermark(tsAt(10), 1) + c.advanceWatermark(tsAt(12), 0) + c.syncPacing() + require.True(t, c.pacer.paused[0]) + require.Equal(t, 1, c.pacer.pausedCount) + + // Even before flushing DDL, if stream 1 catches up to 12s, !ahead resumes stream 0 (no deadlock). + c.advanceWatermark(tsAt(12), 1) + c.syncPacing() + require.False(t, c.pacer.paused[0]) + require.Zero(t, c.pacer.pausedCount) + + require.NoError(t, c.flush(t.Context(), w)) + require.Empty(t, c.pendingDDL) + + // Queue a second DDL at 13s; stream 0 at 14s pauses, then resumes after stream 1 reaches 13s and flush executes the DDL. + c.acceptEvent(newTestAlterDDL(info, tsAt(13), "ALTER TABLE test.t1 ADD COLUMN d INT"), &source.Payload{Partition: 0}) + c.advanceWatermark(tsAt(14), 0) + c.syncPacing() + require.True(t, c.pacer.paused[0]) + + c.advanceWatermark(tsAt(13), 1) + require.NoError(t, c.flush(t.Context(), w)) + require.Empty(t, c.pendingDDL) + c.syncPacing() + require.False(t, c.pacer.paused[0]) + require.Zero(t, c.pacer.pausedCount) } -func TestConductorPartitionResumesBehindMinWaitingTs(t *testing.T) { +func TestConductorPacingResumesBehindMinWaitingTs(t *testing.T) { ctrl := gomock.NewController(t) mr := sourcemock.NewMockReader(ctrl) mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() @@ -1028,29 +1046,23 @@ func TestConductorPartitionResumesBehindMinWaitingTs(t *testing.T) { ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) - c.partitionPauseBytes = 2000 - c.partitionResumeBytes = 1000 - info := newTestTableInfo(1, "t1", 100, "id", "v") - c.advanceWatermark(10, 2) - c.advanceWatermark(100, 1) - c.advanceWatermark(150, 0) - for range 5 { - c.acceptEvent(newTestPauseDML(1, info, 140), &source.Payload{Partition: 0}) - } - c.syncPartitionPacing() - require.True(t, c.pausedPartitions[0]) + c.advanceWatermark(tsAt(10), 2) + c.advanceWatermark(tsAt(12), 1) + c.advanceWatermark(tsAt(16), 0) + c.syncPacing() + require.True(t, c.pacer.paused[0]) - // A Simple DML waiting for schema at CommitTs=200 arrives on partition 1; - // partition 0 is only at 150 (< 200) and may hold that schema DDL, so it resumes. + // A Simple DML waiting for schema at 20s arrives on stream 1; + // stream 0 is only at 16s (< 20s) and may hold that schema DDL, so it resumes. c.acceptPending([]*simple.PendingMessage{{ Schema: "test", Table: "t2", SchemaVersion: 200, - CommitTs: 200, - }}, &source.Payload{Partition: 1, Offset: 1}, 512) - require.Equal(t, uint64(200), c.minWaitingTs) - c.syncPartitionPacing() - require.False(t, c.pausedPartitions[0]) - require.Zero(t, c.pausedCount) + CommitTs: tsAt(20), + }}, &source.Payload{Partition: 1, Offset: 1}) + require.Equal(t, tsAt(20), c.minWaitingTs) + c.syncPacing() + require.False(t, c.pacer.paused[0]) + require.Zero(t, c.pacer.pausedCount) } diff --git a/cmd/consumer/conductor/pacer.go b/cmd/consumer/conductor/pacer.go new file mode 100644 index 0000000000..fee06f7b48 --- /dev/null +++ b/cmd/consumer/conductor/pacer.go @@ -0,0 +1,138 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package conductor + +import ( + "math" + "slices" + "time" + + "github.com/pingcap/ticdc/cmd/consumer/source" + "github.com/tikv/client-go/v2/oracle" +) + +const ( + // pauseWatermarkLead pauses streams that run this far ahead of the slowest stream. + pauseWatermarkLead = 5 * time.Second + // resumeWatermarkLead resumes paused streams once the slowest stream catches up within this margin. + resumeWatermarkLead = 2 * time.Second +) + +// pacer tracks per-stream resolved watermarks and pauses ahead streams +// when they run far past the slowest stream or a pending DDL barrier. +type pacer struct { + pauser source.Pauser + watermarks []uint64 + paused []bool + pausedCount int + global uint64 + pauseLeadMs int64 + resumeLeadMs int64 +} + +func newPacer(reader source.Reader) *pacer { + count := reader.Partitions() + p := &pacer{ + watermarks: make([]uint64, count), + paused: make([]bool, count), + pauseLeadMs: pauseWatermarkLead.Milliseconds(), + resumeLeadMs: resumeWatermarkLead.Milliseconds(), + } + if pauser, ok := reader.(source.Pauser); ok { + p.pauser = pauser + } + return p +} + +// advance records resolved progress for one stream and returns the global watermark. +func (p *pacer) advance(id int32, ts uint64) uint64 { + if len(p.watermarks) == 0 { + p.global = max(p.global, ts) + return p.global + } + + if int(id) >= len(p.watermarks) { + return p.global + } + + p.watermarks[id] = max(p.watermarks[id], ts) + + minTs := uint64(math.MaxUint64) + for _, resolved := range p.watermarks { + if resolved == 0 { + return p.global + } + minTs = min(minTs, resolved) + } + + p.global = max(p.global, minTs) + return p.global +} + +func (p *pacer) watermark() uint64 { + return p.global +} + +func (p *pacer) min() (int, uint64, bool) { + if len(p.watermarks) == 0 { + return 0, 0, false + } + minIdx := 0 + minTs := p.watermarks[0] + for i, resolved := range p.watermarks[1:] { + if resolved < minTs { + minIdx = i + 1 + minTs = resolved + } + } + return minIdx, minTs, true +} + +// sync pauses ahead streams that lead the slowest stream or have crossed headDDLTs, +// while never pausing the slowest stream(s) or streams needed to deliver pending schemas. +func (p *pacer) sync(headDDLTs, minWaitingTs uint64) { + if p.pauser == nil || len(p.watermarks) <= 1 { + return + } + + minWatermark := slices.Min(p.watermarks) + minPhysical := oracle.ExtractPhysical(minWatermark) + var toPause, toResume []int32 + for id, resolved := range p.watermarks { + ahead := resolved > minWatermark && (minWaitingTs == 0 || resolved >= minWaitingTs) + behindDDL := headDDLTs != 0 && resolved > headDDLTs + leadMs := oracle.ExtractPhysical(resolved) - minPhysical + if p.paused[id] { + if !ahead || (minWatermark != 0 && !behindDDL && leadMs <= p.resumeLeadMs) { + p.paused[id] = false + p.pausedCount-- + toResume = append(toResume, int32(id)) + } + continue + } + if ahead && (minWatermark == 0 || behindDDL || leadMs >= p.pauseLeadMs) { + p.paused[id] = true + p.pausedCount++ + toPause = append(toPause, int32(id)) + } + } + + if len(toResume) > 0 { + p.pauser.Resume(toResume) + } + if len(toPause) > 0 { + p.pauser.Pause(toPause) + } +} From b3f76a8d08c3d16523ba7ee1eb782106cd2bd103 Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 14:38:57 +0800 Subject: [PATCH 4/7] adjust the pacer --- cmd/consumer/conductor/conductor.go | 42 +++++--- cmd/consumer/conductor/conductor_test.go | 121 +++++++++-------------- cmd/consumer/conductor/pacer.go | 85 +++++++++------- 3 files changed, 125 insertions(+), 123 deletions(-) diff --git a/cmd/consumer/conductor/conductor.go b/cmd/consumer/conductor/conductor.go index 5d41ab893e..51974684d2 100644 --- a/cmd/consumer/conductor/conductor.go +++ b/cmd/consumer/conductor/conductor.go @@ -62,6 +62,7 @@ type waitingDML struct { pending *simple.PendingMessage partition int32 offset int64 + bytes int64 } const ( @@ -69,6 +70,8 @@ const ( roundRows = 1024 // roundBytes bounds the encoded bytes handed to the writer in one round. roundBytes = 2 << 20 + // dmlEventOverheadBytes approximates per-event metadata beyond row chunk bytes. + dmlEventOverheadBytes int64 = 512 // progressLogInterval controls how often consumer progress and throughput are logged. progressLogInterval = 10 * time.Second ) @@ -91,14 +94,16 @@ type Conductor struct { // pendingDML indexes all buffered per-table queues; readyHeap holds only // queues whose head row is not blocked behind pendingDDL (ordered by CommitTs). - pendingDML map[int64]*tableQueue - readyHeap tableHeap - pendingDDL []*event.DDLEvent + pendingDML map[int64]*tableQueue + pendingDMLBytes int64 + readyHeap tableHeap + pendingDDL []*event.DDLEvent // waiting parks Simple DMLs whose schema version has not arrived yet, // single-goroutine owned by run. waiting map[waitingSchemaKey][]waitingDML waitingCount int + waitingBytes int64 minWaitingTs uint64 } @@ -206,8 +211,8 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti zap.Int("pendingDDL", len(c.pendingDDL)), zap.Int("pendingDecode", c.waitingCount), } - if c.pacer.pausedCount > 0 { - fields = append(fields, zap.Int("pausedPartitions", c.pacer.pausedCount)) + if paused := c.pacer.pausedCount(); paused > 0 { + fields = append(fields, zap.Int("pausedPartitions", paused)) } if inFlightEvents != 0 { fields = append(fields, @@ -244,13 +249,19 @@ func (c *Conductor) accept(future *decode.Future) uint64 { for _, e := range future.Events { marker = max(marker, c.acceptEvent(e, future.Payload)) } - marker = max(marker, c.acceptPending(future.Pending, future.Payload)) + marker = max(marker, c.acceptPending(future.Pending, future.Payload, future.Bytes)) c.releaseSchemas() return marker } -func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload) uint64 { - var marker uint64 +func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload, payloadBytes int64) uint64 { + var ( + marker uint64 + perItemBytes int64 + ) + if len(items) > 0 { + perItemBytes = max(payloadBytes/int64(len(items)), dmlEventOverheadBytes) + } for _, pending := range items { if released := c.schemas.ReleasedWatermark(); released != 0 && pending.CommitTs <= released { continue @@ -271,8 +282,10 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc pending: pending, partition: payload.Partition, offset: payload.Offset, + bytes: perItemBytes, }) c.waitingCount++ + c.waitingBytes += perItemBytes if pending.CommitTs != 0 && (c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs) { c.minWaitingTs = pending.CommitTs } @@ -299,6 +312,7 @@ func (c *Conductor) wakeWaiting(info *common.TableInfo) { delete(c.waiting, key) c.waitingCount -= len(items) for _, item := range items { + c.waitingBytes -= item.bytes c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset)) } c.recomputeMinWaiting() @@ -489,6 +503,7 @@ func (c *Conductor) syncTable(q *tableQueue) { // queueDML records a decoded row until the writer can accept it. func (c *Conductor) queueDML(item *event.DMLEvent) { + c.pendingDMLBytes += dmlMemoryBytes(item) tableID := item.PhysicalTableID q := c.pendingDML[tableID] @@ -567,6 +582,7 @@ func (c *Conductor) nextDML() *event.DMLEvent { } func (c *Conductor) popDML(row *event.DMLEvent) { + c.pendingDMLBytes -= dmlMemoryBytes(row) q := c.pendingDML[row.PhysicalTableID] q.rows[0] = nil q.rows = q.rows[1:] @@ -694,12 +710,12 @@ func (c *Conductor) advanceWatermark(ts uint64, partition int32) { c.releaseSchemas() } +func dmlMemoryBytes(item *event.DMLEvent) int64 { + return dmlEventOverheadBytes + item.Rows.MemoryUsage() +} + func (c *Conductor) syncPacing() { - var headDDLTs uint64 - if len(c.pendingDDL) > 0 { - headDDLTs = c.pendingDDL[0].GetCommitTs() - } - c.pacer.sync(headDDLTs, c.minWaitingTs) + c.pacer.sync(c.pendingDMLBytes+c.waitingBytes, c.minWaitingTs) } // source.Payload progress can pass decoded events still awaiting delivery. Publish diff --git a/cmd/consumer/conductor/conductor_test.go b/cmd/consumer/conductor/conductor_test.go index 1766e790f0..567d70e200 100644 --- a/cmd/consumer/conductor/conductor_test.go +++ b/cmd/consumer/conductor/conductor_test.go @@ -40,7 +40,6 @@ import ( "github.com/pingcap/tidb/pkg/types" "github.com/pingcap/tidb/pkg/util/chunk" "github.com/stretchr/testify/require" - "github.com/tikv/client-go/v2/oracle" ) type mockNotifierReader struct { @@ -802,6 +801,8 @@ func TestConductorSimpleCrossPartitionWakeupAndPrePostSchema(t *testing.T) { require.NoError(t, c.flush(t.Context(), w)) require.NoError(t, w.Drain(t.Context())) require.Equal(t, uint64(250), w.Checkpoint()) + require.Zero(t, c.pendingDMLBytes) + require.Zero(t, c.waitingBytes) } func TestConductorDDLWakesAllMultipleTableInfos(t *testing.T) { @@ -927,11 +928,7 @@ type mockPauserReader struct { *sourcemock.MockPauser } -func tsAt(sec int64) uint64 { - return oracle.ComposeTS(sec*1000, 0) -} - -func TestConductorPacingStartupAndWatermarkLead(t *testing.T) { +func TestConductorPacingSteadyStateAndThresholdHysteresis(t *testing.T) { ctrl := gomock.NewController(t) mr := sourcemock.NewMockReader(ctrl) mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() @@ -939,52 +936,41 @@ func TestConductorPacingStartupAndWatermarkLead(t *testing.T) { gomock.InOrder( mp.EXPECT().Pause([]int32{0}).Times(1), mp.EXPECT().Resume([]int32{0}).Times(1), - mp.EXPECT().Pause([]int32{0}).Times(1), - mp.EXPECT().Resume([]int32{0}).Times(1), ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) - // Startup (minWatermark == 0): stream 0 at 10s pauses while stream 2 has not reported. - c.advanceWatermark(tsAt(10), 0) - c.syncPacing() - require.True(t, c.pacer.paused[0]) - require.False(t, c.pacer.paused[1]) - require.False(t, c.pacer.paused[2]) - require.Equal(t, 1, c.pacer.pausedCount) - - // Once all streams report 10s, stream 0 resumes. - c.advanceWatermark(tsAt(10), 1) - c.advanceWatermark(tsAt(10), 2) - c.syncPacing() - require.False(t, c.pacer.paused[0]) - require.Zero(t, c.pacer.pausedCount) - - // Lead of 4s (< 5s) stays unpaused. - c.advanceWatermark(tsAt(14), 0) + // Below pausePendingBytes: even with watermark skew (including minWatermark == 0), no stream is paused. + c.advanceWatermark(100, 0) + c.pendingDMLBytes = pausePendingBytes - 1 c.syncPacing() - require.False(t, c.pacer.paused[0]) + require.False(t, c.pacer.throttling) + require.Zero(t, c.pacer.pausedCount()) - // Lead of 5s (>= 5s) pauses stream 0. - c.advanceWatermark(tsAt(15), 0) + // At pausePendingBytes: ahead stream pauses while lagging streams stay unpaused. + c.pendingDMLBytes = pausePendingBytes c.syncPacing() + require.True(t, c.pacer.throttling) require.True(t, c.pacer.paused[0]) + require.False(t, c.pacer.paused[1]) + require.False(t, c.pacer.paused[2]) + require.Equal(t, 1, c.pacer.pausedCount()) - // Slow streams reach 12s (lead = 3s > 2s): hysteresis keeps stream 0 paused. - c.advanceWatermark(tsAt(12), 1) - c.advanceWatermark(tsAt(12), 2) + // Between resumePendingBytes and pausePendingBytes: hysteresis keeps throttling active. + c.pendingDMLBytes = resumePendingBytes + 1 c.syncPacing() + require.True(t, c.pacer.throttling) require.True(t, c.pacer.paused[0]) - // Slow streams reach 13s (lead = 2s <= 2s): stream 0 resumes. - c.advanceWatermark(tsAt(13), 1) - c.advanceWatermark(tsAt(13), 2) + // At resumePendingBytes: throttling clears and paused stream resumes. + c.pendingDMLBytes = resumePendingBytes c.syncPacing() + require.False(t, c.pacer.throttling) require.False(t, c.pacer.paused[0]) - require.Zero(t, c.pacer.pausedCount) + require.Zero(t, c.pacer.pausedCount()) } -func TestConductorPacingDDLBarrierAndMinWatermarkCatchup(t *testing.T) { +func TestConductorPacingResumesWhenMinWatermarkCatchesUp(t *testing.T) { ctrl := gomock.NewController(t) mr := sourcemock.NewMockReader(ctrl) mr.EXPECT().Partitions().Return(int32(2)).AnyTimes() @@ -992,8 +978,6 @@ func TestConductorPacingDDLBarrierAndMinWatermarkCatchup(t *testing.T) { gomock.InOrder( mp.EXPECT().Pause([]int32{0}).Times(1), mp.EXPECT().Resume([]int32{0}).Times(1), - mp.EXPECT().Pause([]int32{0}).Times(1), - mp.EXPECT().Resume([]int32{0}).Times(1), ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) @@ -1003,36 +987,25 @@ func TestConductorPacingDDLBarrierAndMinWatermarkCatchup(t *testing.T) { }() info := newTestTableInfo(1, "t1", 100, "id", "v") - // Queue a DDL at 11s; stream 0 advances to 12s while stream 1 is at 10s - // (lead = 2s < 5s, but resolved > headDDLTs so stream 0 pauses). - c.acceptEvent(newTestAlterDDL(info, tsAt(11), "ALTER TABLE test.t1 ADD COLUMN c INT"), &source.Payload{Partition: 0}) - c.advanceWatermark(tsAt(10), 1) - c.advanceWatermark(tsAt(12), 0) + c.acceptEvent(newInsertDML(info, 200, 1, 2), &source.Payload{Partition: 0}) + require.Greater(t, c.pendingDMLBytes, int64(0)) + + // Simulate high buffered memory while stream 0 leads stream 1 -> stream 0 pauses. + c.advanceWatermark(100, 1) + c.advanceWatermark(200, 0) + c.waitingBytes = pausePendingBytes c.syncPacing() require.True(t, c.pacer.paused[0]) - require.Equal(t, 1, c.pacer.pausedCount) - // Even before flushing DDL, if stream 1 catches up to 12s, !ahead resumes stream 0 (no deadlock). - c.advanceWatermark(tsAt(12), 1) + // While still throttling, stream 1 catches up to 200 -> stream 0 canAdvance becomes true and resumes immediately. + c.advanceWatermark(200, 1) c.syncPacing() require.False(t, c.pacer.paused[0]) - require.Zero(t, c.pacer.pausedCount) + require.Zero(t, c.pacer.pausedCount()) + // Flushing buffered DMLs returns pendingDMLBytes to 0. require.NoError(t, c.flush(t.Context(), w)) - require.Empty(t, c.pendingDDL) - - // Queue a second DDL at 13s; stream 0 at 14s pauses, then resumes after stream 1 reaches 13s and flush executes the DDL. - c.acceptEvent(newTestAlterDDL(info, tsAt(13), "ALTER TABLE test.t1 ADD COLUMN d INT"), &source.Payload{Partition: 0}) - c.advanceWatermark(tsAt(14), 0) - c.syncPacing() - require.True(t, c.pacer.paused[0]) - - c.advanceWatermark(tsAt(13), 1) - require.NoError(t, c.flush(t.Context(), w)) - require.Empty(t, c.pendingDDL) - c.syncPacing() - require.False(t, c.pacer.paused[0]) - require.Zero(t, c.pacer.pausedCount) + require.Zero(t, c.pendingDMLBytes) } func TestConductorPacingResumesBehindMinWaitingTs(t *testing.T) { @@ -1041,28 +1014,32 @@ func TestConductorPacingResumesBehindMinWaitingTs(t *testing.T) { mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() mp := sourcemock.NewMockPauser(ctrl) gomock.InOrder( - mp.EXPECT().Pause([]int32{0}).Times(1), - mp.EXPECT().Resume([]int32{0}).Times(1), + mp.EXPECT().Pause([]int32{0, 1}).Times(1), + mp.EXPECT().Resume([]int32{0, 1}).Times(1), ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) - c.advanceWatermark(tsAt(10), 2) - c.advanceWatermark(tsAt(12), 1) - c.advanceWatermark(tsAt(16), 0) + c.advanceWatermark(10, 2) + c.advanceWatermark(100, 1) + c.advanceWatermark(150, 0) + c.pendingDMLBytes = pausePendingBytes c.syncPacing() require.True(t, c.pacer.paused[0]) + require.True(t, c.pacer.paused[1]) + require.False(t, c.pacer.paused[2]) - // A Simple DML waiting for schema at 20s arrives on stream 1; - // stream 0 is only at 16s (< 20s) and may hold that schema DDL, so it resumes. + // A Simple DML waiting for schema at CommitTs=200 arrives on stream 1; + // streams 0 and 1 are at 150 and 100 (< 200) and may hold that schema DDL, so both resume. c.acceptPending([]*simple.PendingMessage{{ Schema: "test", Table: "t2", SchemaVersion: 200, - CommitTs: tsAt(20), - }}, &source.Payload{Partition: 1, Offset: 1}) - require.Equal(t, tsAt(20), c.minWaitingTs) + CommitTs: 200, + }}, &source.Payload{Partition: 1, Offset: 1}, 512) + require.Equal(t, uint64(200), c.minWaitingTs) c.syncPacing() require.False(t, c.pacer.paused[0]) - require.Zero(t, c.pacer.pausedCount) + require.False(t, c.pacer.paused[1]) + require.Zero(t, c.pacer.pausedCount()) } diff --git a/cmd/consumer/conductor/pacer.go b/cmd/consumer/conductor/pacer.go index fee06f7b48..14a55f80ba 100644 --- a/cmd/consumer/conductor/pacer.go +++ b/cmd/consumer/conductor/pacer.go @@ -16,39 +16,34 @@ package conductor import ( "math" - "slices" - "time" "github.com/pingcap/ticdc/cmd/consumer/source" - "github.com/tikv/client-go/v2/oracle" ) const ( - // pauseWatermarkLead pauses streams that run this far ahead of the slowest stream. - pauseWatermarkLead = 5 * time.Second - // resumeWatermarkLead resumes paused streams once the slowest stream catches up within this margin. - resumeWatermarkLead = 2 * time.Second + // pausePendingBytes enables stream pacing once buffered memory in conductor + // reaches this threshold, avoiding pause/resume churn during steady-state traffic. + pausePendingBytes int64 = 1 << 30 + // resumePendingBytes disables stream pacing once buffered memory drains to + // this threshold (hysteresis to avoid oscillation). + resumePendingBytes int64 = 512 << 20 ) -// pacer tracks per-stream resolved watermarks and pauses ahead streams -// when they run far past the slowest stream or a pending DDL barrier. +// pacer tracks per-stream resolved watermarks and pauses streams that cannot +// currently advance delivery when buffered memory exceeds high-water marks. type pacer struct { - pauser source.Pauser - watermarks []uint64 - paused []bool - pausedCount int - global uint64 - pauseLeadMs int64 - resumeLeadMs int64 + pauser source.Pauser + watermarks []uint64 + paused []bool + global uint64 + throttling bool } func newPacer(reader source.Reader) *pacer { count := reader.Partitions() p := &pacer{ - watermarks: make([]uint64, count), - paused: make([]bool, count), - pauseLeadMs: pauseWatermarkLead.Milliseconds(), - resumeLeadMs: resumeWatermarkLead.Milliseconds(), + watermarks: make([]uint64, count), + paused: make([]bool, count), } if pauser, ok := reader.(source.Pauser); ok { p.pauser = pauser @@ -56,15 +51,15 @@ func newPacer(reader source.Reader) *pacer { return p } -// advance records resolved progress for one stream and returns the global watermark. -func (p *pacer) advance(id int32, ts uint64) uint64 { +// advance records resolved progress for one stream and updates the global watermark. +func (p *pacer) advance(id int32, ts uint64) { if len(p.watermarks) == 0 { p.global = max(p.global, ts) - return p.global + return } if int(id) >= len(p.watermarks) { - return p.global + return } p.watermarks[id] = max(p.watermarks[id], ts) @@ -72,13 +67,12 @@ func (p *pacer) advance(id int32, ts uint64) uint64 { minTs := uint64(math.MaxUint64) for _, resolved := range p.watermarks { if resolved == 0 { - return p.global + return } minTs = min(minTs, resolved) } p.global = max(p.global, minTs) - return p.global } func (p *pacer) watermark() uint64 { @@ -100,31 +94,46 @@ func (p *pacer) min() (int, uint64, bool) { return minIdx, minTs, true } -// sync pauses ahead streams that lead the slowest stream or have crossed headDDLTs, -// while never pausing the slowest stream(s) or streams needed to deliver pending schemas. -func (p *pacer) sync(headDDLTs, minWaitingTs uint64) { +func (p *pacer) pausedCount() int { + count := 0 + for _, paused := range p.paused { + if paused { + count++ + } + } + return count +} + +// sync pauses streams that cannot currently advance watermark or schema wakeup +// while throttling is active, and resumes streams needed to advance progress or +// when buffered memory drains below the low-water mark. +func (p *pacer) sync(pendingBytes int64, minWaitingTs uint64) { if p.pauser == nil || len(p.watermarks) <= 1 { return } - minWatermark := slices.Min(p.watermarks) - minPhysical := oracle.ExtractPhysical(minWatermark) + if !p.throttling { + if pendingBytes < pausePendingBytes { + return + } + p.throttling = true + } else if pendingBytes <= resumePendingBytes { + p.throttling = false + } + + _, minWatermark, _ := p.min() var toPause, toResume []int32 for id, resolved := range p.watermarks { - ahead := resolved > minWatermark && (minWaitingTs == 0 || resolved >= minWaitingTs) - behindDDL := headDDLTs != 0 && resolved > headDDLTs - leadMs := oracle.ExtractPhysical(resolved) - minPhysical + canAdvance := !p.throttling || resolved == minWatermark || (minWaitingTs != 0 && resolved < minWaitingTs) if p.paused[id] { - if !ahead || (minWatermark != 0 && !behindDDL && leadMs <= p.resumeLeadMs) { + if canAdvance { p.paused[id] = false - p.pausedCount-- toResume = append(toResume, int32(id)) } continue } - if ahead && (minWatermark == 0 || behindDDL || leadMs >= p.pauseLeadMs) { + if !canAdvance { p.paused[id] = true - p.pausedCount++ toPause = append(toPause, int32(id)) } } From 12847b373fb8c140a9c7a545001db9905e4023a8 Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 14:58:53 +0800 Subject: [PATCH 5/7] refactor the consumer --- cmd/consumer/conductor/conductor.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/cmd/consumer/conductor/conductor.go b/cmd/consumer/conductor/conductor.go index 51974684d2..31ca7a9a10 100644 --- a/cmd/consumer/conductor/conductor.go +++ b/cmd/consumer/conductor/conductor.go @@ -70,8 +70,15 @@ const ( roundRows = 1024 // roundBytes bounds the encoded bytes handed to the writer in one round. roundBytes = 2 << 20 - // dmlEventOverheadBytes approximates per-event metadata beyond row chunk bytes. + // dmlEventOverheadBytes approximates per-DMLEvent heap metadata beyond + // Chunk column buffers on 64-bit (~272B DMLEvent + ~80B Chunk + 8B*cols + + // ~56B RowTypes/postFlush closure ≈ 500B at 10 columns). dmlEventOverheadBytes int64 = 512 + // waitingDMLHeapFactor scales encoded Simple payload bytes to approximate + // the Go heap footprint of parked PendingMessage maps (map[string]any). + waitingDMLHeapFactor int64 = 4 + // waitingDMLMinBytes is the lower-bound floor for one parked Simple DML. + waitingDMLMinBytes int64 = 1024 // progressLogInterval controls how often consumer progress and throughput are logged. progressLogInterval = 10 * time.Second ) @@ -260,7 +267,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc perItemBytes int64 ) if len(items) > 0 { - perItemBytes = max(payloadBytes/int64(len(items)), dmlEventOverheadBytes) + perItemBytes = max(payloadBytes/int64(len(items))*waitingDMLHeapFactor, waitingDMLMinBytes) } for _, pending := range items { if released := c.schemas.ReleasedWatermark(); released != 0 && pending.CommitTs <= released { From ffd13042c664960b3aeee024d05f86aad3692380 Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 17:22:15 +0800 Subject: [PATCH 6/7] fix simple --- cmd/consumer/conductor/conductor.go | 73 +++++++++++++++-------------- cmd/consumer/conductor/pacer.go | 45 +++++++----------- cmd/consumer/source/kafka.go | 6 --- pkg/sink/codec/simple/decoder.go | 15 ++++-- 4 files changed, 67 insertions(+), 72 deletions(-) diff --git a/cmd/consumer/conductor/conductor.go b/cmd/consumer/conductor/conductor.go index 31ca7a9a10..626d21a2c1 100644 --- a/cmd/consumer/conductor/conductor.go +++ b/cmd/consumer/conductor/conductor.go @@ -74,8 +74,8 @@ const ( // Chunk column buffers on 64-bit (~272B DMLEvent + ~80B Chunk + 8B*cols + // ~56B RowTypes/postFlush closure ≈ 500B at 10 columns). dmlEventOverheadBytes int64 = 512 - // waitingDMLHeapFactor scales encoded Simple payload bytes to approximate - // the Go heap footprint of parked PendingMessage maps (map[string]any). + // waitingDMLHeapFactor scales decompressed Simple payload bytes (PendingMessage.Bytes) + // to approximate the Go heap footprint of parked PendingMessage maps (map[string]any). waitingDMLHeapFactor int64 = 4 // waitingDMLMinBytes is the lower-bound floor for one parked Simple DML. waitingDMLMinBytes int64 = 1024 @@ -101,17 +101,17 @@ type Conductor struct { // pendingDML indexes all buffered per-table queues; readyHeap holds only // queues whose head row is not blocked behind pendingDDL (ordered by CommitTs). - pendingDML map[int64]*tableQueue - pendingDMLBytes int64 - readyHeap tableHeap - pendingDDL []*event.DDLEvent + pendingDML map[int64]*tableQueue + bufferedBytes int64 + readyHeap tableHeap + pendingDDL []*event.DDLEvent // waiting parks Simple DMLs whose schema version has not arrived yet, // single-goroutine owned by run. waiting map[waitingSchemaKey][]waitingDML waitingCount int - waitingBytes int64 minWaitingTs uint64 + maxWaitingTs uint64 } // New creates a conductor driven by reader metadata, decoder schema state, and @@ -182,7 +182,7 @@ func (c *Conductor) run(ctx context.Context, tasks <-chan *decode.Future, w *wri } return err } - c.syncPacing() + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) c.observeCheckpoint(c.confirmCheckpoint(w.Checkpoint())) c.recordPosition(marker, future.Payload) @@ -217,9 +217,8 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti zap.Int("pendingDMLTables", len(c.pendingDML)), zap.Int("pendingDDL", len(c.pendingDDL)), zap.Int("pendingDecode", c.waitingCount), - } - if paused := c.pacer.pausedCount(); paused > 0 { - fields = append(fields, zap.Int("pausedPartitions", paused)) + zap.Int64("bufferedBytes", c.bufferedBytes), + zap.Int("pausedPartitions", c.pacer.pausedCount()), } if inFlightEvents != 0 { fields = append(fields, @@ -256,19 +255,13 @@ func (c *Conductor) accept(future *decode.Future) uint64 { for _, e := range future.Events { marker = max(marker, c.acceptEvent(e, future.Payload)) } - marker = max(marker, c.acceptPending(future.Pending, future.Payload, future.Bytes)) + marker = max(marker, c.acceptPending(future.Pending, future.Payload)) c.releaseSchemas() return marker } -func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload, payloadBytes int64) uint64 { - var ( - marker uint64 - perItemBytes int64 - ) - if len(items) > 0 { - perItemBytes = max(payloadBytes/int64(len(items))*waitingDMLHeapFactor, waitingDMLMinBytes) - } +func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *source.Payload) uint64 { + var marker uint64 for _, pending := range items { if released := c.schemas.ReleasedWatermark(); released != 0 && pending.CommitTs <= released { continue @@ -280,6 +273,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc continue } + itemBytes := max(pending.Bytes*waitingDMLHeapFactor, waitingDMLMinBytes) key := waitingSchemaKey{ schema: pending.Schema, table: pending.Table, @@ -289,12 +283,17 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc pending: pending, partition: payload.Partition, offset: payload.Offset, - bytes: perItemBytes, + bytes: itemBytes, }) c.waitingCount++ - c.waitingBytes += perItemBytes - if pending.CommitTs != 0 && (c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs) { - c.minWaitingTs = pending.CommitTs + c.bufferedBytes += itemBytes + if pending.CommitTs != 0 { + if c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs { + c.minWaitingTs = pending.CommitTs + } + if pending.CommitTs > c.maxWaitingTs { + c.maxWaitingTs = pending.CommitTs + } } } @@ -319,22 +318,30 @@ func (c *Conductor) wakeWaiting(info *common.TableInfo) { delete(c.waiting, key) c.waitingCount -= len(items) for _, item := range items { - c.waitingBytes -= item.bytes + c.bufferedBytes -= item.bytes c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset)) } - c.recomputeMinWaiting() + c.recomputeWaitingBounds() } -func (c *Conductor) recomputeMinWaiting() { - var minTs uint64 +func (c *Conductor) recomputeWaitingBounds() { + var minTs, maxTs uint64 for _, items := range c.waiting { for _, item := range items { - if ts := item.pending.CommitTs; ts != 0 && (minTs == 0 || ts < minTs) { + ts := item.pending.CommitTs + if ts == 0 { + continue + } + if minTs == 0 || ts < minTs { minTs = ts } + if ts > maxTs { + maxTs = ts + } } } c.minWaitingTs = minTs + c.maxWaitingTs = maxTs } func (c *Conductor) acceptEvent(e event.Event, payload *source.Payload) uint64 { @@ -510,7 +517,7 @@ func (c *Conductor) syncTable(q *tableQueue) { // queueDML records a decoded row until the writer can accept it. func (c *Conductor) queueDML(item *event.DMLEvent) { - c.pendingDMLBytes += dmlMemoryBytes(item) + c.bufferedBytes += dmlMemoryBytes(item) tableID := item.PhysicalTableID q := c.pendingDML[tableID] @@ -589,7 +596,7 @@ func (c *Conductor) nextDML() *event.DMLEvent { } func (c *Conductor) popDML(row *event.DMLEvent) { - c.pendingDMLBytes -= dmlMemoryBytes(row) + c.bufferedBytes -= dmlMemoryBytes(row) q := c.pendingDML[row.PhysicalTableID] q.rows[0] = nil q.rows = q.rows[1:] @@ -721,10 +728,6 @@ func dmlMemoryBytes(item *event.DMLEvent) int64 { return dmlEventOverheadBytes + item.Rows.MemoryUsage() } -func (c *Conductor) syncPacing() { - c.pacer.sync(c.pendingDMLBytes+c.waitingBytes, c.minWaitingTs) -} - // source.Payload progress can pass decoded events still awaiting delivery. Publish // the earliest pending timestamp so the writer never checkpoints past it. func (c *Conductor) advanceWriter(w *writer.Writer) { diff --git a/cmd/consumer/conductor/pacer.go b/cmd/consumer/conductor/pacer.go index 14a55f80ba..cc9597fd12 100644 --- a/cmd/consumer/conductor/pacer.go +++ b/cmd/consumer/conductor/pacer.go @@ -15,17 +15,16 @@ package conductor import ( - "math" + "slices" "github.com/pingcap/ticdc/cmd/consumer/source" ) const ( - // pausePendingBytes enables stream pacing once buffered memory in conductor - // reaches this threshold, avoiding pause/resume churn during steady-state traffic. - pausePendingBytes int64 = 1 << 30 - // resumePendingBytes disables stream pacing once buffered memory drains to - // this threshold (hysteresis to avoid oscillation). + // pausePendingBytes and resumePendingBytes form a soft hysteresis band tuned + // for multi-GiB consumer pods: Pause stops new broker fetches while already-fetched + // batches in franz-go and decode queues finish draining. + pausePendingBytes int64 = 1 << 30 resumePendingBytes int64 = 512 << 20 ) @@ -63,16 +62,9 @@ func (p *pacer) advance(id int32, ts uint64) { } p.watermarks[id] = max(p.watermarks[id], ts) - - minTs := uint64(math.MaxUint64) - for _, resolved := range p.watermarks { - if resolved == 0 { - return - } - minTs = min(minTs, resolved) + if minTs := slices.Min(p.watermarks); minTs != 0 { + p.global = max(p.global, minTs) } - - p.global = max(p.global, minTs) } func (p *pacer) watermark() uint64 { @@ -105,10 +97,11 @@ func (p *pacer) pausedCount() int { } // sync pauses streams that cannot currently advance watermark or schema wakeup -// while throttling is active, and resumes streams needed to advance progress or -// when buffered memory drains below the low-water mark. -func (p *pacer) sync(pendingBytes int64, minWaitingTs uint64) { - if p.pauser == nil || len(p.watermarks) <= 1 { +// (using maxWaitingTs so streams with resolved <= maxWaitingTs stay active to +// deliver its DDL) while throttling is active, and resumes streams needed to +// advance progress or when buffered memory drains below resumePendingBytes. +func (p *pacer) sync(pendingBytes int64, maxWaitingTs uint64) { + if p.pauser == nil { return } @@ -124,17 +117,15 @@ func (p *pacer) sync(pendingBytes int64, minWaitingTs uint64) { _, minWatermark, _ := p.min() var toPause, toResume []int32 for id, resolved := range p.watermarks { - canAdvance := !p.throttling || resolved == minWatermark || (minWaitingTs != 0 && resolved < minWaitingTs) - if p.paused[id] { - if canAdvance { - p.paused[id] = false - toResume = append(toResume, int32(id)) - } + wantPause := p.throttling && resolved > minWatermark && (maxWaitingTs == 0 || resolved > maxWaitingTs) + if p.paused[id] == wantPause { continue } - if !canAdvance { - p.paused[id] = true + p.paused[id] = wantPause + if wantPause { toPause = append(toPause, int32(id)) + } else { + toResume = append(toResume, int32(id)) } } diff --git a/cmd/consumer/source/kafka.go b/cmd/consumer/source/kafka.go index 2e8e4f9196..83fa134eb9 100644 --- a/cmd/consumer/source/kafka.go +++ b/cmd/consumer/source/kafka.go @@ -111,16 +111,10 @@ func (c *kafkaReader) Partitions() int32 { } func (c *kafkaReader) Pause(ids []int32) { - if len(ids) == 0 { - return - } c.client.PauseFetchPartitions(map[string][]int32{c.topic: ids}) } func (c *kafkaReader) Resume(ids []int32) { - if len(ids) == 0 { - return - } c.client.ResumeFetchPartitions(map[string][]int32{c.topic: ids}) } diff --git a/pkg/sink/codec/simple/decoder.go b/pkg/sink/codec/simple/decoder.go index 143bf30764..4823c4e534 100644 --- a/pkg/sink/codec/simple/decoder.go +++ b/pkg/sink/codec/simple/decoder.go @@ -47,9 +47,10 @@ type Decoder struct { upstreamTiDB *sql.DB storage storeapi.Storage - value []byte - msg *message - memo *common.TableInfoProvider + value []byte + valueBytes int64 + msg *message + memo *common.TableInfoProvider } // NewDecoder returns a simple decoder, reusing storage when provided. @@ -100,6 +101,7 @@ func (d *Decoder) AddKeyValue(_, value []byte) { zap.Error(err)) } d.value = value + d.valueBytes = int64(len(value)) } // HasNext returns whether there is any event need to be consumed @@ -290,7 +292,9 @@ type PendingMessage struct { Table string SchemaVersion uint64 CommitTs uint64 - msg *message + // Bytes records the decompressed payload length before JSON/Avro unmarshaling. + Bytes int64 + msg *message } // TakePendingDML detaches the current DML message so the caller can decode it @@ -300,12 +304,15 @@ func (d *Decoder) TakePendingDML() *PendingMessage { log.Panic("invalid data for the DML event", zap.String("message", util.RedactAny(d.msg))) } msg := d.msg + valueBytes := d.valueBytes d.msg = nil + d.valueBytes = 0 return &PendingMessage{ Schema: msg.Schema, Table: msg.Table, SchemaVersion: msg.SchemaVersion, CommitTs: msg.CommitTs, + Bytes: valueBytes, msg: msg, } } From 59a5de226f7d2dd3a6b6b94700d44dbb3afa001a Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Thu, 3 Dec 2026 17:24:55 +0800 Subject: [PATCH 7/7] consumer: fix conductor tests for buffered bytes pacer Replace the removed pendingDMLBytes/waitingBytes/syncPacing references with bufferedBytes and pacer.sync, and update the pacing tests for the maxWaitingTs resume rule. --- cmd/consumer/conductor/conductor_test.go | 80 ++++++++++++------------ 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/cmd/consumer/conductor/conductor_test.go b/cmd/consumer/conductor/conductor_test.go index 567d70e200..6d9e2a4135 100644 --- a/cmd/consumer/conductor/conductor_test.go +++ b/cmd/consumer/conductor/conductor_test.go @@ -801,8 +801,7 @@ func TestConductorSimpleCrossPartitionWakeupAndPrePostSchema(t *testing.T) { require.NoError(t, c.flush(t.Context(), w)) require.NoError(t, w.Drain(t.Context())) require.Equal(t, uint64(250), w.Checkpoint()) - require.Zero(t, c.pendingDMLBytes) - require.Zero(t, c.waitingBytes) + require.Zero(t, c.bufferedBytes) } func TestConductorDDLWakesAllMultipleTableInfos(t *testing.T) { @@ -942,14 +941,14 @@ func TestConductorPacingSteadyStateAndThresholdHysteresis(t *testing.T) { // Below pausePendingBytes: even with watermark skew (including minWatermark == 0), no stream is paused. c.advanceWatermark(100, 0) - c.pendingDMLBytes = pausePendingBytes - 1 - c.syncPacing() + c.bufferedBytes = pausePendingBytes - 1 + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.False(t, c.pacer.throttling) require.Zero(t, c.pacer.pausedCount()) // At pausePendingBytes: ahead stream pauses while lagging streams stay unpaused. - c.pendingDMLBytes = pausePendingBytes - c.syncPacing() + c.bufferedBytes = pausePendingBytes + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.True(t, c.pacer.throttling) require.True(t, c.pacer.paused[0]) require.False(t, c.pacer.paused[1]) @@ -957,14 +956,14 @@ func TestConductorPacingSteadyStateAndThresholdHysteresis(t *testing.T) { require.Equal(t, 1, c.pacer.pausedCount()) // Between resumePendingBytes and pausePendingBytes: hysteresis keeps throttling active. - c.pendingDMLBytes = resumePendingBytes + 1 - c.syncPacing() + c.bufferedBytes = resumePendingBytes + 1 + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.True(t, c.pacer.throttling) require.True(t, c.pacer.paused[0]) // At resumePendingBytes: throttling clears and paused stream resumes. - c.pendingDMLBytes = resumePendingBytes - c.syncPacing() + c.bufferedBytes = resumePendingBytes + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.False(t, c.pacer.throttling) require.False(t, c.pacer.paused[0]) require.Zero(t, c.pacer.pausedCount()) @@ -988,58 +987,61 @@ func TestConductorPacingResumesWhenMinWatermarkCatchesUp(t *testing.T) { info := newTestTableInfo(1, "t1", 100, "id", "v") c.acceptEvent(newInsertDML(info, 200, 1, 2), &source.Payload{Partition: 0}) - require.Greater(t, c.pendingDMLBytes, int64(0)) + require.Greater(t, c.bufferedBytes, int64(0)) // Simulate high buffered memory while stream 0 leads stream 1 -> stream 0 pauses. c.advanceWatermark(100, 1) c.advanceWatermark(200, 0) - c.waitingBytes = pausePendingBytes - c.syncPacing() + c.bufferedBytes = pausePendingBytes + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.True(t, c.pacer.paused[0]) - // While still throttling, stream 1 catches up to 200 -> stream 0 canAdvance becomes true and resumes immediately. + // While still throttling, stream 1 catches up to 200 -> stream 0 resumes immediately. c.advanceWatermark(200, 1) - c.syncPacing() + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.False(t, c.pacer.paused[0]) require.Zero(t, c.pacer.pausedCount()) - // Flushing buffered DMLs returns pendingDMLBytes to 0. + // Flushing buffered DMLs drains all queued bytes back to 0. + c.bufferedBytes = dmlMemoryBytes(c.pendingDML[1].rows[0]) require.NoError(t, c.flush(t.Context(), w)) - require.Zero(t, c.pendingDMLBytes) + require.Zero(t, c.bufferedBytes) } -func TestConductorPacingResumesBehindMinWaitingTs(t *testing.T) { +func TestConductorPacingResumesBehindMaxWaitingTs(t *testing.T) { ctrl := gomock.NewController(t) mr := sourcemock.NewMockReader(ctrl) - mr.EXPECT().Partitions().Return(int32(3)).AnyTimes() + mr.EXPECT().Partitions().Return(int32(4)).AnyTimes() mp := sourcemock.NewMockPauser(ctrl) gomock.InOrder( - mp.EXPECT().Pause([]int32{0, 1}).Times(1), - mp.EXPECT().Resume([]int32{0, 1}).Times(1), + mp.EXPECT().Pause([]int32{0, 1, 2}).Times(1), + mp.EXPECT().Resume([]int32{1, 2}).Times(1), ) c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil) - c.advanceWatermark(10, 2) - c.advanceWatermark(100, 1) - c.advanceWatermark(150, 0) - c.pendingDMLBytes = pausePendingBytes - c.syncPacing() + c.advanceWatermark(10, 3) + c.advanceWatermark(100, 2) + c.advanceWatermark(300, 1) + c.advanceWatermark(400, 0) + c.bufferedBytes = pausePendingBytes + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) require.True(t, c.pacer.paused[0]) require.True(t, c.pacer.paused[1]) - require.False(t, c.pacer.paused[2]) - - // A Simple DML waiting for schema at CommitTs=200 arrives on stream 1; - // streams 0 and 1 are at 150 and 100 (< 200) and may hold that schema DDL, so both resume. - c.acceptPending([]*simple.PendingMessage{{ - Schema: "test", - Table: "t2", - SchemaVersion: 200, - CommitTs: 200, - }}, &source.Payload{Partition: 1, Offset: 1}, 512) + require.True(t, c.pacer.paused[2]) + require.False(t, c.pacer.paused[3]) + + // Park two Simple DMLs at CommitTs=200 and CommitTs=300: stream 1 at 300 + // (== maxWaitingTs) and stream 2 at 100 resume, while stream 0 at 400 stays paused. + c.acceptPending([]*simple.PendingMessage{ + {Schema: "test", Table: "t2", SchemaVersion: 200, CommitTs: 200, Bytes: 512}, + {Schema: "test", Table: "t3", SchemaVersion: 300, CommitTs: 300, Bytes: 512}, + }, &source.Payload{Partition: 2, Offset: 1}) require.Equal(t, uint64(200), c.minWaitingTs) - c.syncPacing() - require.False(t, c.pacer.paused[0]) + require.Equal(t, uint64(300), c.maxWaitingTs) + c.pacer.sync(c.bufferedBytes, c.maxWaitingTs) + require.True(t, c.pacer.paused[0]) require.False(t, c.pacer.paused[1]) - require.Zero(t, c.pacer.pausedCount()) + require.False(t, c.pacer.paused[2]) + require.Equal(t, 1, c.pacer.pausedCount()) }