Skip to content

Commit cf78eca

Browse files
committed
update code
1 parent e11e603 commit cf78eca

12 files changed

Lines changed: 396 additions & 107 deletions

File tree

‎coordinator/controller.go‎

Lines changed: 45 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ func NewController(
150150
batchSize int,
151151
balanceInterval time.Duration,
152152
pdClient pd.Client,
153-
meteringEnabled bool,
153+
accumulator *meteringAccumulator,
154154
) *Controller {
155155
changefeedDB := changefeed.NewChangefeedDB(version)
156156

@@ -199,8 +199,8 @@ func NewController(
199199
writeLease: newCaptureWriteLeaseController(version, selfNode.ID),
200200
}
201201
c.nodeChanged.changed = false
202-
if meteringEnabled {
203-
c.metering = newMeteringAccumulator()
202+
if accumulator != nil {
203+
c.metering = accumulator
204204
if version > 0 {
205205
changefeedDB.SetMeteringEpoch(uint64(version))
206206
}
@@ -768,38 +768,49 @@ func (c *Controller) handleSingleMaintainerStatus(
768768
return nil
769769
}
770770

771-
if c.metering != nil && c.version > 0 &&
772-
status.MeteringEpoch == uint64(c.version) && status.MeteringSeq > 0 {
773-
if ackedSeq, ok := c.metering.Accept(cfID, status.MeteringSeq, status.MeteringBytes); ok {
774-
cf.SetMeteringLastSeq(ackedSeq)
775-
if c.messageCenter != nil {
776-
// Reuse CheckpointTsMessage with CheckpointTs=0 as a metering-only ACK
777-
// carrier so Maintainer drops it before forwarding downstream.
778-
_ = c.messageCenter.SendCommand(messaging.NewSingleTargetMessage(
779-
from,
780-
messaging.MaintainerManagerTopic,
781-
&heartbeatpb.CheckpointTsMessage{
782-
ChangefeedID: cfID.ToPB(),
783-
CheckpointTs: 0,
784-
MeteringEpoch: uint64(c.version),
785-
MeteringAckedSeq: ackedSeq,
786-
},
787-
))
788-
}
789-
} else {
790-
meteringRejectedStatusCounter.Inc()
791-
log.Warn("drop out-of-order traffic metering status",
792-
zap.Stringer("changefeedID", cfID),
793-
zap.Stringer("from", from),
794-
zap.Uint64("meteringEpoch", status.MeteringEpoch),
795-
zap.Uint64("reportedSeq", status.MeteringSeq),
796-
zap.Uint64("lastAcceptedSeq", ackedSeq),
797-
zap.Uint64("meteringBytes", status.MeteringBytes))
798-
}
799-
}
771+
c.acceptMeteringStatus(cf, from, status)
772+
return c.updateChangefeedStatus(cf, cfID, status)
773+
}
800774

801-
change := c.updateChangefeedStatus(cf, cfID, status)
802-
return change
775+
// acceptMeteringStatus records one sealed traffic delta from a maintainer and
776+
// acknowledges the cumulative sequence. Stale or out-of-order reports are dropped.
777+
func (c *Controller) acceptMeteringStatus(
778+
cf *changefeed.Changefeed,
779+
from node.ID,
780+
status *heartbeatpb.MaintainerStatus,
781+
) {
782+
if c.metering == nil || c.version == 0 ||
783+
status.MeteringEpoch != uint64(c.version) || status.MeteringSeq == 0 {
784+
return
785+
}
786+
ackedSeq, ok := c.metering.Accept(cf.ID, status.MeteringSeq, status.MeteringBytes)
787+
if !ok {
788+
meteringRejectedStatusCounter.Inc()
789+
log.Warn("drop out-of-order traffic metering status",
790+
zap.Stringer("changefeedID", cf.ID),
791+
zap.Stringer("from", from),
792+
zap.Uint64("meteringEpoch", status.MeteringEpoch),
793+
zap.Uint64("reportedSeq", status.MeteringSeq),
794+
zap.Uint64("lastAcceptedSeq", ackedSeq),
795+
zap.Uint64("meteringBytes", status.MeteringBytes))
796+
return
797+
}
798+
cf.SetMeteringLastSeq(ackedSeq)
799+
if c.messageCenter == nil {
800+
return
801+
}
802+
// Reuse CheckpointTsMessage with CheckpointTs=0 as a metering-only ACK
803+
// carrier so Maintainer drops it before forwarding downstream.
804+
_ = c.messageCenter.SendCommand(messaging.NewSingleTargetMessage(
805+
from,
806+
messaging.MaintainerManagerTopic,
807+
&heartbeatpb.CheckpointTsMessage{
808+
ChangefeedID: cf.ID.ToPB(),
809+
CheckpointTs: 0,
810+
MeteringEpoch: uint64(c.version),
811+
MeteringAckedSeq: ackedSeq,
812+
},
813+
))
803814
}
804815

805816
// markChangefeedBootstrapped serializes the acknowledgement with API lifecycle

‎coordinator/coordinator.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ func New(node *node.Info,
130130
// handle messages from message center
131131
mc.RegisterHandler(messaging.CoordinatorTopic, c.recvMessages)
132132
reporter := createMeteringReporter()
133+
var accumulator *meteringAccumulator
134+
if reporter != nil {
135+
accumulator = newMeteringAccumulator()
136+
}
133137
c.controller = NewController(
134138
c.version,
135139
c.nodeInfo,
@@ -139,10 +143,10 @@ func New(node *node.Info,
139143
batchSize,
140144
balanceCheckInterval,
141145
c.pdClient,
142-
reporter != nil,
146+
accumulator,
143147
)
144148
if reporter != nil {
145-
c.metering = newMeteringReporter(reporter, c.controller.metering)
149+
c.metering = newMeteringReporter(reporter, accumulator)
146150
}
147151

148152
nodeManager := appcontext.GetService[*watcher.NodeManager](watcher.NodeManagerName)

‎coordinator/metering.go‎

Lines changed: 40 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,9 @@ func (m *meteringAccumulator) Commit(records []metering.Record) uint64 {
126126
cur := m.pending[key]
127127
if cur <= r.EffectiveBytes {
128128
delete(m.pending, key)
129-
} else {
130-
m.pending[key] = cur - r.EffectiveBytes
129+
continue
131130
}
131+
m.pending[key] = cur - r.EffectiveBytes
132132
}
133133
var remaining uint64
134134
for _, bytes := range m.pending {
@@ -139,8 +139,10 @@ func (m *meteringAccumulator) Commit(records []metering.Record) uint64 {
139139

140140
// meteringReporter schedules per-minute delta uploads and shutdown flush for one coordinator term.
141141
type meteringReporter struct {
142-
reporter *metering.Reporter
143-
accumulator *meteringAccumulator
142+
reporter *metering.Reporter
143+
accumulator *meteringAccumulator
144+
uncertainTS int64
145+
uncertainRecords []metering.Record
144146
}
145147

146148
func newMeteringReporter(reporter *metering.Reporter, accumulator *meteringAccumulator) *meteringReporter {
@@ -181,10 +183,33 @@ func waitUntil(ctx context.Context, deadline time.Time) bool {
181183
}
182184
}
183185

184-
func (r *meteringReporter) reportAt(ctx context.Context, reportTime time.Time) error {
185-
if r.reporter == nil || r.accumulator == nil {
186+
func (r *meteringReporter) resolveUncertain(ctx context.Context) error {
187+
if len(r.uncertainRecords) == 0 {
186188
return nil
187189
}
190+
persisted, err := r.reporter.ResolveUncertainUpload(ctx)
191+
if err != nil {
192+
meteringReportCounter.WithLabelValues("failure").Inc()
193+
log.Warn("failed to verify uncertain traffic metering upload",
194+
zap.Int64("timestamp", r.uncertainTS),
195+
zap.Int("recordCount", len(r.uncertainRecords)),
196+
zap.Error(err))
197+
return err
198+
}
199+
if persisted {
200+
meteringPendingBytesGauge.Set(float64(r.accumulator.Commit(r.uncertainRecords)))
201+
meteringReportCounter.WithLabelValues("success").Inc()
202+
meteringLastSuccessTimestampGauge.Set(float64(r.uncertainTS))
203+
}
204+
r.uncertainTS = 0
205+
r.uncertainRecords = nil
206+
return nil
207+
}
208+
209+
func (r *meteringReporter) reportAt(ctx context.Context, reportTime time.Time) error {
210+
if err := r.resolveUncertain(ctx); err != nil {
211+
return err
212+
}
188213
records, pending := r.accumulator.Snapshot()
189214
meteringPendingBytesGauge.Set(float64(pending))
190215
if len(records) == 0 {
@@ -196,11 +221,15 @@ func (r *meteringReporter) reportAt(ctx context.Context, reportTime time.Time) e
196221
err := r.reporter.Report(ctx, ts, records)
197222
meteringReportDuration.Observe(time.Since(start).Seconds())
198223
if err != nil {
224+
if r.reporter.HasUncertainUpload() {
225+
r.uncertainTS = ts
226+
r.uncertainRecords = records
227+
}
228+
reason := "failure"
199229
if errors.Is(err, writer.ErrFileExists) {
200-
meteringReportCounter.WithLabelValues("exists").Inc()
201-
} else {
202-
meteringReportCounter.WithLabelValues("failure").Inc()
230+
reason = "exists"
203231
}
232+
meteringReportCounter.WithLabelValues(reason).Inc()
204233
log.Warn("failed to upload traffic metering delta",
205234
zap.Int64("timestamp", ts),
206235
zap.Int("recordCount", len(records)),
@@ -215,11 +244,8 @@ func (r *meteringReporter) reportAt(ctx context.Context, reportTime time.Time) e
215244
}
216245

217246
func (r *meteringReporter) FlushOnShutdown() {
218-
if r.reporter == nil || r.accumulator == nil {
219-
return
220-
}
221247
records, _ := r.accumulator.Snapshot()
222-
if len(records) == 0 {
248+
if len(records) == 0 && len(r.uncertainRecords) == 0 {
223249
return
224250
}
225251
flushTS := time.Now().Truncate(time.Minute).Add(time.Minute)
@@ -242,7 +268,5 @@ func (r *meteringReporter) FlushOnShutdown() {
242268
}
243269

244270
func (r *meteringReporter) Close() {
245-
if r.reporter != nil {
246-
r.reporter.Close()
247-
}
271+
r.reporter.Close()
248272
}

‎coordinator/metering_test.go‎

Lines changed: 105 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,18 @@
1515
package coordinator
1616

1717
import (
18+
"bytes"
1819
"compress/gzip"
1920
"context"
2021
"encoding/json"
22+
"io"
23+
"net/http"
24+
"net/http/httptest"
2125
"os"
2226
"path/filepath"
2327
"strconv"
28+
"strings"
29+
"sync"
2430
"testing"
2531
"testing/synctest"
2632
"time"
@@ -34,6 +40,7 @@ import (
3440
appcontext "github.com/pingcap/ticdc/pkg/common/context"
3541
"github.com/pingcap/ticdc/pkg/config"
3642
"github.com/pingcap/ticdc/pkg/messaging"
43+
"github.com/pingcap/ticdc/pkg/metering"
3744
"github.com/pingcap/ticdc/pkg/node"
3845
"github.com/pingcap/ticdc/pkg/pdutil"
3946
"github.com/pingcap/ticdc/server/watcher"
@@ -146,7 +153,7 @@ func TestMeteringCoordinatorTerm(t *testing.T) {
146153
config.StoreGlobalServerConfig(cfg)
147154
c := &coordinator{
148155
gcTickInterval: time.Hour,
149-
controller: &Controller{},
156+
controller: &Controller{metering: newMeteringAccumulator()},
150157
gcCleaner: gccleaner.New(nil, "test"),
151158
eventCh: chann.NewAutoDrainChann[*Event](),
152159
changefeedChangeCh: make(chan []*changefeedChange),
@@ -349,7 +356,7 @@ func TestNewControllerBootstrapAdvertisesMetering(t *testing.T) {
349356
1,
350357
time.Minute,
351358
nil,
352-
true,
359+
newMeteringAccumulator(),
353360
)
354361
t.Cleanup(func() {
355362
ctrl.taskScheduler.Stop()
@@ -432,3 +439,99 @@ func TestControllerMeteringAckAndAddMaintainerRecovery(t *testing.T) {
432439
require.Equal(t, uint64(640), total)
433440
require.Equal(t, rejectedBefore+1, testutil.ToFloat64(meteringRejectedStatusCounter))
434441
}
442+
443+
func TestCoordinatorMeteringResolvesUncertainUpload(t *testing.T) {
444+
for _, tc := range []struct {
445+
name string
446+
persistOnFinal bool
447+
expectedNextVal uint64
448+
}{
449+
{name: "persisted on final attempt commits prior batch", persistOnFinal: true, expectedNextVal: 250},
450+
{name: "not persisted merges prior batch into next minute", persistOnFinal: false, expectedNextVal: 750},
451+
} {
452+
t.Run(tc.name, func(t *testing.T) {
453+
t1 := time.Now().Truncate(time.Minute)
454+
t2 := t1.Add(time.Minute)
455+
t1Seg := "/" + strconv.FormatInt(t1.Unix(), 10) + "/"
456+
t2Seg := "/" + strconv.FormatInt(t2.Unix(), 10) + "/"
457+
458+
var mu sync.Mutex
459+
objects := make(map[string]decodedMeteringFile)
460+
t1PutCount := 0
461+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
462+
mu.Lock()
463+
defer mu.Unlock()
464+
switch r.Method {
465+
case http.MethodHead:
466+
if _, ok := objects[r.URL.Path]; ok {
467+
w.WriteHeader(http.StatusOK)
468+
} else {
469+
w.WriteHeader(http.StatusNotFound)
470+
}
471+
case http.MethodPut:
472+
body, err := io.ReadAll(r.Body)
473+
require.NoError(t, err)
474+
gz, err := gzip.NewReader(bytes.NewReader(body))
475+
require.NoError(t, err)
476+
var payload decodedMeteringFile
477+
require.NoError(t, json.NewDecoder(gz).Decode(&payload))
478+
require.NoError(t, gz.Close())
479+
480+
if strings.Contains(r.URL.Path, t1Seg) {
481+
t1PutCount++
482+
if tc.persistOnFinal && t1PutCount == 3 {
483+
objects[r.URL.Path] = payload
484+
}
485+
w.WriteHeader(http.StatusBadRequest)
486+
return
487+
}
488+
objects[r.URL.Path] = payload
489+
w.WriteHeader(http.StatusOK)
490+
default:
491+
w.WriteHeader(http.StatusMethodNotAllowed)
492+
}
493+
}))
494+
defer server.Close()
495+
496+
cfg := meteringconfig.NewMeteringConfig().WithS3("us-east-1", "bucket").WithEndpoint(server.URL).
497+
WithAWSConfig(&meteringconfig.MeteringAWSConfig{AccessKey: "test", SecretAccessKey: "test", S3ForcePathStyle: true})
498+
rep, err := metering.NewReporter(cfg, "cluster-1")
499+
require.NoError(t, err)
500+
defer rep.Close()
501+
502+
acc := newMeteringAccumulator()
503+
mr := newMeteringReporter(rep, acc)
504+
cf := common.NewChangeFeedIDWithName("cf-a", "ks-a")
505+
_, ok := acc.Accept(cf, 1, 500)
506+
require.True(t, ok)
507+
508+
// All attempts fail on t1, leaving upload persistence uncertain.
509+
err = mr.reportAt(t.Context(), t1)
510+
require.Error(t, err)
511+
require.True(t, rep.HasUncertainUpload())
512+
require.Len(t, mr.uncertainRecords, 1)
513+
514+
// Additional bytes arrive before t2; reportAt(t2) must probe t1 first.
515+
_, ok = acc.Accept(cf, 2, 250)
516+
require.True(t, ok)
517+
require.NoError(t, mr.reportAt(t.Context(), t2))
518+
require.False(t, rep.HasUncertainUpload())
519+
require.Empty(t, mr.uncertainRecords)
520+
_, remaining := acc.Snapshot()
521+
require.Zero(t, remaining)
522+
523+
mu.Lock()
524+
defer mu.Unlock()
525+
var t2Payload *decodedMeteringFile
526+
for p, f := range objects {
527+
if strings.Contains(p, t2Seg) {
528+
cp := f
529+
t2Payload = &cp
530+
}
531+
}
532+
require.NotNil(t, t2Payload)
533+
require.Len(t, t2Payload.Data, 1)
534+
require.Equal(t, tc.expectedNextVal, t2Payload.Data[0].EffectiveBytes.Value)
535+
})
536+
}
537+
}

‎docs/design/2026-11-26-ticdc-traffic-metering.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ The protocol operates as follows:
108108
#### 3. Failure Recovery and Rolling Upgrade
109109

110110
- **Maintainer crash or migration (Coordinator alive)**: Coordinator retains `lastSeq` and `pendingBytes` in memory, and the new or migrated Maintainer inherits `(metering_epoch, lastSeq)` to realign with surviving `DispatcherManager` nodes. If the crash occurred before Coordinator accepted the round, DMs resend `sealedBytes` (zero loss); if it occurred after acceptance, the new Maintainer requests the next sequence and DMs discard the already-accepted snapshot and seal newly flushed traffic (zero double-counting).
111-
- **DispatcherManager node crash or restart**: the restarted node starts from zero state and Maintainer removes the lost node from the active round. Events on the crashed node that were not yet confirmed at the checkpoint are resynchronized after rescheduling and metered normally upon confirmation, while at most the trailing unsealed/unacknowledged round (`~1s`) for already-confirmed events is discarded.
112-
- **Transient object storage failures or object conflicts**: Coordinator retains in-memory `pendingBytes` without deducting it, merging it into the next whole-minute upload with zero loss.
111+
- **DispatcherManager node crash or restart**: the restarted node starts from zero state and Maintainer removes the lost node from the active round. Events on the crashed node that were not yet confirmed at the checkpoint are resynchronized after rescheduling and metered normally upon confirmation, while the bytes flushed since that node's last seal, and any sealed snapshot the Maintainer has not yet received, are discarded; `defaultMeteringRoundInterval` delays the next round after an acknowledgment and does not bound how long a stalled round remains open.
112+
- **Transient object storage failures or object conflicts**: Coordinator retains in-memory `pendingBytes` without deducting it; if a failed write already attempted storage `PUT` with an unknown outcome, Coordinator checks the object's existence before the next upload—committing the prior batch if persisted or merging it into the next whole-minute upload otherwise—guaranteeing zero loss and preventing cross-minute duplication.
113113
- **Graceful shutdown, failover, and rolling upgrade**: before stepping down or exiting, Coordinator flushes unreported in-memory deltas to the next unused whole minute. The newly elected Coordinator holds a strictly greater `metering_epoch` and immediately advances sealing from sequence `1` of the new epoch across surviving `DispatcherManager` nodes without being blocked by prior `sealedSeq` values; any prior-term `sealedBytes` not yet absorbed before epoch switch—as well as the trailing unsealed round during changefeed deletion or close—are discarded on purpose rather than carried across epochs or blocking deletion, guaranteeing zero double-counting.
114114
- **Unexpected Coordinator crash**: an abrupt process termination or host outage loses all unreported in-memory `pendingBytes` accumulated since the last successful upload (typically `< 60` seconds under healthy object storage, or the full unuploaded window during prolonged storage outages); the newly elected Coordinator resumes seamlessly with a higher `metering_epoch`.
115115
- **Mixed-version rolling upgrade**: normal rolling upgrades upgrade the Coordinator node last. `DispatcherManager` nodes advertise metering capability during handshake and heartbeats; when advancing `metering_seq`, Maintainer waits only for capable nodes and skips un-upgraded nodes until they are upgraded and naturally join subsequent rounds.
@@ -188,3 +188,11 @@ During its term, Coordinator uploads per-minute **incremental traffic deltas** f
188188
1. **Complete decoupling from protocols and sinks**: metering at the sink-agnostic event dispatching layer with event-level `PostFlush` confirmation avoids touching encoders or downstream SQL builders and remains invariant to batching and compression.
189189
2. **Simple, accurate cross-node aggregation**: reusing existing heartbeats with `(metering_epoch, metering_seq)` achieves sealing and cumulative acknowledgment with zero new RPCs, avoiding double-counting and data loss while enabling fast failover recovery.
190190
3. **Zero metadata intrusion and minimal storage cost**: pure in-memory aggregation combined with per-minute single-file delta uploads leaves etcd untouched, avoids metadata downgrade burdens, and keeps cluster-wide object storage writes down to one request per minute.
191+
192+
---
193+
194+
### Follow-up Work
195+
196+
- **Avoid re-submitting a batch whose previous upload may have succeeded.** `Reporter.write` returns success when a retry observes `ErrFileExists`, but if an earlier attempt stored the object and every later attempt fails before that check, `Report` returns an error and `reportAt` keeps the snapshot in `pendingBytes`; the next whole-minute upload then stores the same bytes under a later timestamp. Decide how a retry identifies the earlier batch, for example through the object path or payload, and whether an unprovable outcome favors duplicate counting or loss.
197+
- **Clear `roundBytes` when an ACK advances `targetSeq`.** `meteringCollector.OnAck` sets `targetSeq = ackedSeq + 1` without clearing `roundBytes`. `meteringAccumulator.Accept` answers a stale sequence with the latest accepted sequence, so a Maintainer that starts from an older `MeteringLastSeq` can receive an ACK ahead of its target while `roundBytes` still holds entries recorded for the old target; the next completed round reuses those entries and the Coordinator counts the same bytes twice. Clear `roundBytes` and reset `roundStartedAt` whenever the ACK advances the target, and cover a stale `MeteringLastSeq` in a test.
198+
- **State the shutdown flush guarantee.** `FlushOnShutdown` advances the timestamp only on `ErrFileExists`, stops on any other error, and gives up after five attempts within `meteringShutdownFlushTimeout`; when it stops, the buffered bytes are lost as the Coordinator exits. Either document the final flush as best-effort or keep retrying transient failures until the timeout.

0 commit comments

Comments
 (0)