Skip to content

Commit c9ec970

Browse files
authored
consumer,codec: bound consumer memory and size decoder chunks (#7042)
close #7043
1 parent aad4bc0 commit c9ec970

15 files changed

Lines changed: 480 additions & 99 deletions

File tree

‎cmd/consumer/conductor/conductor.go‎

Lines changed: 62 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"cmp"
2121
"container/heap"
2222
"context"
23-
"math"
2423
"slices"
2524
"sort"
2625
"sync"
@@ -63,13 +62,23 @@ type waitingDML struct {
6362
pending *simple.PendingMessage
6463
partition int32
6564
offset int64
65+
bytes int64
6666
}
6767

6868
const (
6969
// roundRows bounds the rows handed to the writer in one round.
7070
roundRows = 1024
7171
// roundBytes bounds the encoded bytes handed to the writer in one round.
7272
roundBytes = 2 << 20
73+
// dmlEventOverheadBytes approximates per-DMLEvent heap metadata beyond
74+
// Chunk column buffers on 64-bit (~272B DMLEvent + ~80B Chunk + 8B*cols +
75+
// ~56B RowTypes/postFlush closure ≈ 500B at 10 columns).
76+
dmlEventOverheadBytes int64 = 512
77+
// waitingDMLHeapFactor scales decompressed Simple payload bytes (PendingMessage.Bytes)
78+
// to approximate the Go heap footprint of parked PendingMessage maps (map[string]any).
79+
waitingDMLHeapFactor int64 = 4
80+
// waitingDMLMinBytes is the lower-bound floor for one parked Simple DML.
81+
waitingDMLMinBytes int64 = 1024
7382
// progressLogInterval controls how often consumer progress and throughput are logged.
7483
progressLogInterval = 10 * time.Second
7584
)
@@ -83,41 +92,39 @@ type Conductor struct {
8392

8493
schemas *codecCommon.TableInfoProvider
8594
notifier source.SchemaNotifier
95+
pacer *pacer
8696
// decoder assembles woken Simple DMLs serially via DecodePending.
8797
decoder *decode.Group
8898

8999
// confirmable wakes the confirm goroutine when positions or checkpoint advance.
90100
confirmable chan struct{}
91101

92-
// partitionWatermarks holds each partition's resolved timestamp; watermark is
93-
// their global minimum once every partition has reported.
94-
partitionWatermarks []uint64
95-
watermark uint64
96-
97102
// pendingDML indexes all buffered per-table queues; readyHeap holds only
98103
// queues whose head row is not blocked behind pendingDDL (ordered by CommitTs).
99-
pendingDML map[int64]*tableQueue
100-
readyHeap tableHeap
101-
pendingDDL []*event.DDLEvent
104+
pendingDML map[int64]*tableQueue
105+
bufferedBytes int64
106+
readyHeap tableHeap
107+
pendingDDL []*event.DDLEvent
102108

103109
// waiting parks Simple DMLs whose schema version has not arrived yet,
104110
// single-goroutine owned by run.
105111
waiting map[waitingSchemaKey][]waitingDML
106112
waitingCount int
107113
minWaitingTs uint64
114+
maxWaitingTs uint64
108115
}
109116

110117
// New creates a conductor driven by reader metadata, decoder schema state, and
111118
// pending-DML assembly.
112119
func New(reader source.Reader, schemas *codecCommon.TableInfoProvider, decoder *decode.Group) *Conductor {
113120
c := &Conductor{
114-
schemas: schemas,
115-
decoder: decoder,
116-
confirmable: make(chan struct{}, 1),
117-
positions: make(map[int32][]sourcePosition),
118-
partitionWatermarks: make([]uint64, reader.Partitions()),
119-
pendingDML: make(map[int64]*tableQueue),
120-
waiting: make(map[waitingSchemaKey][]waitingDML),
121+
schemas: schemas,
122+
pacer: newPacer(reader),
123+
decoder: decoder,
124+
confirmable: make(chan struct{}, 1),
125+
positions: make(map[int32][]sourcePosition),
126+
pendingDML: make(map[int64]*tableQueue),
127+
waiting: make(map[waitingSchemaKey][]waitingDML),
121128
}
122129

123130
if notifier, ok := reader.(source.SchemaNotifier); ok {
@@ -175,6 +182,7 @@ func (c *Conductor) run(ctx context.Context, tasks <-chan *decode.Future, w *wri
175182
}
176183
return err
177184
}
185+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
178186

179187
c.observeCheckpoint(c.confirmCheckpoint(w.Checkpoint()))
180188
c.recordPosition(marker, future.Payload)
@@ -203,12 +211,14 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti
203211
zap.Float64("bytesPerSec", bytesPerSec),
204212
zap.Int64("totalRows", outRows),
205213
zap.Int64("totalBytes", inBytes),
206-
zap.Uint64("watermark", c.watermark),
214+
zap.Uint64("watermark", c.pacer.watermark()),
207215
zap.Uint64("effectiveWatermark", c.effectiveWatermark()),
208216
zap.Uint64("checkpoint", checkpoint),
209217
zap.Int("pendingDMLTables", len(c.pendingDML)),
210218
zap.Int("pendingDDL", len(c.pendingDDL)),
211219
zap.Int("pendingDecode", c.waitingCount),
220+
zap.Int64("bufferedBytes", c.bufferedBytes),
221+
zap.Int("pausedPartitions", c.pacer.pausedCount()),
212222
}
213223
if inFlightEvents != 0 {
214224
fields = append(fields,
@@ -224,15 +234,7 @@ func (c *Conductor) logProgress(w *writer.Writer, inBytes int64, lastLogTime *ti
224234
if c.minWaitingTs != 0 {
225235
fields = append(fields, zap.Uint64("minPendingDecode", c.minWaitingTs))
226236
}
227-
if len(c.partitionWatermarks) > 0 {
228-
minPartition := 0
229-
minWatermark := c.partitionWatermarks[0]
230-
for i, resolved := range c.partitionWatermarks[1:] {
231-
if resolved < minWatermark {
232-
minPartition = i + 1
233-
minWatermark = resolved
234-
}
235-
}
237+
if minPartition, minWatermark, ok := c.pacer.min(); ok {
236238
fields = append(fields,
237239
zap.Int("minWatermarkPartition", minPartition),
238240
zap.Uint64("minPartitionWatermark", minWatermark))
@@ -271,6 +273,7 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc
271273
continue
272274
}
273275

276+
itemBytes := max(pending.Bytes*waitingDMLHeapFactor, waitingDMLMinBytes)
274277
key := waitingSchemaKey{
275278
schema: pending.Schema,
276279
table: pending.Table,
@@ -280,10 +283,17 @@ func (c *Conductor) acceptPending(items []*simple.PendingMessage, payload *sourc
280283
pending: pending,
281284
partition: payload.Partition,
282285
offset: payload.Offset,
286+
bytes: itemBytes,
283287
})
284288
c.waitingCount++
285-
if pending.CommitTs != 0 && (c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs) {
286-
c.minWaitingTs = pending.CommitTs
289+
c.bufferedBytes += itemBytes
290+
if pending.CommitTs != 0 {
291+
if c.minWaitingTs == 0 || pending.CommitTs < c.minWaitingTs {
292+
c.minWaitingTs = pending.CommitTs
293+
}
294+
if pending.CommitTs > c.maxWaitingTs {
295+
c.maxWaitingTs = pending.CommitTs
296+
}
287297
}
288298
}
289299

@@ -308,21 +318,30 @@ func (c *Conductor) wakeWaiting(info *common.TableInfo) {
308318
delete(c.waiting, key)
309319
c.waitingCount -= len(items)
310320
for _, item := range items {
321+
c.bufferedBytes -= item.bytes
311322
c.queueDML(c.decoder.DecodePending(item.pending, info, item.partition, item.offset))
312323
}
313-
c.recomputeMinWaiting()
324+
c.recomputeWaitingBounds()
314325
}
315326

316-
func (c *Conductor) recomputeMinWaiting() {
317-
var minTs uint64
327+
func (c *Conductor) recomputeWaitingBounds() {
328+
var minTs, maxTs uint64
318329
for _, items := range c.waiting {
319330
for _, item := range items {
320-
if ts := item.pending.CommitTs; ts != 0 && (minTs == 0 || ts < minTs) {
331+
ts := item.pending.CommitTs
332+
if ts == 0 {
333+
continue
334+
}
335+
if minTs == 0 || ts < minTs {
321336
minTs = ts
322337
}
338+
if ts > maxTs {
339+
maxTs = ts
340+
}
323341
}
324342
}
325343
c.minWaitingTs = minTs
344+
c.maxWaitingTs = maxTs
326345
}
327346

328347
func (c *Conductor) acceptEvent(e event.Event, payload *source.Payload) uint64 {
@@ -498,6 +517,7 @@ func (c *Conductor) syncTable(q *tableQueue) {
498517

499518
// queueDML records a decoded row until the writer can accept it.
500519
func (c *Conductor) queueDML(item *event.DMLEvent) {
520+
c.bufferedBytes += dmlMemoryBytes(item)
501521
tableID := item.PhysicalTableID
502522

503523
q := c.pendingDML[tableID]
@@ -576,6 +596,7 @@ func (c *Conductor) nextDML() *event.DMLEvent {
576596
}
577597

578598
func (c *Conductor) popDML(row *event.DMLEvent) {
599+
c.bufferedBytes -= dmlMemoryBytes(row)
579600
q := c.pendingDML[row.PhysicalTableID]
580601
q.rows[0] = nil
581602
q.rows = q.rows[1:]
@@ -683,11 +704,12 @@ func (c *Conductor) flush(ctx context.Context, w *writer.Writer) error {
683704
}
684705

685706
func (c *Conductor) effectiveWatermark() uint64 {
707+
watermark := c.pacer.watermark()
686708
if c.minWaitingTs != 0 {
687-
return min(c.watermark, c.minWaitingTs-1)
709+
return min(watermark, c.minWaitingTs-1)
688710
}
689711

690-
return c.watermark
712+
return watermark
691713
}
692714

693715
func (c *Conductor) releaseSchemas() {
@@ -696,34 +718,16 @@ func (c *Conductor) releaseSchemas() {
696718
}
697719
}
698720

699-
// advanceWatermark records resolved progress. Sources without partitions
700-
// publish a global watermark; partitioned sources advance only when every
701-
// partition has been resolved.
721+
// advanceWatermark records resolved progress.
702722
func (c *Conductor) advanceWatermark(ts uint64, partition int32) {
703-
if len(c.partitionWatermarks) == 0 {
704-
c.watermark = max(c.watermark, ts)
705-
c.releaseSchemas()
706-
return
707-
}
708-
709-
if int(partition) >= len(c.partitionWatermarks) {
710-
return
711-
}
712-
713-
c.partitionWatermarks[partition] = max(c.partitionWatermarks[partition], ts)
714-
715-
watermark := uint64(math.MaxUint64)
716-
for _, resolved := range c.partitionWatermarks {
717-
if resolved == 0 {
718-
return
719-
}
720-
watermark = min(watermark, resolved)
721-
}
722-
723-
c.watermark = max(c.watermark, watermark)
723+
c.pacer.advance(partition, ts)
724724
c.releaseSchemas()
725725
}
726726

727+
func dmlMemoryBytes(item *event.DMLEvent) int64 {
728+
return dmlEventOverheadBytes + item.Rows.MemoryUsage()
729+
}
730+
727731
// source.Payload progress can pass decoded events still awaiting delivery. Publish
728732
// the earliest pending timestamp so the writer never checkpoints past it.
729733
func (c *Conductor) advanceWriter(w *writer.Writer) {

‎cmd/consumer/conductor/conductor_test.go‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,7 @@ func TestConductorSimpleCrossPartitionWakeupAndPrePostSchema(t *testing.T) {
801801
require.NoError(t, c.flush(t.Context(), w))
802802
require.NoError(t, w.Drain(t.Context()))
803803
require.Equal(t, uint64(250), w.Checkpoint())
804+
require.Zero(t, c.bufferedBytes)
804805
}
805806

806807
func TestConductorDDLWakesAllMultipleTableInfos(t *testing.T) {
@@ -920,3 +921,127 @@ func TestConductorRunAdvancesCheckpointWhenAsyncWriterCompletesIdle(t *testing.T
920921
group.Close()
921922
require.Equal(t, uint64(100), w.Checkpoint())
922923
}
924+
925+
type mockPauserReader struct {
926+
*sourcemock.MockReader
927+
*sourcemock.MockPauser
928+
}
929+
930+
func TestConductorPacingSteadyStateAndThresholdHysteresis(t *testing.T) {
931+
ctrl := gomock.NewController(t)
932+
mr := sourcemock.NewMockReader(ctrl)
933+
mr.EXPECT().Partitions().Return(int32(3)).AnyTimes()
934+
mp := sourcemock.NewMockPauser(ctrl)
935+
gomock.InOrder(
936+
mp.EXPECT().Pause([]int32{0}).Times(1),
937+
mp.EXPECT().Resume([]int32{0}).Times(1),
938+
)
939+
940+
c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil)
941+
942+
// Below pausePendingBytes: even with watermark skew (including minWatermark == 0), no stream is paused.
943+
c.advanceWatermark(100, 0)
944+
c.bufferedBytes = pausePendingBytes - 1
945+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
946+
require.False(t, c.pacer.throttling)
947+
require.Zero(t, c.pacer.pausedCount())
948+
949+
// At pausePendingBytes: ahead stream pauses while lagging streams stay unpaused.
950+
c.bufferedBytes = pausePendingBytes
951+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
952+
require.True(t, c.pacer.throttling)
953+
require.True(t, c.pacer.paused[0])
954+
require.False(t, c.pacer.paused[1])
955+
require.False(t, c.pacer.paused[2])
956+
require.Equal(t, 1, c.pacer.pausedCount())
957+
958+
// Between resumePendingBytes and pausePendingBytes: hysteresis keeps throttling active.
959+
c.bufferedBytes = resumePendingBytes + 1
960+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
961+
require.True(t, c.pacer.throttling)
962+
require.True(t, c.pacer.paused[0])
963+
964+
// At resumePendingBytes: throttling clears and paused stream resumes.
965+
c.bufferedBytes = resumePendingBytes
966+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
967+
require.False(t, c.pacer.throttling)
968+
require.False(t, c.pacer.paused[0])
969+
require.Zero(t, c.pacer.pausedCount())
970+
}
971+
972+
func TestConductorPacingResumesWhenMinWatermarkCatchesUp(t *testing.T) {
973+
ctrl := gomock.NewController(t)
974+
mr := sourcemock.NewMockReader(ctrl)
975+
mr.EXPECT().Partitions().Return(int32(2)).AnyTimes()
976+
mp := sourcemock.NewMockPauser(ctrl)
977+
gomock.InOrder(
978+
mp.EXPECT().Pause([]int32{0}).Times(1),
979+
mp.EXPECT().Resume([]int32{0}).Times(1),
980+
)
981+
982+
c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil)
983+
w := startBlackholeWriter(t)
984+
defer func() {
985+
require.NoError(t, w.Drain(t.Context()))
986+
}()
987+
988+
info := newTestTableInfo(1, "t1", 100, "id", "v")
989+
c.acceptEvent(newInsertDML(info, 200, 1, 2), &source.Payload{Partition: 0})
990+
require.Greater(t, c.bufferedBytes, int64(0))
991+
992+
// Simulate high buffered memory while stream 0 leads stream 1 -> stream 0 pauses.
993+
c.advanceWatermark(100, 1)
994+
c.advanceWatermark(200, 0)
995+
c.bufferedBytes = pausePendingBytes
996+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
997+
require.True(t, c.pacer.paused[0])
998+
999+
// While still throttling, stream 1 catches up to 200 -> stream 0 resumes immediately.
1000+
c.advanceWatermark(200, 1)
1001+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
1002+
require.False(t, c.pacer.paused[0])
1003+
require.Zero(t, c.pacer.pausedCount())
1004+
1005+
// Flushing buffered DMLs drains all queued bytes back to 0.
1006+
c.bufferedBytes = dmlMemoryBytes(c.pendingDML[1].rows[0])
1007+
require.NoError(t, c.flush(t.Context(), w))
1008+
require.Zero(t, c.bufferedBytes)
1009+
}
1010+
1011+
func TestConductorPacingResumesBehindMaxWaitingTs(t *testing.T) {
1012+
ctrl := gomock.NewController(t)
1013+
mr := sourcemock.NewMockReader(ctrl)
1014+
mr.EXPECT().Partitions().Return(int32(4)).AnyTimes()
1015+
mp := sourcemock.NewMockPauser(ctrl)
1016+
gomock.InOrder(
1017+
mp.EXPECT().Pause([]int32{0, 1, 2}).Times(1),
1018+
mp.EXPECT().Resume([]int32{1, 2}).Times(1),
1019+
)
1020+
1021+
c := New(mockPauserReader{MockReader: mr, MockPauser: mp}, codecCommon.NewTableInfoProvider(), nil)
1022+
1023+
c.advanceWatermark(10, 3)
1024+
c.advanceWatermark(100, 2)
1025+
c.advanceWatermark(300, 1)
1026+
c.advanceWatermark(400, 0)
1027+
c.bufferedBytes = pausePendingBytes
1028+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
1029+
require.True(t, c.pacer.paused[0])
1030+
require.True(t, c.pacer.paused[1])
1031+
require.True(t, c.pacer.paused[2])
1032+
require.False(t, c.pacer.paused[3])
1033+
1034+
// Park two Simple DMLs at CommitTs=200 and CommitTs=300: stream 1 at 300
1035+
// (== maxWaitingTs) and stream 2 at 100 resume, while stream 0 at 400 stays paused.
1036+
c.acceptPending([]*simple.PendingMessage{
1037+
{Schema: "test", Table: "t2", SchemaVersion: 200, CommitTs: 200, Bytes: 512},
1038+
{Schema: "test", Table: "t3", SchemaVersion: 300, CommitTs: 300, Bytes: 512},
1039+
}, &source.Payload{Partition: 2, Offset: 1})
1040+
require.Equal(t, uint64(200), c.minWaitingTs)
1041+
require.Equal(t, uint64(300), c.maxWaitingTs)
1042+
c.pacer.sync(c.bufferedBytes, c.maxWaitingTs)
1043+
require.True(t, c.pacer.paused[0])
1044+
require.False(t, c.pacer.paused[1])
1045+
require.False(t, c.pacer.paused[2])
1046+
require.Equal(t, 1, c.pacer.pausedCount())
1047+
}

0 commit comments

Comments
 (0)