From 9e79e04fcf1f010144c3d2209e9cfc0177056817 Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 21 Sep 2026 13:12:09 +0800 Subject: [PATCH 01/17] snapshot: bootstrap native changefeeds from CSE backups Signed-off-by: dongmen <414110582@qq.com> --- api/v2/changefeed.go | 38 +- api/v2/model.go | 40 +- cmd/snapshot-provider/main.go | 37 ++ coordinator/changefeed/etcd_backend.go | 133 +++--- coordinator/changefeed/etcd_backend_test.go | 16 +- coordinator/changefeed/snapshot.go | 76 ++++ coordinator/changefeed/snapshot_test.go | 56 +++ coordinator/coordinator.go | 16 +- coordinator/snapshot.go | 43 ++ .../dispatchermanager/snapshot.go | 126 ++++++ .../dispatcherorchestrator/snapshot.go | 51 +++ downstreamadapter/sink/helper/mq_row_event.go | 2 + maintainer/maintainer.go | 23 +- maintainer/maintainer_event.go | 11 +- maintainer/snapshot.go | 101 +++++ pkg/common/event/dml_event.go | 2 + pkg/common/event/row_change.go | 8 + pkg/config/changefeed.go | 6 +- pkg/config/replica_config.go | 14 +- pkg/errors/snapshot.go | 6 + pkg/sink/codec/open/codec.go | 7 + pkg/sink/codec/open/snapshot_test.go | 30 ++ pkg/snapshot/bootstrap/controller.go | 239 +++++++++++ pkg/snapshot/bootstrap/interfaces.go | 31 ++ pkg/snapshot/protocol/chunk.go | 160 ++++++++ pkg/snapshot/protocol/protocol_test.go | 70 ++++ pkg/snapshot/protocol/testdata/rust-v1.skv | Bin 0 -> 348 bytes pkg/snapshot/protocol/types.go | 236 +++++++++++ pkg/snapshot/provider/client.go | 38 ++ pkg/snapshot/provider/provider.go | 388 ++++++++++++++++++ pkg/snapshot/provider/provider_test.go | 53 +++ pkg/snapshot/store/local.go | 122 ++++++ pkg/snapshot/store/store_test.go | 72 ++++ pkg/snapshot/store/tasks.go | 173 ++++++++ .../native_snapshot/README.md | 163 ++++++++ .../native_snapshot/compare.py | 19 + .../integration_tests/native_snapshot/demo.py | 158 +++++++ .../native_snapshot/verify/main.go | 225 ++++++++++ 38 files changed, 2856 insertions(+), 133 deletions(-) create mode 100644 cmd/snapshot-provider/main.go create mode 100644 coordinator/changefeed/snapshot.go create mode 100644 coordinator/changefeed/snapshot_test.go create mode 100644 coordinator/snapshot.go create mode 100644 downstreamadapter/dispatchermanager/snapshot.go create mode 100644 downstreamadapter/dispatcherorchestrator/snapshot.go create mode 100644 maintainer/snapshot.go create mode 100644 pkg/errors/snapshot.go create mode 100644 pkg/sink/codec/open/snapshot_test.go create mode 100644 pkg/snapshot/bootstrap/controller.go create mode 100644 pkg/snapshot/bootstrap/interfaces.go create mode 100644 pkg/snapshot/protocol/chunk.go create mode 100644 pkg/snapshot/protocol/protocol_test.go create mode 100644 pkg/snapshot/protocol/testdata/rust-v1.skv create mode 100644 pkg/snapshot/protocol/types.go create mode 100644 pkg/snapshot/provider/client.go create mode 100644 pkg/snapshot/provider/provider.go create mode 100644 pkg/snapshot/provider/provider_test.go create mode 100644 pkg/snapshot/store/local.go create mode 100644 pkg/snapshot/store/store_test.go create mode 100644 pkg/snapshot/store/tasks.go create mode 100644 tests/integration_tests/native_snapshot/README.md create mode 100644 tests/integration_tests/native_snapshot/compare.py create mode 100644 tests/integration_tests/native_snapshot/demo.py create mode 100644 tests/integration_tests/native_snapshot/verify/main.go diff --git a/api/v2/changefeed.go b/api/v2/changefeed.go index 12340b0f39..d8280b15a7 100644 --- a/api/v2/changefeed.go +++ b/api/v2/changefeed.go @@ -620,24 +620,26 @@ func CfInfoToAPIModel( } apiInfoModel := &ChangeFeedInfo{ - UpstreamID: info.UpstreamID, - ID: info.ChangefeedID.Name(), - Keyspace: info.ChangefeedID.Keyspace(), - SinkURI: util.MaskSensitiveDataInURI(info.SinkURI), - CreateTime: info.CreateTime, - StartTs: info.StartTs, - TargetTs: info.TargetTs, - AdminJobType: info.AdminJobType, - Config: replicaConfig, - State: info.State, - Error: runningError, - CreatorVersion: info.CreatorVersion, - CheckpointTs: status.CheckpointTs, - ResolvedTs: status.CheckpointTs, - CheckpointTime: api.JSONTime(oracle.GetTimeFromTS(status.CheckpointTs)), - TaskStatus: taskStatus, - MaintainerAddr: status.GetMaintainerAddr(), - GID: info.ChangefeedID.ID(), + Snapshot: status.Snapshot, + BootstrapComplete: info.Config == nil || info.Config.Snapshot == nil || status.Snapshot != nil && status.Snapshot.Marker != nil, + UpstreamID: info.UpstreamID, + ID: info.ChangefeedID.Name(), + Keyspace: info.ChangefeedID.Keyspace(), + SinkURI: util.MaskSensitiveDataInURI(info.SinkURI), + CreateTime: info.CreateTime, + StartTs: info.StartTs, + TargetTs: info.TargetTs, + AdminJobType: info.AdminJobType, + Config: replicaConfig, + State: info.State, + Error: runningError, + CreatorVersion: info.CreatorVersion, + CheckpointTs: status.CheckpointTs, + ResolvedTs: status.CheckpointTs, + CheckpointTime: api.JSONTime(oracle.GetTimeFromTS(status.CheckpointTs)), + TaskStatus: taskStatus, + MaintainerAddr: status.GetMaintainerAddr(), + GID: info.ChangefeedID.ID(), } return apiInfoModel } diff --git a/api/v2/model.go b/api/v2/model.go index bd9c1898b1..7b1a052c79 100644 --- a/api/v2/model.go +++ b/api/v2/model.go @@ -24,6 +24,7 @@ import ( "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/integrity" "github.com/pingcap/ticdc/pkg/liveness" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/util" ) @@ -212,17 +213,18 @@ func (d *JSONDuration) UnmarshalText(text []byte) error { // ReplicaConfig is a duplicate of config.ReplicaConfig type ReplicaConfig struct { - PerformanceMode *string `json:"performance_mode,omitempty" toml:"performance-mode,omitempty"` - MemoryQuota *uint64 `json:"memory_quota,omitempty" toml:"memory-quota,omitempty"` - EventCollectorBatchCount *int `json:"event_collector_batch_count,omitempty" toml:"event-collector-batch-count,omitempty"` - EventCollectorBatchBytes *int `json:"event_collector_batch_bytes,omitempty" toml:"event-collector-batch-bytes,omitempty"` - CaseSensitive *bool `json:"case_sensitive,omitempty" toml:"case-sensitive,omitempty"` - ForceReplicate *bool `json:"force_replicate,omitempty" toml:"force-replicate,omitempty"` - IgnoreIneligibleTable *bool `json:"ignore_ineligible_table,omitempty" toml:"ignore-ineligible-table,omitempty"` - CheckGCSafePoint *bool `json:"check_gc_safe_point,omitempty" toml:"check-gc-safe-point,omitempty"` - EnableSyncPoint *bool `json:"enable_sync_point,omitempty" toml:"enable-sync-point,omitempty"` - EnableTableMonitor *bool `json:"enable_table_monitor,omitempty" toml:"enable-table-monitor,omitempty"` - BDRMode *bool `json:"bdr_mode,omitempty" toml:"bdr-mode,omitempty"` + Snapshot *protocol.Config `json:"snapshot,omitempty"` + PerformanceMode *string `json:"performance_mode,omitempty" toml:"performance-mode,omitempty"` + MemoryQuota *uint64 `json:"memory_quota,omitempty" toml:"memory-quota,omitempty"` + EventCollectorBatchCount *int `json:"event_collector_batch_count,omitempty" toml:"event-collector-batch-count,omitempty"` + EventCollectorBatchBytes *int `json:"event_collector_batch_bytes,omitempty" toml:"event-collector-batch-bytes,omitempty"` + CaseSensitive *bool `json:"case_sensitive,omitempty" toml:"case-sensitive,omitempty"` + ForceReplicate *bool `json:"force_replicate,omitempty" toml:"force-replicate,omitempty"` + IgnoreIneligibleTable *bool `json:"ignore_ineligible_table,omitempty" toml:"ignore-ineligible-table,omitempty"` + CheckGCSafePoint *bool `json:"check_gc_safe_point,omitempty" toml:"check-gc-safe-point,omitempty"` + EnableSyncPoint *bool `json:"enable_sync_point,omitempty" toml:"enable-sync-point,omitempty"` + EnableTableMonitor *bool `json:"enable_table_monitor,omitempty" toml:"enable-table-monitor,omitempty"` + BDRMode *bool `json:"bdr_mode,omitempty" toml:"bdr-mode,omitempty"` // AllowSameCluster allows the downstream to be the same TiDB logical cluster as the upstream. // By default TiCDC rejects such a changefeed to avoid self-replication loops. AllowSameCluster *bool `json:"allow_same_cluster,omitempty" toml:"allow-same-cluster,omitempty"` @@ -263,6 +265,9 @@ func (c *ReplicaConfig) ToInternalReplicaConfig() *config.ReplicaConfig { func (c *ReplicaConfig) toInternalReplicaConfigWithOriginConfig( res *config.ReplicaConfig, ) *config.ReplicaConfig { + if c.Snapshot != nil { + res.Snapshot = c.Snapshot + } if c.PerformanceMode != nil { res.PerformanceMode = c.PerformanceMode } @@ -729,6 +734,7 @@ func ToAPIReplicaConfig(c *config.ReplicaConfig) *ReplicaConfig { cloned := c.Clone() res := &ReplicaConfig{ + Snapshot: cloned.Snapshot, PerformanceMode: cloned.PerformanceMode, MemoryQuota: cloned.MemoryQuota, EventCollectorBatchCount: cloned.EventCollectorBatchCount, @@ -1421,11 +1427,13 @@ type ResolveLockReq struct { // ChangeFeedInfo describes the detail of a ChangeFeed type ChangeFeedInfo struct { - UpstreamID uint64 `json:"upstream_id,omitempty" toml:"upstream-id,omitempty"` - ID string `json:"id" toml:"id"` - Keyspace string `json:"keyspace" toml:"keyspace"` - SinkURI string `json:"sink_uri,omitempty" toml:"sink-uri,omitempty"` - CreateTime time.Time `json:"create_time" toml:"create-time"` + Snapshot *protocol.State `json:"snapshot,omitempty"` + BootstrapComplete bool `json:"bootstrap_complete"` + UpstreamID uint64 `json:"upstream_id,omitempty" toml:"upstream-id,omitempty"` + ID string `json:"id" toml:"id"` + Keyspace string `json:"keyspace" toml:"keyspace"` + SinkURI string `json:"sink_uri,omitempty" toml:"sink-uri,omitempty"` + CreateTime time.Time `json:"create_time" toml:"create-time"` // Start sync at this commit ts if `StartTs` is specify or using the CreateTime of changefeed. StartTs uint64 `json:"start_ts,omitempty" toml:"start-ts,omitempty"` // The ChangeFeed will exits until sync to timestamp TargetTs diff --git a/cmd/snapshot-provider/main.go b/cmd/snapshot-provider/main.go new file mode 100644 index 0000000000..889aad7152 --- /dev/null +++ b/cmd/snapshot-provider/main.go @@ -0,0 +1,37 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package main + +import ( + "flag" + "log" + "net/http" + "os" + "path/filepath" + "syscall" + "time" + + "github.com/pingcap/ticdc/pkg/snapshot/provider" +) + +func main() { + root := flag.String("root", "", "shared artifact directory") + binary := flag.String("cse-binary", "", "CSE batch binary") + addr := flag.String("listen", "127.0.0.1:18400", "listen address") + flag.Parse() + if *root == "" || *binary == "" { + log.Fatal("root and cse-binary required") + } + if e := os.MkdirAll(*root, 0o700); e != nil { + log.Fatal(e) + } + f, e := os.OpenFile(filepath.Join(*root, "provider.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if e != nil { + log.Fatal(e) + } + defer f.Close() + if e = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); e != nil { + log.Fatal("another controller owns this demo store") + } + s := http.Server{Addr: *addr, Handler: provider.New(*root, *binary), ReadHeaderTimeout: 5 * time.Second} + log.Fatal(s.ListenAndServe()) +} diff --git a/coordinator/changefeed/etcd_backend.go b/coordinator/changefeed/etcd_backend.go index 84939d14db..d23b4393f0 100644 --- a/coordinator/changefeed/etcd_backend.go +++ b/coordinator/changefeed/etcd_backend.go @@ -181,30 +181,29 @@ func (b *EtcdBackend) UpdateChangefeed(ctx context.Context, info *config.ChangeF if err != nil { return errors.Trace(err) } - status := &config.ChangeFeedStatus{ - CheckpointTs: checkpointTs, - Progress: progress, - } - statusStr, err := status.Marshal() - if err != nil { - return errors.Trace(err) - } - jobKey := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), info.ChangefeedID.DisplayName) - opsThen := []clientv3.Op{} - opsThen = append(opsThen, - clientv3.OpPut(infoKey, newStr), - clientv3.OpPut(jobKey, statusStr), - ) - - putResp, err := b.etcdClient.GetEtcdClient().Txn(ctx, []clientv3.Cmp{}, opsThen, []clientv3.Op{}) - if err != nil { - return errors.Trace(err) - } - if !putResp.Succeeded { - err = cerror.ErrMetaOpFailed.GenWithStackByArgs(fmt.Sprintf("update changefeed %s failed", info.ChangefeedID.Name())) - return errors.Trace(err) + for retry := 0; retry < 20; retry++ { + status, revision, err := b.etcdClient.GetChangeFeedStatus(ctx, info.ChangefeedID) + if err != nil { + return errors.Trace(err) + } + status.CheckpointTs = checkpointTs + status.Progress = progress + statusStr, err := status.Marshal() + if err != nil { + return err + } + jobKey := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), info.ChangefeedID.DisplayName) + resp, err := b.etcdClient.GetEtcdClient().Txn(ctx, + []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision(jobKey), "=", revision)}, + []clientv3.Op{clientv3.OpPut(infoKey, newStr), clientv3.OpPut(jobKey, statusStr)}, nil) + if err != nil { + return errors.Trace(err) + } + if resp.Succeeded { + return nil + } } - return nil + return cerror.ErrMetaOpFailed.GenWithStackByArgs("update changefeed status contention") } // FinishInit acknowledges initialization without overwriting status @@ -387,35 +386,11 @@ func (b *EtcdBackend) PauseChangefeed(ctx context.Context, id common.ChangeFeedI return errors.Trace(err) } info.State = config.StateStopped - infoKey := etcd.GetEtcdKeyChangeFeedInfo(b.etcdClient.GetClusterID(), id.DisplayName) - inforValue, err := info.Marshal() - if err != nil { - return errors.Trace(err) - } status, _, err := b.etcdClient.GetChangeFeedStatus(ctx, id) - status.Progress = config.ProgressStopping - if err != nil { - return errors.Trace(err) - } - jobValue, err := status.Marshal() - if err != nil { - return errors.Trace(err) - } - jobKey := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), id.DisplayName) - putResp, err := b.etcdClient.GetEtcdClient().Txn(ctx, nil, - []clientv3.Op{ - clientv3.OpPut(jobKey, jobValue), - clientv3.OpPut(infoKey, inforValue), - }, - []clientv3.Op{}) if err != nil { return errors.Trace(err) } - if !putResp.Succeeded { - err = cerror.ErrMetaOpFailed.GenWithStackByArgs(fmt.Sprintf("pause changefeed %s failed", id.DisplayName)) - return errors.Trace(err) - } - return nil + return b.UpdateChangefeed(ctx, info, status.CheckpointTs, config.ProgressStopping) } func (b *EtcdBackend) DeleteChangefeed(ctx context.Context, @@ -492,40 +467,40 @@ func (b *EtcdBackend) SetChangefeedProgress(ctx context.Context, id common.Chang } func (b *EtcdBackend) UpdateChangefeedCheckpointTs(ctx context.Context, cps map[common.ChangeFeedID]uint64) error { - opsThen := make([]clientv3.Op, 0, 128) - batchSize := 0 - - txnFunc := func() error { - putResp, err := b.etcdClient.GetEtcdClient().Txn(ctx, []clientv3.Cmp{}, opsThen, []clientv3.Op{}) - if err != nil { - return errors.Trace(err) - } - logEtcdOps(opsThen, putResp.Succeeded) - if !putResp.Succeeded { - return errors.New("commit failed") - } - return err - } - for cfID, checkpointTs := range cps { - status := &config.ChangeFeedStatus{CheckpointTs: checkpointTs, Progress: config.ProgressNone} - jobValue, err := status.Marshal() - if err != nil { - return errors.Trace(err) - } - jobKey := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), cfID.DisplayName) - opsThen = append(opsThen, clientv3.OpPut(jobKey, jobValue)) - batchSize++ - if batchSize >= 128 { - if err = txnFunc(); err != nil { + ids := make([]common.ChangeFeedID, 0, len(cps)) + for id := range cps { + ids = append(ids, id) + } + for start := 0; start < len(ids); start += 128 { + saved := false + for retry := 0; retry < 20; retry++ { + var ops []clientv3.Op + var comparisons []clientv3.Cmp + for _, id := range ids[start:min(start+128, len(ids))] { + status, revision, err := b.etcdClient.GetChangeFeedStatus(ctx, id) + if err != nil { + return errors.Trace(err) + } + status.CheckpointTs = max(status.CheckpointTs, cps[id]) + value, err := status.Marshal() + if err != nil { + return err + } + key := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), id.DisplayName) + comparisons = append(comparisons, clientv3.Compare(clientv3.ModRevision(key), "=", revision)) + ops = append(ops, clientv3.OpPut(key, value)) + } + response, err := b.etcdClient.GetEtcdClient().Txn(ctx, comparisons, ops, nil) + if err != nil { return errors.Trace(err) } - opsThen = opsThen[:0] - batchSize = 0 + if response.Succeeded { + saved = true + break + } } - } - if batchSize > 0 { - if err := txnFunc(); err != nil { - return errors.Trace(err) + if !saved { + return cerror.ErrMetaOpFailed.GenWithStackByArgs("checkpoint CAS contention") } } return nil diff --git a/coordinator/changefeed/etcd_backend_test.go b/coordinator/changefeed/etcd_backend_test.go index d98309092f..85b0d3beaf 100644 --- a/coordinator/changefeed/etcd_backend_test.go +++ b/coordinator/changefeed/etcd_backend_test.go @@ -127,16 +127,19 @@ func TestUpdateChangefeed(t *testing.T) { cdcClient.EXPECT().GetEtcdClient().Return(etcdClient).AnyTimes() cdcClient.EXPECT().GetClusterID().Return("test-cluster-id").AnyTimes() backend := NewEtcdBackend(cdcClient) + cdcClient.EXPECT().GetChangeFeedStatus(gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, common.ChangeFeedID) (*config.ChangeFeedStatus, int64, error) { + return &config.ChangeFeedStatus{}, 1, nil + }).AnyTimes() etcdClient.EXPECT().Txn(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, errors.New("txn failed")).Times(1) require.NotNil(t, backend.UpdateChangefeed(context.Background(), &config.ChangeFeedInfo{}, 0, config.ProgressStopping)) // txn fail etcdClient.EXPECT().Txn(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(&clientv3.TxnResponse{Succeeded: false}, nil).Times(1) + Return(&clientv3.TxnResponse{Succeeded: false}, nil).Times(20) require.NotNil(t, backend.UpdateChangefeed(context.Background(), &config.ChangeFeedInfo{}, 0, config.ProgressStopping)) - etcdClient.EXPECT().Txn(gomock.Any(), gomock.Len(0), NewFuncMatcher(func(i interface{}) bool { + etcdClient.EXPECT().Txn(gomock.Any(), gomock.Len(1), NewFuncMatcher(func(i interface{}) bool { ops := i.([]clientv3.Op) require.Len(t, ops, 2) require.True(t, ops[0].IsPut()) @@ -405,11 +408,11 @@ func TestPauseChangefeed(t *testing.T) { backend := NewEtcdBackend(cdcClient) changefeedID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) - info := &config.ChangeFeedInfo{State: config.StateNormal} + info := &config.ChangeFeedInfo{ChangefeedID: changefeedID, State: config.StateNormal} status := &config.ChangeFeedStatus{Progress: config.ProgressStopping} cdcClient.EXPECT().GetChangeFeedInfo(gomock.Any(), changefeedID.DisplayName).Return(info, nil).Times(1) - cdcClient.EXPECT().GetChangeFeedStatus(gomock.Any(), changefeedID).Return(status, int64(0), nil).Times(1) + cdcClient.EXPECT().GetChangeFeedStatus(gomock.Any(), changefeedID).Return(status, int64(0), nil).Times(2) etcdClient.EXPECT().Txn(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&clientv3.TxnResponse{Succeeded: true}, nil).Times(1) err := backend.PauseChangefeed(context.Background(), changefeedID) @@ -532,11 +535,14 @@ func TestUpdateChangefeedCheckpointTs(t *testing.T) { cdcClient.EXPECT().GetEtcdClient().Return(etcdClient).AnyTimes() cdcClient.EXPECT().GetClusterID().Return("test-cluster-id").AnyTimes() backend := NewEtcdBackend(cdcClient) + cdcClient.EXPECT().GetChangeFeedStatus(gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, common.ChangeFeedID) (*config.ChangeFeedStatus, int64, error) { + return &config.ChangeFeedStatus{}, 1, nil + }).AnyTimes() cps := map[common.ChangeFeedID]uint64{ common.NewChangeFeedIDWithName("test1", common.DefaultKeyspaceName): 100, } - etcdClient.EXPECT().Txn(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&clientv3.TxnResponse{Succeeded: false}, nil).Times(1) + etcdClient.EXPECT().Txn(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&clientv3.TxnResponse{Succeeded: false}, nil).Times(20) err := backend.UpdateChangefeedCheckpointTs(context.Background(), cps) require.NotNil(t, err) diff --git a/coordinator/changefeed/snapshot.go b/coordinator/changefeed/snapshot.go new file mode 100644 index 0000000000..5352718f5d --- /dev/null +++ b/coordinator/changefeed/snapshot.go @@ -0,0 +1,76 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package changefeed + +import ( + "context" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/etcd" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + clientv3 "go.etcd.io/etcd/client/v3" +) + +func (b *EtcdBackend) LoadSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) (*protocol.State, error) { + info, e := b.etcdClient.GetChangeFeedInfo(ctx, id.DisplayName) + if e != nil { + return nil, protocol.Wrap(e) + } + if info.Epoch != epoch { + return nil, protocol.Invalid("stale snapshot owner") + } + status, _, e := b.etcdClient.GetChangeFeedStatus(ctx, id) + if e != nil { + return nil, protocol.Wrap(e) + } + return status.Snapshot, nil +} + +func (b *EtcdBackend) SaveSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, next *protocol.State) error { + infoKey := etcd.GetEtcdKeyChangeFeedInfo(b.etcdClient.GetClusterID(), id.DisplayName) + statusKey := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), id.DisplayName) + for retry := 0; retry < 20; retry++ { + ir, e := b.etcdClient.GetEtcdClient().Get(ctx, infoKey) + if e != nil { + return protocol.Wrap(e) + } + if len(ir.Kvs) != 1 { + return protocol.Invalid("changefeed disappeared") + } + var info config.ChangeFeedInfo + if e = info.Unmarshal(ir.Kvs[0].Value); e != nil { + return e + } + if info.Epoch != epoch || info.ChangefeedID != id || !info.State.IsRunning() { + return protocol.Invalid("snapshot owner no longer active") + } + status, rev, e := b.etcdClient.GetChangeFeedStatus(ctx, id) + if e != nil { + return protocol.Wrap(e) + } + if old := status.Snapshot; old != nil { + if old.Generation != next.Generation || old.SnapshotID != next.SnapshotID || old.SnapshotTS != next.SnapshotTS { + return protocol.Invalid("snapshot identity changed") + } + if old.Marker != nil && (next.Marker == nil || *old.Marker != *next.Marker) { + return protocol.Invalid("cannot roll back snapshot marker") + } + } + if next.Marker != nil && (next.Phase != "SNAPSHOT_COMMITTED" || next.Marker.PlanDigest != next.PlanRef.Digest || next.Marker.SnapshotTS != next.SnapshotTS) { + return protocol.Invalid("marker/phase mismatch") + } + status.Snapshot = next + bts, e := status.Marshal() + if e != nil { + return e + } + res, e := b.etcdClient.GetEtcdClient().Txn(ctx, []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision(infoKey), "=", ir.Kvs[0].ModRevision), clientv3.Compare(clientv3.ModRevision(statusKey), "=", rev)}, []clientv3.Op{clientv3.OpPut(statusKey, bts)}, nil) + if e != nil { + return protocol.Wrap(e) + } + if res.Succeeded { + return nil + } + } + return protocol.Invalid("snapshot runtime CAS contention") +} diff --git a/coordinator/changefeed/snapshot_test.go b/coordinator/changefeed/snapshot_test.go new file mode 100644 index 0000000000..dcfb08c429 --- /dev/null +++ b/coordinator/changefeed/snapshot_test.go @@ -0,0 +1,56 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package changefeed + +import ( + "context" + "testing" + + "github.com/golang/mock/gomock" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/etcd" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/api/v3/mvccpb" + clientv3 "go.etcd.io/etcd/client/v3" +) + +func TestCheckpointPreservesSnapshotAcrossConflict(t *testing.T) { + ctrl := gomock.NewController(t) + cdc := etcd.NewMockCDCEtcdClient(ctrl) + raw := etcd.NewMockClient(ctrl) + cdc.EXPECT().GetEtcdClient().Return(raw).AnyTimes() + cdc.EXPECT().GetClusterID().Return("test").AnyTimes() + backend := NewEtcdBackend(cdc) + id := common.NewChangeFeedIDWithName("demo", common.DefaultKeyspaceName) + first := &config.ChangeFeedStatus{CheckpointTs: 42, Snapshot: &protocol.State{Generation: "g", Phase: "APPLYING"}} + marker := &protocol.Marker{SnapshotTS: 42, SnapshotID: "s", PlanDigest: "p"} + second := &config.ChangeFeedStatus{CheckpointTs: 42, Progress: config.ProgressStopping, Snapshot: &protocol.State{Generation: "g", Phase: "SNAPSHOT_COMMITTED", Marker: marker}} + gomock.InOrder(cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(first, int64(1), nil), raw.EXPECT().Txn(gomock.Any(), gomock.Len(1), gomock.Any(), gomock.Any()).Return(&clientv3.TxnResponse{}, nil), cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(second, int64(2), nil), raw.EXPECT().Txn(gomock.Any(), gomock.Len(1), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ []clientv3.Cmp, ops []clientv3.Op, _ []clientv3.Op) (*clientv3.TxnResponse, error) { + var s config.ChangeFeedStatus + require.NoError(t, s.Unmarshal(ops[0].ValueBytes())) + require.Equal(t, uint64(100), s.CheckpointTs) + require.Equal(t, config.ProgressStopping, s.Progress) + require.Equal(t, marker, s.Snapshot.Marker) + return &clientv3.TxnResponse{Succeeded: true}, nil + })) + require.NoError(t, backend.UpdateChangefeedCheckpointTs(context.Background(), map[common.ChangeFeedID]uint64{id: 100})) +} + +func TestSnapshotRejectsOldOwnerAndMarkerRollback(t *testing.T) { + ctrl := gomock.NewController(t) + cdc := etcd.NewMockCDCEtcdClient(ctrl) + raw := etcd.NewMockClient(ctrl) + cdc.EXPECT().GetEtcdClient().Return(raw).AnyTimes() + cdc.EXPECT().GetClusterID().Return("test").AnyTimes() + backend := NewEtcdBackend(cdc) + id := common.NewChangeFeedIDWithName("demo", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ChangefeedID: id, Epoch: 2, State: config.StateNormal} + b, e := info.Marshal() + require.NoError(t, e) + raw.EXPECT().Get(gomock.Any(), gomock.Any()).Return(&clientv3.GetResponse{Kvs: []*mvccpb.KeyValue{{Value: []byte(b), ModRevision: 7}}}, nil).Times(2) + require.ErrorContains(t, backend.SaveSnapshot(context.Background(), id, 1, &protocol.State{Generation: "g"}), "owner") + old := &protocol.State{Generation: "g", SnapshotID: "s", SnapshotTS: 42, Phase: "SNAPSHOT_COMMITTED", Marker: &protocol.Marker{SnapshotTS: 42}} + cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(&config.ChangeFeedStatus{Snapshot: old}, int64(9), nil) + require.ErrorContains(t, backend.SaveSnapshot(context.Background(), id, 2, &protocol.State{Generation: "g", SnapshotID: "s", SnapshotTS: 42}), "roll back") +} diff --git a/coordinator/coordinator.go b/coordinator/coordinator.go index 4c535c008c..5ff7c9931b 100644 --- a/coordinator/coordinator.go +++ b/coordinator/coordinator.go @@ -32,6 +32,7 @@ import ( "github.com/pingcap/ticdc/pkg/node" "github.com/pingcap/ticdc/pkg/pdutil" "github.com/pingcap/ticdc/pkg/server" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/txnutil/gc" "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/ticdc/server/watcher" @@ -123,6 +124,7 @@ func New(node *node.Info, changefeedChangeCh: make(chan []*changefeedChange, 1024), backend: backend, } + appcontext.SetService(bootstrap.RepositoryService, bootstrap.Repository(c)) // handle messages from message center mc.RegisterHandler(messaging.CoordinatorTopic, c.recvMessages) c.controller = NewController( @@ -446,7 +448,19 @@ func (c *coordinator) ListChangefeeds(ctx context.Context, keyspace string) ([]* } func (c *coordinator) GetChangefeed(ctx context.Context, changefeedDisplayName common.ChangeFeedDisplayName) (*config.ChangeFeedInfo, *config.ChangeFeedStatus, error) { - return c.controller.GetChangefeed(ctx, changefeedDisplayName) + info, status, err := c.controller.GetChangefeed(ctx, changefeedDisplayName) + if err != nil { + return nil, nil, err + } + if info.Config != nil && info.Config.Snapshot != nil { + if backend, ok := c.backend.(bootstrap.Repository); ok { + status.Snapshot, err = backend.LoadSnapshot(ctx, info.ChangefeedID, info.Epoch) + if err != nil { + return nil, nil, err + } + } + } + return info, status, nil } func (c *coordinator) GetPersistedChangefeedInfo(ctx context.Context, id common.ChangeFeedID) (*config.ChangeFeedInfo, error) { diff --git a/coordinator/snapshot.go b/coordinator/snapshot.go new file mode 100644 index 0000000000..a800c00b4d --- /dev/null +++ b/coordinator/snapshot.go @@ -0,0 +1,43 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package coordinator + +import ( + "context" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +func (c *coordinator) snapshotOwner(id common.ChangeFeedID, epoch uint64) error { + if c.closed.Load() { + return protocol.Invalid("coordinator stopped") + } + cf := c.controller.getChangefeed(id) + if cf == nil || cf.GetNodeID() != c.nodeInfo.ID || cf.GetInfo().Epoch != epoch { + return protocol.Invalid("demo snapshot requires local current maintainer") + } + return nil +} + +func (c *coordinator) LoadSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) (*protocol.State, error) { + if e := c.snapshotOwner(id, epoch); e != nil { + return nil, e + } + b, ok := c.backend.(bootstrap.Repository) + if !ok { + return nil, protocol.Invalid("backend does not support snapshots") + } + return b.LoadSnapshot(ctx, id, epoch) +} + +func (c *coordinator) SaveSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, s *protocol.State) error { + if e := c.snapshotOwner(id, epoch); e != nil { + return e + } + b, ok := c.backend.(bootstrap.Repository) + if !ok { + return protocol.Invalid("backend does not support snapshots") + } + return b.SaveSnapshot(ctx, id, epoch, s) +} diff --git a/downstreamadapter/dispatchermanager/snapshot.go b/downstreamadapter/dispatchermanager/snapshot.go new file mode 100644 index 0000000000..ad0c2308ac --- /dev/null +++ b/downstreamadapter/dispatchermanager/snapshot.go @@ -0,0 +1,126 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package dispatchermanager + +import ( + "context" + "encoding/base64" + "sync" + "time" + + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/integrity" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/tidb/pkg/util/chunk" +) + +// ApplySnapshot is the second data entry to the same capture-owned sink. It +// mounts frozen schema, preserves ordinary row routing, and waits for broker +// callbacks. It does not start or own the CSE process. +func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + stop := context.AfterFunc(e.ctx, cancel) + defer stop() + if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { + return 0, protocol.Invalid("capture write authority lost") + } + var bundle bootstrap.SchemaBundle + if err := protocol.Read(spec.SchemaRef, &bundle); err != nil { + return 0, err + } + if bundle.SnapshotTS != spec.SnapshotTS { + return 0, protocol.Invalid("schema timestamp mismatch") + } + var table *common.TableInfo + var schema string + for _, s := range bundle.Tables { + if s.TableID == ex.Range.TableID { + var err error + table, err = common.UnmarshalJSONToTableInfo(s.Data) + if err != nil { + return 0, protocol.Wrap(err) + } + schema = base64.StdEncoding.EncodeToString(s.Data) + break + } + } + if table == nil { + return 0, protocol.Invalid("missing frozen table schema") + } + mounter := commonEvent.NewMounter(time.UTC, &integrity.Config{}) + var rows uint64 + done := make(chan struct{}, 128) + queued := 0 + wait := func() error { + for queued > 0 { + select { + case <-done: + queued-- + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + } + } + return nil + } + for seq, c := range ex.Chunks { + expected := protocol.Header{Version: 1, Compression: "none", JobID: spec.JobID, SnapshotID: spec.SnapshotID, SnapshotTS: spec.SnapshotTS, PlanDigest: ref.Digest, RangeID: ex.Range.RangeID, AttemptID: ex.AttemptID, TableID: ex.Range.TableID, Seq: uint64(seq)} + _, err := protocol.DecodeChunk(c, expected, ex.Range, func(key, value []byte) error { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { + return protocol.Invalid("snapshot writer fenced") + } + chk := chunk.NewChunkWithCapacity(table.GetFieldSlice(), 1) + raw := &common.RawKVEntry{Key: key, Value: value, CRTs: spec.SnapshotTS} + n, checksum, err := mounter.DecodeToChunk(raw, table, chk) + if err != nil { + return protocol.Wrap(err) + } + if n != 1 { + return protocol.Invalid("snapshot KV did not mount to one row") + } + ev := commonEvent.NewDMLEvent(common.NewDispatcherID(), ex.Range.TableID, 0, spec.SnapshotTS, table) + ev.Rows = chk + ev.Length = 1 + ev.RowTypes = []common.RowType{common.RowTypeInsert} + ev.RowKeys = [][]byte{key} + ev.ApproximateSize = int64(len(key) + len(value)) + ev.Snapshot = &commonEvent.SnapshotRow{ID: protocol.RecordID(spec.SnapshotID, ex.Range.TableID, key), SnapshotID: spec.SnapshotID, Timestamp: spec.SnapshotTS, Schema: schema} + if checksum != nil { + ev.Checksum = append(ev.Checksum, checksum) + } + var once sync.Once + ev.AddPostFlushFunc(func() { once.Do(func() { done <- struct{}{} }) }) + e.writeSink.AddDMLEvent(ev) + queued++ + rows++ + if queued >= 128 { + return wait() + } + return nil + }) + if err != nil { + return rows, err + } + } + if err := wait(); err != nil { + return rows, err + } + if rows != ex.KVCount { + return rows, protocol.Invalid("apply count mismatch") + } + return rows, nil +} + +func (e *DispatcherManager) DrainSnapshot(ctx context.Context, epoch uint64) error { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { + return protocol.Invalid("snapshot drain fenced") + } + return nil +} diff --git a/downstreamadapter/dispatcherorchestrator/snapshot.go b/downstreamadapter/dispatcherorchestrator/snapshot.go new file mode 100644 index 0000000000..af49e6be1e --- /dev/null +++ b/downstreamadapter/dispatcherorchestrator/snapshot.go @@ -0,0 +1,51 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package dispatcherorchestrator + +import ( + "context" + "time" + + "github.com/pingcap/ticdc/downstreamadapter/dispatchermanager" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +func (m *DispatcherOrchestrator) snapshotManager(id common.ChangeFeedID) (*dispatchermanager.DispatcherManager, error) { + m.mutex.Lock() + defer m.mutex.Unlock() + e := m.dispatcherManagers[id] + if e == nil || m.fenced.Load() || m.closed.Load() { + return nil, protocol.Invalid("capture is unavailable") + } + return e, nil +} + +func (m *DispatcherOrchestrator) ApplySnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { + e, err := m.snapshotManager(id) + if err != nil { + return 0, err + } + return e.ApplySnapshot(ctx, epoch, spec, ref, ex) +} + +func (m *DispatcherOrchestrator) DrainSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) error { + e, err := m.snapshotManager(id) + if err != nil { + return err + } + return e.DrainSnapshot(ctx, epoch) +} + +// Abort waits for closure before releasing the single-host writer lock. +func (m *DispatcherOrchestrator) AbortSnapshot(id common.ChangeFeedID) { + m.mutex.Lock() + e := m.dispatcherManagers[id] + m.mutex.Unlock() + if e == nil { + return + } + e.LocalFence() + for !e.TryClose(false) { + time.Sleep(50 * time.Millisecond) + } +} diff --git a/downstreamadapter/sink/helper/mq_row_event.go b/downstreamadapter/sink/helper/mq_row_event.go index bbd8de207c..a410da47ca 100644 --- a/downstreamadapter/sink/helper/mq_row_event.go +++ b/downstreamadapter/sink/helper/mq_row_event.go @@ -53,6 +53,7 @@ func NewMQRowEvents( TotalPartition: partitionNum, }, RowEvent: commonEvent.RowEvent{ + Snapshot: event.Snapshot, PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, StartTs: event.StartTs, @@ -85,6 +86,7 @@ func NewRowEvents( } events = append(events, &commonEvent.RowEvent{ + Snapshot: event.Snapshot, PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, StartTs: event.StartTs, diff --git a/maintainer/maintainer.go b/maintainer/maintainer.go index 7d6ffb2abc..2facca073a 100644 --- a/maintainer/maintainer.go +++ b/maintainer/maintainer.go @@ -64,10 +64,13 @@ const ( // 4. checker controller, handled in threadpool, it runs the checkers to dynamically adjust the schedule // all threads are read/write information from/to the ReplicationDB type Maintainer struct { - changefeedID common.ChangeFeedID - info *config.ChangeFeedInfo - selfNode *node.Info - controller *Controller + snapshotRunning bool + snapshotDone bool + snapshotContext context.Context + changefeedID common.ChangeFeedID + info *config.ChangeFeedInfo + selfNode *node.Info + controller *Controller pdClock pdutil.Clock eventCh *chann.DrainableChann[*Event] @@ -269,6 +272,7 @@ func NewMaintainer(cfID common.ChangeFeedID, ctx, cancel := context.WithCancel(context.Background()) m.ctx = ctx m.cancel = cancel + m.snapshotContext = ctx go m.runHandleEvents(ctx) go m.calCheckpointTs(ctx) @@ -361,6 +365,14 @@ func (m *Maintainer) HandleEvent(event *Event) bool { m.onMessage(event.message) case EventPeriod: m.onPeriodTask() + case EventSnapshotDone: + m.snapshotRunning = false + if event.snapshotError != nil { + m.handleError(event.snapshotError) + } else { + m.snapshotDone = true + m.onBootstrapResponses(event.snapshotResponses) + } } return false } @@ -1156,6 +1168,9 @@ func (m *Maintainer) onBootstrapResponses(responses map[node.ID]*heartbeatpb.Mai if responses == nil || m.removing.Load() { return } + if !m.snapshotBeforeBootstrap(responses) { + return + } isMySQLSinkCompatible, err := isMysqlCompatible(m.info.SinkURI) if err != nil { m.handleError(err) diff --git a/maintainer/maintainer_event.go b/maintainer/maintainer_event.go index 6c6467f9c5..3852ab614b 100644 --- a/maintainer/maintainer_event.go +++ b/maintainer/maintainer_event.go @@ -14,8 +14,10 @@ package maintainer import ( + "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/messaging" + "github.com/pingcap/ticdc/pkg/node" ) const ( @@ -25,13 +27,16 @@ const ( EventMessage // EventPeriod is triggered periodically, maintainer handle some task in the loop, like resend messages EventPeriod + EventSnapshotDone ) // Event identify the Event that maintainer will handle in event-driven loop type Event struct { - changefeedID common.ChangeFeedID - eventType int - message *messaging.TargetMessage + snapshotError error + snapshotResponses map[node.ID]*heartbeatpb.MaintainerBootstrapResponse + changefeedID common.ChangeFeedID + eventType int + message *messaging.TargetMessage // blockStatusReleaseKeys tracks the block-status keys reserved when the // event entered the maintainer queue. They are released after HandleEvent // returns so duplicate resends stay suppressed while the event is pending. diff --git a/maintainer/snapshot.go b/maintainer/snapshot.go new file mode 100644 index 0000000000..c8be0bff97 --- /dev/null +++ b/maintainer/snapshot.go @@ -0,0 +1,101 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package maintainer + +import ( + "net/url" + "sort" + + "github.com/pingcap/ticdc/heartbeatpb" + "github.com/pingcap/ticdc/logservice/schemastore" + appcontext "github.com/pingcap/ticdc/pkg/common/context" + "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/ticdc/pkg/sink/kafka" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/tidb/pkg/tablecodec" +) + +// The first native deployment keeps a single capture. The local Capture +// interface is the seam for later MessageCenter assignment transport. +func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb.MaintainerBootstrapResponse) bool { + if m.info.Config.Snapshot == nil || m.snapshotDone { + return true + } + if m.snapshotRunning { + return false + } + cfg := m.info.Config.Snapshot + uri, err := url.Parse(m.info.SinkURI) + if err != nil { + m.handleError(protocol.Wrap(err)) + return false + } + if len(responses) != 1 || responses[m.selfNode.ID] == nil || uri.Scheme != "kafka" || uri.Query().Get("protocol") != "open-protocol" || cfg.ArtifactDir == "" || cfg.ProviderURL == "" || cfg.BackupURI == "" || len(cfg.BackupDigest) != 64 || m.enableRedo || len(m.info.Config.Filter.EventFilters) > 0 { + m.handleError(protocol.Invalid("snapshot demo requires single capture, kafka open-protocol, frozen backup digest, artifact dir, Provider and no redo/event filters")) + return false + } + options := kafka.NewOptions() + if err := options.Apply(m.changefeedID, uri, m.info.Config.Sink); err != nil { + m.handleError(err) + return false + } + if options.RequiredAcks == kafka.NoResponse { + m.handleError(protocol.Invalid("snapshot receipts require Kafka broker acknowledgements")) + return false + } + repo, ok := appcontext.TryGetService[bootstrap.Repository](bootstrap.RepositoryService) + if !ok { + m.handleError(protocol.Invalid("local coordinator snapshot service unavailable")) + return false + } + capture, ok := appcontext.TryGetService[bootstrap.Capture](appcontext.DispatcherOrchestrator) + if !ok { + m.handleError(protocol.Invalid("capture snapshot capability unavailable")) + return false + } + controller := bootstrap.Controller{ID: m.changefeedID, Epoch: m.info.Epoch, TS: m.info.StartTs, Keyspace: m.controller.keyspaceMeta.ID, Config: cfg, Repository: repo, Capture: capture, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { + bundle := bootstrap.SchemaBundle{SnapshotTS: m.info.StartTs} + tables, err := m.controller.loadTables(m.info.StartTs) + if err != nil { + return bundle, nil, protocol.Wrap(err) + } + sort.Slice(tables, func(i, j int) bool { return tables[i].TableID < tables[j].TableID }) + schemas := appcontext.GetService[schemastore.SchemaStore](appcontext.SchemaStore) + var spans []protocol.Span + for _, t := range tables { + // Snapshot mounting precedes incremental dispatcher registration. Pin + // this version explicitly while copying its frozen schema. + if err := schemas.RegisterTable(m.controller.keyspaceMeta, t.TableID, m.info.StartTs); err != nil { + return bundle, nil, protocol.Wrap(err) + } + table, err := schemas.GetTableInfo(m.controller.keyspaceMeta, t.TableID, m.info.StartTs) + unregisterErr := schemas.UnregisterTable(m.controller.keyspaceMeta, t.TableID) + if err != nil { + return bundle, nil, protocol.Wrap(err) + } + if unregisterErr != nil { + return bundle, nil, protocol.Wrap(unregisterErr) + } + b, err := table.Marshal() + if err != nil { + return bundle, nil, protocol.Wrap(err) + } + bundle.Tables = append(bundle.Tables, bootstrap.Schema{TableID: t.TableID, Data: b}) + start := tablecodec.GenTableRecordPrefix(t.TableID) + end := append([]byte(nil), start...) + end[len(end)-1]++ + spans = append(spans, protocol.Span{TableID: t.TableID, Start: start, End: end}) + } + return bundle, spans, nil + }} + m.snapshotRunning = true + go func() { + err := controller.Run(m.snapshotContext) + select { + case <-m.snapshotContext.Done(): + return + case m.eventCh.In() <- &Event{changefeedID: m.changefeedID, eventType: EventSnapshotDone, snapshotError: err, snapshotResponses: responses}: + } + }() + return false +} diff --git a/pkg/common/event/dml_event.go b/pkg/common/event/dml_event.go index 18b2cd3615..cbbd09ea9c 100644 --- a/pkg/common/event/dml_event.go +++ b/pkg/common/event/dml_event.go @@ -377,6 +377,8 @@ func (b *BatchDMLEvent) DMLCount() int { // DMLEvent represent a batch of DMLs of a whole or partial of a transaction. type DMLEvent struct { + // Snapshot is local capture metadata; never transported through EventStore. + Snapshot *SnapshotRow `json:"-"` // Version is the version of the DMLEvent struct. Version int `json:"version"` DispatcherID common.DispatcherID `json:"dispatcher_id"` diff --git a/pkg/common/event/row_change.go b/pkg/common/event/row_change.go index 1d16eb358a..0b4a1b4ed0 100644 --- a/pkg/common/event/row_change.go +++ b/pkg/common/event/row_change.go @@ -88,7 +88,15 @@ type TopicPartitionKey struct { TotalPartition int32 } +type SnapshotRow struct { + ID string + SnapshotID string + Timestamp uint64 + Schema string +} + type RowEvent struct { + Snapshot *SnapshotRow PhysicalTableID int64 TableInfo *common.TableInfo StartTs uint64 diff --git a/pkg/config/changefeed.go b/pkg/config/changefeed.go index 4faedeffbd..262fd0c329 100644 --- a/pkg/config/changefeed.go +++ b/pkg/config/changefeed.go @@ -23,6 +23,7 @@ import ( "github.com/pingcap/log" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/ticdc/pkg/version" "github.com/tikv/client-go/v2/oracle" @@ -189,6 +190,7 @@ func (t AdminJobType) IsStopState() bool { } type ChangefeedConfig struct { + Snapshot *protocol.Config `json:"snapshot,omitempty"` ChangefeedID common.ChangeFeedID `json:"changefeed_id"` PerformanceMode string `json:"performance_mode"` StartTS uint64 `json:"start_ts"` @@ -299,6 +301,7 @@ func (info *ChangeFeedInfo) ToChangefeedConfig() *ChangefeedConfig { } } return &ChangefeedConfig{ + Snapshot: info.Config.Snapshot, ChangefeedID: info.ChangefeedID, PerformanceMode: util.GetOrZero(info.Config.PerformanceMode), StartTS: info.StartTs, @@ -765,7 +768,8 @@ var ( // ChangeFeedStatus stores information about a ChangeFeed // It is stored in etcd. type ChangeFeedStatus struct { - CheckpointTs uint64 `json:"checkpoint-ts"` + Snapshot *protocol.State `json:"snapshot,omitempty"` + CheckpointTs uint64 `json:"checkpoint-ts"` // Progress indicates changefeed progress status Progress Progress `json:"progress"` diff --git a/pkg/config/replica_config.go b/pkg/config/replica_config.go index 37f96d527e..8c5f34ed7c 100644 --- a/pkg/config/replica_config.go +++ b/pkg/config/replica_config.go @@ -27,6 +27,7 @@ import ( cerror "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/integrity" "github.com/pingcap/ticdc/pkg/redo" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/util" "go.uber.org/zap" ) @@ -152,12 +153,13 @@ type ReplicaConfig replicaConfig type replicaConfig struct { // Pause is a CLI create-only option, forwarded to the API creation request. // It does not control the state of an existing changefeed. - Pause *bool `toml:"pause" json:"pause,omitempty"` - PerformanceMode *string `toml:"performance-mode" json:"performance-mode,omitempty"` - MemoryQuota *uint64 `toml:"memory-quota" json:"memory-quota,omitempty"` - CaseSensitive *bool `toml:"case-sensitive" json:"case-sensitive,omitempty"` - ForceReplicate *bool `toml:"force-replicate" json:"force-replicate,omitempty"` - CheckGCSafePoint *bool `toml:"check-gc-safe-point" json:"check-gc-safe-point,omitempty"` + Pause *bool `toml:"pause" json:"pause,omitempty"` + Snapshot *protocol.Config `toml:"snapshot" json:"snapshot,omitempty"` + PerformanceMode *string `toml:"performance-mode" json:"performance-mode,omitempty"` + MemoryQuota *uint64 `toml:"memory-quota" json:"memory-quota,omitempty"` + CaseSensitive *bool `toml:"case-sensitive" json:"case-sensitive,omitempty"` + ForceReplicate *bool `toml:"force-replicate" json:"force-replicate,omitempty"` + CheckGCSafePoint *bool `toml:"check-gc-safe-point" json:"check-gc-safe-point,omitempty"` // AllowSameCluster allows the downstream to be the same TiDB logical cluster as the upstream. // By default TiCDC rejects such a changefeed to avoid self-replication loops. Set it to true // only when the changefeed cannot capture its own writes, for example when the downstream diff --git a/pkg/errors/snapshot.go b/pkg/errors/snapshot.go new file mode 100644 index 0000000000..2b420100ce --- /dev/null +++ b/pkg/errors/snapshot.go @@ -0,0 +1,6 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package errors + +import "github.com/pingcap/errors" + +var ErrSnapshotBootstrap = errors.Normalize("snapshot bootstrap: %s", errors.RFCCodeText("CDC:ErrSnapshotBootstrap")) diff --git a/pkg/sink/codec/open/codec.go b/pkg/sink/codec/open/codec.go index dd76fdfdf0..75527f2567 100644 --- a/pkg/sink/codec/open/codec.go +++ b/pkg/sink/codec/open/codec.go @@ -45,6 +45,13 @@ func encodeRowChangedEvent( keyWriter.WriteObject(func() { keyWriter.WriteUint64Field("ts", e.CommitTs) + if e.Snapshot != nil { + keyWriter.WriteStringField("snapshot_record_id", e.Snapshot.ID) + keyWriter.WriteStringField("snapshot_id", e.Snapshot.SnapshotID) + keyWriter.WriteUint64Field("snapshot_ts", e.Snapshot.Timestamp) + keyWriter.WriteStringField("snapshot_schema", e.Snapshot.Schema) + keyWriter.WriteStringField("snapshot_schema_encoding", "ticdc-table-info-base64-v1") + } keyWriter.WriteStringField("scm", e.TableInfo.GetTargetSchemaName()) keyWriter.WriteStringField("tbl", e.TableInfo.GetTargetTableName()) keyWriter.WriteIntField("t", int(common.MessageTypeRow)) diff --git a/pkg/sink/codec/open/snapshot_test.go b/pkg/sink/codec/open/snapshot_test.go new file mode 100644 index 0000000000..82536e1431 --- /dev/null +++ b/pkg/sink/codec/open/snapshot_test.go @@ -0,0 +1,30 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package open + +import ( + "testing" + + "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/sink/codec/common" + "github.com/stretchr/testify/require" +) + +func TestSnapshotEnvelopeKeepsIdentityAndInlineSchema(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + helper.DDL2Job("create table test.snap (id int primary key, v int)") + event := helper.DML2Event("test", "snap", "insert into test.snap values(1,10)") + row, ok := event.GetNextRow() + require.True(t, ok) + e := &commonEvent.RowEvent{PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, Event: row, CommitTs: 42, ColumnSelector: columnselector.NewDefaultColumnSelector(), Snapshot: &commonEvent.SnapshotRow{ID: "stable", SnapshotID: "generation", Timestamp: 42, Schema: "c2NoZW1h"}} + key, _, _, err := encodeRowChangedEvent(e, initColumnFlags(e.TableInfo), common.NewConfig(config.ProtocolOpen), false, "") + require.NoError(t, err) + require.Contains(t, string(key), `"snapshot_record_id":"stable"`) + require.Contains(t, string(key), `"snapshot_schema":"c2NoZW1h"`) + e.Snapshot = nil + key, _, _, err = encodeRowChangedEvent(e, initColumnFlags(e.TableInfo), common.NewConfig(config.ProtocolOpen), false, "") + require.NoError(t, err) + require.NotContains(t, string(key), "snapshot_record_id") +} diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go new file mode 100644 index 0000000000..39b973dff7 --- /dev/null +++ b/pkg/snapshot/bootstrap/controller.go @@ -0,0 +1,239 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package bootstrap + +import ( + "context" + "os" + "path/filepath" + "syscall" + "time" + + "github.com/google/uuid" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/snapshot/provider" + "github.com/pingcap/ticdc/pkg/snapshot/store" +) + +type Controller struct { + ID common.ChangeFeedID + Epoch uint64 + TS uint64 + Keyspace uint32 + Config *protocol.Config + Repository Repository + Capture Capture + Freeze func() (SchemaBundle, []protocol.Span, error) +} + +func (c Controller) Run(ctx context.Context) (result error) { + objects := store.Local{Root: c.Config.ArtifactDir} + dir := filepath.Join(objects.Root, "cdc", c.ID.ID().String()) + if err := os.MkdirAll(dir, 0o700); err != nil { + return protocol.Wrap(err) + } + lock, err := os.OpenFile(filepath.Join(dir, "writer.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return protocol.Wrap(err) + } + defer lock.Close() + if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + return protocol.Invalid("previous snapshot writer has not drained") + } + defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + // An aborted writer must stop actual sink mutation before a new owner can + // acquire the lock. Process death releases flock; old process cannot retry. + defer func() { + if result != nil { + c.Capture.AbortSnapshot(c.ID) + } + }() + state, err := c.Repository.LoadSnapshot(ctx, c.ID, c.Epoch) + if err != nil { + return err + } + if state != nil && state.Marker != nil { + return nil + } + if state == nil { + gen := uuid.NewString() + state = &protocol.State{Generation: gen, SnapshotID: gen, SnapshotTS: c.TS, Phase: "PREPARING"} + if err = c.Repository.SaveSnapshot(ctx, c.ID, c.Epoch, state); err != nil { + return err + } + } + save := func() error { return c.Repository.SaveSnapshot(ctx, c.ID, c.Epoch, state) } + if state.SpecRef.URI == "" { + bundle, spans, err := c.Freeze() + if err != nil { + return err + } + schema, err := objects.Put("cdc/"+state.Generation+"/schema.json", bundle) + if err != nil { + return err + } + spec := protocol.Spec{ProtocolVersion: 1, JobID: state.Generation, SnapshotID: state.SnapshotID, SnapshotTS: c.TS, KeyspaceID: c.Keyspace, BackupURI: c.Config.BackupURI, BackupDigest: c.Config.BackupDigest, SelectedSpans: spans, SchemaRef: schema} + state.SpecRef, err = objects.Put("cdc/"+state.Generation+"/spec.json", spec) + if err != nil { + return err + } + state.Phase = "PLANNING" + if err = save(); err != nil { + return err + } + } + var spec protocol.Spec + if err = protocol.Read(state.SpecRef, &spec); err != nil { + return err + } + client := provider.Client{URL: c.Config.ProviderURL} + var job provider.Job + if err = client.Call(ctx, "ensure", provider.Request{SpecRef: state.SpecRef}, &job); err != nil { + return err + } + wait := func() error { + select { + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + case <-time.After(200 * time.Millisecond): + return nil + } + } + for job.PlanRef.URI == "" { + if job.Phase == "FAILED" || job.Phase == "CANCELED" { + return protocol.Invalid("export failed: %s", job.Error) + } + if err = wait(); err != nil { + return err + } + if err = client.Call(ctx, "status", provider.Request{JobID: spec.JobID}, &job); err != nil { + return err + } + } + var plan protocol.Plan + if err = protocol.Read(job.PlanRef, &plan); err != nil { + return err + } + if err = protocol.ValidatePlan(spec, plan); err != nil { + return err + } + if state.PlanRef.URI != "" && state.PlanRef != job.PlanRef { + return protocol.Invalid("accepted plan changed") + } + state.PlanRef = job.PlanRef + state.Total = len(plan.Ranges) + state.Barrier = true + state.Phase = "APPLYING" + if err = save(); err != nil { + return err + } + tasks := store.Tasks{Objects: objects, Job: spec.JobID, Digest: job.PlanRef.Digest, Epoch: c.Epoch, Plan: plan} + if err = tasks.Init(); err != nil { + return err + } + complete := false + for { + all, err := tasks.List() + if err != nil { + return err + } + applied := 0 + for _, task := range all { + if task.State == "APPLIED" { + applied++ + continue + } + if task.State != "READY" { + continue + } + assigned, err := tasks.Assign(task.Range.RangeID) + if err != nil { + return err + } + var ex protocol.Export + if err = protocol.Read(assigned.Export, &ex); err != nil { + return err + } + if err = protocol.ValidateExport(spec, state.PlanRef, task.Range, ex); err != nil { + return err + } + rows, err := c.Capture.ApplySnapshot(ctx, c.ID, c.Epoch, spec, state.PlanRef, ex) + if err != nil { + return err + } + if err = tasks.Commit(task.Range.RangeID, assigned.Lease, rows); err != nil { + return err + } + applied++ + } + state.Applied = applied + if err = save(); err != nil { + return err + } + if complete && applied == len(plan.Ranges) { + break + } + var page provider.Page + if err = client.Call(ctx, "list", provider.Request{JobID: spec.JobID, Cursor: state.Cursor, Limit: 64}, &page); err != nil { + return err + } + for _, ref := range page.Exports { + var ex protocol.Export + if err = protocol.Read(ref, &ex); err != nil { + return err + } + found := false + for _, r := range plan.Ranges { + if r.RangeID == ex.Range.RangeID { + found = true + if err = protocol.ValidateExport(spec, state.PlanRef, r, ex); err != nil { + return err + } + break + } + } + if !found { + return protocol.Invalid("provider returned unknown range") + } + if err = tasks.Ready(ex.Range.RangeID, ref); err != nil { + return err + } + } + // Task pages are durable before advancing the runtime cursor. + state.Cursor = page.Cursor + complete = page.Complete + if err = save(); err != nil { + return err + } + if len(page.Exports) == 0 { + if err = client.Call(ctx, "status", provider.Request{JobID: spec.JobID}, &job); err != nil { + return err + } + if job.Phase == "FAILED" || job.Phase == "CANCELED" { + return protocol.Invalid("source job failed: %s", job.Error) + } + if err = wait(); err != nil { + return err + } + } + } + state.Phase = "DRAINING" + if err = save(); err != nil { + return err + } + if err = c.Capture.DrainSnapshot(ctx, c.ID, c.Epoch); err != nil { + return err + } + all, err := tasks.List() + if err != nil { + return err + } + for i, t := range all { + if !protocol.SameSpan(t.Range, plan.Ranges[i]) || t.State != "APPLIED" { + return protocol.Invalid("incomplete exact range receipts") + } + } + state.Marker = &protocol.Marker{SnapshotTS: spec.SnapshotTS, SnapshotID: spec.SnapshotID, PlanDigest: state.PlanRef.Digest, OutputFence: "single-capture-all-broker-acks"} + state.Phase = "SNAPSHOT_COMMITTED" + return save() +} diff --git a/pkg/snapshot/bootstrap/interfaces.go b/pkg/snapshot/bootstrap/interfaces.go new file mode 100644 index 0000000000..2190b1834f --- /dev/null +++ b/pkg/snapshot/bootstrap/interfaces.go @@ -0,0 +1,31 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package bootstrap + +import ( + "context" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +const RepositoryService = "SnapshotRuntimeRepository" + +// Repository is implemented by Coordinator, using the existing changefeed +// runtime status key and ownership epoch. Mutate preserves concurrent fields. +type Repository interface { + LoadSnapshot(context.Context, common.ChangeFeedID, uint64) (*protocol.State, error) + SaveSnapshot(context.Context, common.ChangeFeedID, uint64, *protocol.State) error +} +type Capture interface { + AbortSnapshot(common.ChangeFeedID) + ApplySnapshot(context.Context, common.ChangeFeedID, uint64, protocol.Spec, protocol.ObjectRef, protocol.Export) (uint64, error) + DrainSnapshot(context.Context, common.ChangeFeedID, uint64) error +} +type Schema struct { + TableID int64 `json:"physical_table_id"` + Data []byte `json:"table_info"` +} +type SchemaBundle struct { + SnapshotTS uint64 `json:"snapshot_ts"` + Tables []Schema `json:"tables"` +} diff --git a/pkg/snapshot/protocol/chunk.go b/pkg/snapshot/protocol/chunk.go new file mode 100644 index 0000000000..4fe7e7290d --- /dev/null +++ b/pkg/snapshot/protocol/chunk.go @@ -0,0 +1,160 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package protocol + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "io" + "os" +) + +// DecodeChunk first verifies the entire immutable object before emitting rows. +// The local artifact backend doubles as a bounded spool (64 MiB per object). +func DecodeChunk(ref Chunk, expected Header, span Span, emit func([]byte, []byte) error) (Footer, error) { + var zero Footer + if ref.Size < 0 || ref.Size > 64<<20 { + return zero, Invalid("chunk exceeds demo size limit") + } + info, err := os.Stat(ref.URI) + if err != nil { + return zero, Wrap(err) + } + if info.Size() != ref.Size { + return zero, Invalid("chunk size mismatch") + } + actual, err := Ref(ref.URI) + if err != nil { + return zero, err + } + if actual != ref.ObjectRef { + return zero, Invalid("chunk checksum/size mismatch") + } + f, err := os.Open(ref.URI) + if err != nil { + return zero, Wrap(err) + } + defer f.Close() + return decode(f, expected, span, ref, emit) +} + +func readN(r io.Reader, n uint32, max uint32) ([]byte, error) { + if n > max { + return nil, Invalid("frame exceeds limit") + } + b := make([]byte, n) + _, e := io.ReadFull(r, b) + return b, Wrap(e) +} + +func readU32(r io.Reader) (uint32, error) { + var b [4]byte + _, e := io.ReadFull(r, b[:]) + return binary.LittleEndian.Uint32(b[:]), Wrap(e) +} + +func decode(r io.Reader, expected Header, span Span, ref Chunk, emit func([]byte, []byte) error) (Footer, error) { + var seen Footer + magic, e := readN(r, 8, 8) + if e != nil { + return seen, e + } + if string(magic) != "SNAPKV01" { + return seen, Invalid("invalid chunk magic") + } + n, e := readU32(r) + if e != nil { + return seen, e + } + b, e := readN(r, n, 64<<10) + if e != nil { + return seen, e + } + var h Header + if e = json.Unmarshal(b, &h); e != nil { + return seen, Wrap(e) + } + if h != expected || h.Version != 1 || h.Compression != "none" { + return seen, Invalid("chunk header mismatch or unsupported version") + } + for { + n, e = readU32(r) + if e != nil { + return seen, e + } + count, e := readU32(r) + if e != nil { + return seen, e + } + if n == 0 { + b, e = readN(r, count, 64<<10) + if e != nil { + return seen, e + } + var footer Footer + if e = json.Unmarshal(b, &footer); e != nil { + return seen, Wrap(e) + } + end, e := readN(r, 8, 8) + if e != nil { + return seen, e + } + if string(end) != "SNAPEND1" { + return seen, Invalid("missing footer magic") + } + var tail [1]byte + if n, err := r.Read(tail[:]); n != 0 || err != io.EOF { + return seen, Invalid("trailing chunk bytes") + } + if footer.Blocks != seen.Blocks || footer.KVCount != seen.KVCount || footer.LogicalBytes != seen.LogicalBytes || !bytes.Equal(footer.First, seen.First) || !bytes.Equal(footer.Last, seen.Last) || footer.KVCount != ref.KVCount || footer.LogicalBytes != ref.LogicalBytes || !bytes.Equal(footer.First, ref.First) || !bytes.Equal(footer.Last, ref.Last) { + return seen, Invalid("footer/statistics mismatch") + } + return footer, nil + } + if count == 0 || count > n/8 { + return seen, Invalid("invalid block count") + } + b, e = readN(r, n, (16<<20)+8) + if e != nil { + return seen, e + } + block := bytes.NewReader(b) + for i := uint32(0); i < count; i++ { + kl, e := readU32(block) + if e != nil { + return seen, e + } + vl, e := readU32(block) + if e != nil { + return seen, e + } + if kl == 0 || uint64(kl)+uint64(vl) > 16<<20 { + return seen, Invalid("record exceeds limit") + } + k, e := readN(block, kl, 16<<20) + if e != nil { + return seen, e + } + v, e := readN(block, vl, 16<<20) + if e != nil { + return seen, e + } + if bytes.Compare(k, span.Start) < 0 || bytes.Compare(k, span.End) >= 0 || seen.KVCount > 0 && bytes.Compare(seen.Last, k) >= 0 { + return seen, Invalid("key bounds/order violation") + } + if seen.KVCount == 0 { + seen.First = k + } + seen.Last = k + seen.KVCount++ + seen.LogicalBytes += uint64(kl) + uint64(vl) + if e = emit(k, v); e != nil { + return seen, e + } + } + if block.Len() != 0 { + return seen, Invalid("block trailing bytes") + } + seen.Blocks++ + } +} diff --git a/pkg/snapshot/protocol/protocol_test.go b/pkg/snapshot/protocol/protocol_test.go new file mode 100644 index 0000000000..afa1b5f4b1 --- /dev/null +++ b/pkg/snapshot/protocol/protocol_test.go @@ -0,0 +1,70 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package protocol + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCoverageAndStableIdentity(t *testing.T) { + spec := Spec{JobID: "j", SnapshotID: "s", SnapshotTS: 1, SelectedSpans: []Span{{TableID: 1, Start: []byte("a"), End: []byte("z")}}} + good := Plan{ProtocolVersion: 1, JobID: "j", SnapshotID: "s", SnapshotTS: 1, Ranges: []Span{{"r0", 1, []byte("a"), []byte("m")}, {"r1", 1, []byte("m"), []byte("z")}}} + require.NoError(t, ValidatePlan(spec, good)) + for _, r := range []Span{{"r1", 1, []byte("n"), []byte("z")}, {"r1", 1, []byte("l"), []byte("z")}, {"r0", 1, []byte("m"), []byte("z")}, {"r1", 2, []byte("m"), []byte("z")}} { + p := good + p.Ranges = append([]Span(nil), good.Ranges...) + p.Ranges[1] = r + require.Error(t, ValidatePlan(spec, p)) + } + require.Equal(t, RecordID("s", 1, []byte("a")), RecordID("s", 1, []byte("a"))) + require.NotEqual(t, RecordID("s", 1, []byte("a")), RecordID("s", 2, []byte("a"))) + require.NotEqual(t, RecordID("ab", 1, []byte("c")), RecordID("a", 1, []byte("bc"))) +} + +func TestRustGoldenAndCorruption(t *testing.T) { + path := "testdata/rust-v1.skv" + b, err := os.ReadFile(path) + require.NoError(t, err) + expected := Header{Version: 1, Compression: "none", JobID: "golden", SnapshotID: "golden", SnapshotTS: 42, PlanDigest: "golden", RangeID: "r0", AttemptID: "a0", TableID: 1} + ref := Chunk{KVCount: 2, LogicalBytes: 12, First: []byte("a"), Last: []byte("b")} + span := Span{Start: []byte("a"), End: []byte("z")} + var got []string + footer, err := decode(bytes.NewReader(b), expected, span, ref, func(k, v []byte) error { got = append(got, string(k)); return nil }) + require.NoError(t, err) + require.Equal(t, uint64(2), footer.KVCount) + require.Equal(t, []string{"a", "b"}, got) + for _, bad := range [][]byte{b[:len(b)-1], append(append([]byte(nil), b...), 0), append([]byte("BADMAGIC"), b[8:]...)} { + _, err := decode(bytes.NewReader(bad), expected, span, ref, func([]byte, []byte) error { return nil }) + require.Error(t, err) + } + bad := append([]byte(nil), b...) + binary.LittleEndian.PutUint32(bad[8:12], ^uint32(0)) + _, err = decode(bytes.NewReader(bad), expected, span, ref, func([]byte, []byte) error { return nil }) + require.Error(t, err) + f := filepath.Join(t.TempDir(), "chunk") + require.NoError(t, os.WriteFile(f, b, 0o600)) + ref.ObjectRef, err = Ref(f) + require.NoError(t, err) + bad = append([]byte(nil), b...) + bad[len(bad)/2] ^= 1 + require.NoError(t, os.WriteFile(f, bad, 0o600)) + called := false + _, err = DecodeChunk(ref, expected, span, func([]byte, []byte) error { called = true; return nil }) + require.Error(t, err) + require.False(t, called) +} + +func TestStateRoundTrip(t *testing.T) { + state := State{Generation: "g", Phase: "SNAPSHOT_COMMITTED", Marker: &Marker{SnapshotTS: 42}} + b, e := json.Marshal(state) + require.NoError(t, e) + var out State + require.NoError(t, json.Unmarshal(b, &out)) + require.Equal(t, state, out) +} diff --git a/pkg/snapshot/protocol/testdata/rust-v1.skv b/pkg/snapshot/protocol/testdata/rust-v1.skv new file mode 100644 index 0000000000000000000000000000000000000000..dcbdb0b28d7344a107a7e26d291a964483b2d42e GIT binary patch literal 348 zcmZ{g!Ait15QejQ@FhIWxk4+R3VT@4ldvcY3!cKHolRrYBqnL0Ec<%Cmd;v5FCKov z|C5>dW_H`n)8oFZ-h~iHXu8q$^5EluSxyv_@eb;$fLE`iX`u$~ZA%UcNDf2leEu)a z3F^Ds0wOw1%cod!9p+3!_%6e95-d8|8ciwx9T2)XnFg)QsO-{#K^DS9Z%~)){176g z1rwZi1gC4>gX188{5vVy6 huTyb!FfnD>)6A$Z&+9ewTl`HlC#N0X^kI8neF7@AYBT@< literal 0 HcmV?d00001 diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go new file mode 100644 index 0000000000..034eea58ba --- /dev/null +++ b/pkg/snapshot/protocol/types.go @@ -0,0 +1,236 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package protocol + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "sort" + + "github.com/pingcap/ticdc/pkg/errors" +) + +func Invalid(format string, args ...any) error { + return errors.ErrSnapshotBootstrap.GenWithStackByArgs(fmt.Sprintf(format, args...)) +} + +func Wrap(err error) error { + if err == nil { + return nil + } + return errors.WrapError(errors.ErrSnapshotBootstrap, err, "I/O or encoding") +} + +type ObjectRef struct { + URI string `json:"uri"` + Digest string `json:"digest"` + Size int64 `json:"size"` +} +type Span struct { + RangeID string `json:"range_id,omitempty"` + TableID int64 `json:"physical_table_id"` + Start []byte `json:"start_key"` + End []byte `json:"end_key"` +} +type Spec struct { + ProtocolVersion int `json:"protocol_version"` + JobID string `json:"job_id"` + SnapshotID string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + KeyspaceID uint32 `json:"keyspace_id"` + BackupURI string `json:"backup_uri"` + BackupDigest string `json:"backup_digest"` + SelectedSpans []Span `json:"selected_spans"` + SchemaRef ObjectRef `json:"schema_ref"` +} +type Plan struct { + ProtocolVersion int `json:"protocol_version"` + JobID string `json:"job_id"` + SnapshotID string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + Ranges []Span `json:"ranges"` +} +type Chunk struct { + ObjectRef + KVCount uint64 `json:"kv_count"` + LogicalBytes uint64 `json:"logical_bytes"` + First []byte `json:"first_key"` + Last []byte `json:"last_key"` +} +type Export struct { + ProtocolVersion int `json:"protocol_version"` + JobID string `json:"job_id"` + SnapshotID string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + PlanDigest string `json:"plan_digest"` + Range Span `json:"range"` + AttemptID string `json:"attempt_id"` + Chunks []Chunk `json:"chunks"` + KVCount uint64 `json:"kv_count"` +} +type Header struct { + Version int `json:"chunk_format_version"` + Compression string `json:"compression"` + JobID string `json:"job_id"` + SnapshotID string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + PlanDigest string `json:"plan_digest"` + RangeID string `json:"range_id"` + AttemptID string `json:"attempt_id"` + TableID int64 `json:"physical_table_id"` + Seq uint64 `json:"chunk_seq"` +} +type Footer struct { + Blocks uint64 `json:"block_count"` + KVCount uint64 `json:"kv_count"` + LogicalBytes uint64 `json:"logical_bytes"` + First []byte `json:"first_key"` + Last []byte `json:"last_key"` +} + +// State is the optional snapshot child of ChangeFeedStatus, never a second job key. +type State struct { + Generation string `json:"generation"` + SnapshotID string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + Phase string `json:"phase"` + SpecRef ObjectRef `json:"spec_ref"` + PlanRef ObjectRef `json:"plan_ref"` + Cursor string `json:"ready_cursor"` + Barrier bool `json:"sink_bootstrap_barrier"` + Applied int `json:"applied"` + Total int `json:"total"` + Marker *Marker `json:"global_marker,omitempty"` +} +type Marker struct { + SnapshotTS uint64 `json:"snapshot_ts"` + SnapshotID string `json:"snapshot_id"` + PlanDigest string `json:"plan_digest"` + OutputFence string `json:"output_fence"` +} + +// Config is opt-in. The initial deployment uses one capture and a shared local +// artifact directory. Provider and capture are independent modules. +type Config struct { + BackupURI string `toml:"backup-uri" json:"backup-uri"` + BackupDigest string `toml:"backup-digest" json:"backup-digest"` + ProviderURL string `toml:"provider-url" json:"provider-url"` + ArtifactDir string `toml:"artifact-dir" json:"artifact-dir"` +} + +func Digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } +func Ref(path string) (ObjectRef, error) { + f, e := os.Open(path) + if e != nil { + return ObjectRef{}, Wrap(e) + } + defer f.Close() + h := sha256.New() + n, e := io.Copy(h, f) + return ObjectRef{path, hex.EncodeToString(h.Sum(nil)), n}, Wrap(e) +} + +func Read(ref ObjectRef, dst any) error { + if ref.Size < 0 || ref.Size > 4<<20 { + return Invalid("metadata size exceeds 4 MiB") + } + f, e := os.Open(ref.URI) + if e != nil { + return Wrap(e) + } + defer f.Close() + b, e := io.ReadAll(io.LimitReader(f, (4<<20)+1)) + if e != nil { + return Wrap(e) + } + if int64(len(b)) != ref.Size || Digest(b) != ref.Digest { + return Invalid("metadata checksum mismatch") + } + return Wrap(json.Unmarshal(b, dst)) +} + +func SameSpan(a, b Span) bool { + return a.RangeID == b.RangeID && a.TableID == b.TableID && bytes.Equal(a.Start, b.Start) && bytes.Equal(a.End, b.End) +} + +func ValidatePlan(spec Spec, p Plan) error { + if p.ProtocolVersion != 1 || p.JobID != spec.JobID || p.SnapshotID != spec.SnapshotID || p.SnapshotTS != spec.SnapshotTS { + return Invalid("plan identity mismatch") + } + spans := append([]Span(nil), spec.SelectedSpans...) + ranges := append([]Span(nil), p.Ranges...) + less := func(a, b Span) bool { + if a.TableID != b.TableID { + return a.TableID < b.TableID + } + return bytes.Compare(a.Start, b.Start) < 0 + } + sort.Slice(spans, func(i, j int) bool { return less(spans[i], spans[j]) }) + sort.Slice(ranges, func(i, j int) bool { return less(ranges[i], ranges[j]) }) + ids := map[string]bool{} + idx := 0 + for i, s := range spans { + if len(s.Start) == 0 || bytes.Compare(s.Start, s.End) >= 0 { + return Invalid("invalid selection") + } + if i > 0 && s.TableID == spans[i-1].TableID && bytes.Compare(spans[i-1].End, s.Start) > 0 { + return Invalid("overlapping selected spans") + } + next := s.Start + for idx < len(ranges) && ranges[idx].TableID == s.TableID && bytes.Compare(ranges[idx].Start, s.End) < 0 { + r := ranges[idx] + if r.RangeID == "" || ids[r.RangeID] || !bytes.Equal(r.Start, next) || bytes.Compare(r.Start, r.End) >= 0 || bytes.Compare(r.End, s.End) > 0 { + return Invalid("coverage hole, overlap, or duplicate range") + } + ids[r.RangeID] = true + next = r.End + idx++ + } + if !bytes.Equal(next, s.End) { + return Invalid("incomplete coverage") + } + } + if idx != len(ranges) { + return Invalid("unselected range") + } + return nil +} + +func ValidateExport(spec Spec, plan ObjectRef, r Span, e Export) error { + if e.ProtocolVersion != 1 || e.JobID != spec.JobID || e.SnapshotID != spec.SnapshotID || e.SnapshotTS != spec.SnapshotTS || e.PlanDigest != plan.Digest || !SameSpan(r, e.Range) || e.AttemptID == "" { + return Invalid("export identity mismatch") + } + var count uint64 + var last []byte + for _, c := range e.Chunks { + if c.Size <= 0 || c.Size > 64<<20 || c.KVCount == 0 || len(c.Digest) != 64 || bytes.Compare(c.First, r.Start) < 0 || bytes.Compare(c.First, c.Last) > 0 || bytes.Compare(c.Last, r.End) >= 0 || last != nil && bytes.Compare(last, c.First) >= 0 { + return Invalid("invalid chunk bounds or size") + } + last = c.Last + count += c.KVCount + } + if count != e.KVCount { + return Invalid("export count mismatch") + } + return nil +} + +func RecordID(snapshot string, table int64, key []byte) string { + h := sha256.New() + h.Write([]byte("snapshot-key-v1\x00")) + var b [8]byte + binary.BigEndian.PutUint32(b[:4], uint32(len(snapshot))) + h.Write(b[:4]) + h.Write([]byte(snapshot)) + binary.BigEndian.PutUint64(b[:], uint64(table)) + h.Write(b[:]) + binary.BigEndian.PutUint32(b[:4], uint32(len(key))) + h.Write(b[:4]) + h.Write(key) + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/pkg/snapshot/provider/client.go b/pkg/snapshot/provider/client.go new file mode 100644 index 0000000000..bcf16fa0ff --- /dev/null +++ b/pkg/snapshot/provider/client.go @@ -0,0 +1,38 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package provider + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "time" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +type Client struct{ URL string } + +func (c Client) Call(ctx context.Context, method string, req Request, out any) error { + b, e := json.Marshal(req) + if e != nil { + return protocol.Wrap(e) + } + r, e := http.NewRequestWithContext(ctx, "POST", c.URL+"/"+method, bytes.NewReader(b)) + if e != nil { + return protocol.Wrap(e) + } + r.Header.Set("Content-Type", "application/json") + client := http.Client{Timeout: 30 * time.Second} + resp, e := client.Do(r) + if e != nil { + return protocol.Wrap(e) + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return protocol.Invalid("provider %s: %s", method, b) + } + return protocol.Wrap(json.NewDecoder(io.LimitReader(resp.Body, 4<<20)).Decode(out)) +} diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/provider/provider.go new file mode 100644 index 0000000000..fa129ef625 --- /dev/null +++ b/pkg/snapshot/provider/provider.go @@ -0,0 +1,388 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +// Package provider implements BR's export controller. It never decodes rows or +// opens a sink. The local Runner is confined to this package/process. +package provider + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/snapshot/store" +) + +type Job struct { + Spec protocol.Spec `json:"spec"` + SpecRef protocol.ObjectRef `json:"spec_ref"` + Phase string `json:"phase"` + PlanRef protocol.ObjectRef `json:"plan_ref"` + Exports []protocol.ObjectRef `json:"exports"` + Error string `json:"error,omitempty"` +} +type Page struct { + Exports []protocol.ObjectRef `json:"exports"` + Cursor string `json:"next_cursor"` + Complete bool `json:"source_complete"` +} +type Request struct { + JobID string `json:"job_id"` + SpecRef protocol.ObjectRef `json:"spec_ref"` + Cursor string `json:"cursor"` + Limit int `json:"limit"` +} +type Server struct { + Objects store.Local + Binary string + mu sync.Mutex + running map[string]context.CancelFunc +} + +func New(root, binary string) *Server { + return &Server{Objects: store.Local{Root: root}, Binary: binary, running: map[string]context.CancelFunc{}} +} +func key(id string) string { return "br/" + id + "/control.json" } +func validID(id string) bool { + if id == "" || len(id) > 128 { + return false + } + for _, r := range id { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-') { + return false + } + } + return true +} + +func (s *Server) update(id string, fn func(*Job) error) error { + for retry := 0; retry < 30; retry++ { + var j Job + v, e := s.Objects.Read(key(id), &j) + if e != nil { + return e + } + if v == "" { + return protocol.Invalid("unknown job") + } + if e = fn(&j); e != nil { + return e + } + ok, e := s.Objects.CAS(key(id), v, j) + if e != nil { + return e + } + if ok { + return nil + } + } + return protocol.Invalid("job CAS contention") +} + +func (s *Server) Ensure(ref protocol.ObjectRef) (Job, error) { + var spec protocol.Spec + if e := protocol.Read(ref, &spec); e != nil { + return Job{}, e + } + if !validID(spec.JobID) || spec.ProtocolVersion != 1 || spec.SnapshotTS == 0 || len(spec.SelectedSpans) > 256 { + return Job{}, protocol.Invalid("invalid or oversized demo spec") + } + j := Job{Spec: spec, SpecRef: ref, Phase: "ACCEPTED"} + _, e := s.Objects.CAS(key(spec.JobID), "", j) + if e != nil { + return j, e + } + _, e = s.Objects.Read(key(spec.JobID), &j) + if e != nil { + return j, e + } + if j.SpecRef != ref { + return j, protocol.Invalid("Ensure identity conflict") + } + if j.Phase != "SOURCE_COMPLETE" && j.Phase != "FAILED" && j.Phase != "CANCELED" { + s.start(spec.JobID) + } + return j, nil +} + +func (s *Server) start(id string) { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.running[id]; ok { + return + } + ctx, cancel := context.WithCancel(context.Background()) + s.running[id] = cancel + go func() { + defer func() { cancel(); s.mu.Lock(); delete(s.running, id); s.mu.Unlock() }() + if e := s.run(ctx, id); e != nil { + _ = s.update(id, func(j *Job) error { + if j.Phase != "CANCELED" { + j.Phase = "FAILED" + j.Error = e.Error() + } + return nil + }) + } + }() +} + +func (s *Server) batch(ctx context.Context, id, command string, task map[string]any) (protocol.ObjectRef, error) { + attempt := fmt.Sprintf("%d", time.Now().UnixNano()) + dir := filepath.Join(s.Objects.Root, "br", id, "attempts", attempt) + if e := os.MkdirAll(dir, 0o700); e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + task["protocol_version"] = 1 + task["output_dir"] = dir + task["attempt_id"] = attempt + b, e := json.Marshal(task) + if e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + taskFile := filepath.Join(dir, "task.json") + if e = os.WriteFile(taskFile, b, 0o600); e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + log, e := os.Create(filepath.Join(dir, "worker.log")) + if e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + defer log.Close() + cmd := exec.CommandContext(ctx, s.Binary, "snapshot", command, "--task-spec", taskFile) + cmd.Stdout = log + cmd.Stderr = log + if e = cmd.Run(); e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + name := "candidate.json" + if command == "plan" { + name = "plan.json" + } + return protocol.Ref(filepath.Join(dir, name)) +} + +func (s *Server) run(ctx context.Context, id string) error { + var j Job + if _, e := s.Objects.Read(key(id), &j); e != nil { + return e + } + active := func(j *Job) error { + if j.Phase == "CANCELED" || j.Phase == "FAILED" { + return protocol.Invalid("terminal source job") + } + return nil + } + if j.PlanRef.URI == "" { + if e := s.update(id, func(j *Job) error { + if e := active(j); e != nil { + return e + } + j.Phase = "PLANNING" + return nil + }); e != nil { + return e + } + ref, e := s.batch(ctx, id, "plan", map[string]any{"spec": j.Spec}) + if e != nil { + return e + } + var plan protocol.Plan + if e = protocol.Read(ref, &plan); e != nil { + return e + } + if e = protocol.ValidatePlan(j.Spec, plan); e != nil { + return e + } + if len(plan.Ranges) > 256 { + return protocol.Invalid("demo supports at most 256 ranges") + } + if e = s.update(id, func(j *Job) error { + if e := active(j); e != nil { + return e + } + if j.PlanRef.URI == "" { + j.PlanRef = ref + } + j.Phase = "MATERIALIZING" + return nil + }); e != nil { + return e + } + } + if _, e := s.Objects.Read(key(id), &j); e != nil { + return e + } + var plan protocol.Plan + if e := protocol.Read(j.PlanRef, &plan); e != nil { + return e + } + // A deterministic URI is the completion authority. On recovery, reconcile it + // before launching work, including the export-published/control-not-saved gap. + for _, r := range plan.Ranges { + if e := ctx.Err(); e != nil { + return protocol.Wrap(e) + } + exportKey := "br/" + id + "/range-exports/" + r.RangeID + ".json" + var ex protocol.Export + v, e := s.Objects.Read(exportKey, &ex) + if e != nil { + return e + } + if v == "" { + ref, e := s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 4 << 20}) + if e != nil { + return e + } + if e = protocol.Read(ref, &ex); e != nil { + return e + } + if e = protocol.ValidateExport(j.Spec, j.PlanRef, r, ex); e != nil { + return e + } + for _, chunk := range ex.Chunks { + info, e := os.Stat(chunk.URI) + if e != nil { + return protocol.Wrap(e) + } + if info.Size() != chunk.Size { + return protocol.Invalid("incomplete upload") + } + } + _, e = s.Objects.CAS(exportKey, "", ex) + if e != nil { + return e + } + if _, e = s.Objects.Read(exportKey, &ex); e != nil { + return e + } + } + if e = protocol.ValidateExport(j.Spec, j.PlanRef, r, ex); e != nil { + return e + } + path, _ := s.Objects.Path(exportKey) + ref, e := protocol.Ref(path) + if e != nil { + return e + } + if e = s.update(id, func(j *Job) error { + if e := active(j); e != nil { + return e + } + for _, old := range j.Exports { + if old.URI == ref.URI { + if old != ref { + return protocol.Invalid("export winner changed") + } + return nil + } + } + j.Exports = append(j.Exports, ref) + return nil + }); e != nil { + return e + } + } + return s.update(id, func(j *Job) error { + if e := active(j); e != nil { + return e + } + if len(j.Exports) != len(plan.Ranges) { + return protocol.Invalid("source coverage mismatch") + } + j.Phase = "SOURCE_COMPLETE" + return nil + }) +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method != "POST" { + http.Error(w, "POST required", 405) + return + } + var req Request + if e := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); e != nil { + http.Error(w, "invalid request", 400) + return + } + var out any + var err error + if r.URL.Path == "/ensure" { + out, err = s.Ensure(req.SpecRef) + } else if !validID(req.JobID) { + err = protocol.Invalid("invalid job ID") + } else { + var j Job + var v string + v, err = s.Objects.Read(key(req.JobID), &j) + if err == nil && v == "" { + err = protocol.Invalid("unknown job") + } + if err == nil { + // A Provider can restart between CDC polls without losing an HTTP + // request. Reconcile durable work even when Ensure is not repeated. + if (r.URL.Path == "/status" || r.URL.Path == "/list") && j.Phase != "SOURCE_COMPLETE" && j.Phase != "FAILED" && j.Phase != "CANCELED" { + s.start(req.JobID) + } + switch r.URL.Path { + case "/status": + out = j + case "/list": + var offset int + if req.Cursor != "" { + b, e := base64.RawURLEncoding.DecodeString(req.Cursor) + if e != nil { + err = protocol.Wrap(e) + break + } + parts := strings.Split(string(b), ":") + if len(parts) != 3 || parts[0] != req.JobID || parts[1] != j.PlanRef.Digest { + err = protocol.Invalid("cursor identity mismatch") + break + } + offset, e = strconv.Atoi(parts[2]) + if e != nil { + err = protocol.Wrap(e) + break + } + } + if offset < 0 || offset > len(j.Exports) { + err = protocol.Invalid("cursor outside journal") + break + } + limit := req.Limit + if limit < 1 || limit > 256 { + limit = 64 + } + end := min(offset+limit, len(j.Exports)) + cursor := base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s:%d", req.JobID, j.PlanRef.Digest, end))) + out = Page{j.Exports[offset:end], cursor, j.Phase == "SOURCE_COMPLETE" && end == len(j.Exports)} + case "/cancel": + err = s.update(req.JobID, func(j *Job) error { j.Phase = "CANCELED"; return nil }) + s.mu.Lock() + if cancel := s.running[req.JobID]; cancel != nil { + cancel() + } + s.mu.Unlock() + out = map[string]bool{"canceled": true} + default: + http.NotFound(w, r) + return + } + } + } + if err != nil { + http.Error(w, err.Error(), 400) + return + } + _ = json.NewEncoder(w).Encode(out) +} diff --git a/pkg/snapshot/provider/provider_test.go b/pkg/snapshot/provider/provider_test.go new file mode 100644 index 0000000000..9e1167d93f --- /dev/null +++ b/pkg/snapshot/provider/provider_test.go @@ -0,0 +1,53 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package provider + +import ( + "context" + "net/http/httptest" + "testing" + "time" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestPublishedExportRecoveredAndCursorFinalTail(t *testing.T) { + s := New(t.TempDir(), "must-not-run") + spec := protocol.Spec{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, SelectedSpans: []protocol.Span{{TableID: 1, Start: []byte("a"), End: []byte("z")}}} + plan := protocol.Plan{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, Ranges: []protocol.Span{{RangeID: "r0", TableID: 1, Start: []byte("a"), End: []byte("m")}, {RangeID: "r1", TableID: 1, Start: []byte("m"), End: []byte("z")}}} + ref, e := s.Objects.Put("plan", plan) + require.NoError(t, e) + specRef, e := s.Objects.Put("spec", spec) + require.NoError(t, e) + _, e = s.Objects.Put(key("job"), Job{Spec: spec, SpecRef: specRef, Phase: "MATERIALIZING", PlanRef: ref}) + require.NoError(t, e) + for _, r := range plan.Ranges { + _, e = s.Objects.Put("br/job/range-exports/"+r.RangeID+".json", protocol.Export{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, PlanDigest: ref.Digest, Range: r, AttemptID: "a"}) + require.NoError(t, e) + } + server := httptest.NewServer(s) + defer server.Close() + client := Client{URL: server.URL} + // Simulate Provider restart after export publication but before journal + // update. A status poll must restart reconciliation without another Ensure. + var recovered Job + require.Eventually(t, func() bool { + err := client.Call(context.Background(), "status", Request{JobID: "job"}, &recovered) + return err == nil && recovered.Phase == "SOURCE_COMPLETE" + }, time.Second, 10*time.Millisecond) + var page Page + require.NoError(t, client.Call(context.Background(), "list", Request{JobID: "job", Limit: 1}, &page)) + require.Len(t, page.Exports, 1) + require.False(t, page.Complete) + first := page.Cursor + require.NoError(t, client.Call(context.Background(), "list", Request{JobID: "job", Limit: 1, Cursor: first}, &page)) + require.True(t, page.Complete) + require.Len(t, page.Exports, 1) + var job Job + require.NoError(t, client.Call(context.Background(), "ensure", Request{SpecRef: specRef}, &job)) + require.Equal(t, "SOURCE_COMPLETE", job.Phase) + spec.BackupDigest = "different" + other, e := s.Objects.Put("other-spec", spec) + require.NoError(t, e) + require.Error(t, client.Call(context.Background(), "ensure", Request{SpecRef: other}, &job)) +} diff --git a/pkg/snapshot/store/local.go b/pkg/snapshot/store/local.go new file mode 100644 index 0000000000..1159e88a49 --- /dev/null +++ b/pkg/snapshot/store/local.go @@ -0,0 +1,122 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package store + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "syscall" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +// Local is the single-host demo ObjectCASStore. flock serializes comparisons; +// fsync + rename + directory fsync makes a successful update durable. All +// participants must share this filesystem. This is not an S3 CAS emulation. +type Local struct{ Root string } + +func (s Local) Path(key string) (string, error) { + if key == "" || filepath.IsAbs(key) || strings.Contains(key, "..") { + return "", protocol.Invalid("invalid object key") + } + return filepath.Join(s.Root, key), nil +} + +func (s Local) Read(key string, dst any) (string, error) { + p, e := s.Path(key) + if e != nil { + return "", e + } + b, e := os.ReadFile(p) + if os.IsNotExist(e) { + return "", nil + } + if e != nil { + return "", protocol.Wrap(e) + } + return protocol.Digest(b), protocol.Wrap(json.Unmarshal(b, dst)) +} + +func (s Local) CAS(key, expected string, value any) (bool, error) { + p, e := s.Path(key) + if e != nil { + return false, e + } + if e = os.MkdirAll(filepath.Dir(p), 0o700); e != nil { + return false, protocol.Wrap(e) + } + lock, e := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0o600) + if e != nil { + return false, protocol.Wrap(e) + } + defer lock.Close() + if e = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); e != nil { + return false, protocol.Wrap(e) + } + defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + old, e := os.ReadFile(p) + if e != nil && !os.IsNotExist(e) { + return false, protocol.Wrap(e) + } + version := "" + if e == nil { + version = protocol.Digest(old) + } + if version != expected { + return false, nil + } + b, e := json.Marshal(value) + if e != nil { + return false, protocol.Wrap(e) + } + f, e := os.CreateTemp(filepath.Dir(p), ".cas-") + if e != nil { + return false, protocol.Wrap(e) + } + defer os.Remove(f.Name()) + defer f.Close() + if _, e = f.Write(b); e != nil { + return false, protocol.Wrap(e) + } + if e = f.Sync(); e != nil { + return false, protocol.Wrap(e) + } + if e = f.Close(); e != nil { + return false, protocol.Wrap(e) + } + if e = os.Rename(f.Name(), p); e != nil { + return false, protocol.Wrap(e) + } + dir, e := os.Open(filepath.Dir(p)) + if e != nil { + return false, protocol.Wrap(e) + } + defer dir.Close() + return true, protocol.Wrap(dir.Sync()) +} + +func (s Local) Put(key string, value any) (protocol.ObjectRef, error) { + ok, e := s.CAS(key, "", value) + if e != nil { + return protocol.ObjectRef{}, e + } + p, e := s.Path(key) + if e != nil { + return protocol.ObjectRef{}, e + } + if !ok { + b, e := os.ReadFile(p) + if e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + wanted, e := json.Marshal(value) + if e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + if protocol.Digest(b) != protocol.Digest(wanted) { + return protocol.ObjectRef{}, protocol.Invalid("immutable object conflict") + } + } + return protocol.Ref(p) +} diff --git a/pkg/snapshot/store/store_test.go b/pkg/snapshot/store/store_test.go new file mode 100644 index 0000000000..dfebb6a2ce --- /dev/null +++ b/pkg/snapshot/store/store_test.go @@ -0,0 +1,72 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package store + +import ( + "sync" + "testing" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestCASAndTaskRecovery(t *testing.T) { + s := Local{Root: t.TempDir()} + ok, e := s.CAS("counter", "", 0) + require.NoError(t, e) + require.True(t, ok) + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + var n int + v, e := s.Read("counter", &n) + if e != nil { + t.Error(e) + return + } + ok, e := s.CAS("counter", v, n+1) + if e != nil { + t.Error(e) + return + } + if ok { + return + } + } + }() + } + wg.Wait() + var n int + _, e = s.Read("counter", &n) + require.NoError(t, e) + require.Equal(t, 16, n) + plan := protocol.Plan{Ranges: []protocol.Span{{RangeID: "r0"}, {RangeID: "empty"}}} + tasks := Tasks{Objects: s, Job: "job", Digest: "plan", Epoch: 1, Plan: plan} + require.NoError(t, tasks.Init()) + ref := protocol.ObjectRef{URI: "x", Digest: "d"} + require.NoError(t, tasks.Ready("r0", ref)) + first, e := tasks.Assign("r0") + require.NoError(t, e) + next := tasks + next.Epoch = 2 + require.NoError(t, next.Init()) + require.Error(t, tasks.Commit("r0", first.Lease, 5)) + second, e := next.Assign("r0") + require.NoError(t, e) + require.Greater(t, second.Lease, first.Lease) + require.Error(t, next.Commit("r0", first.Lease, 5)) + require.NoError(t, next.Commit("r0", second.Lease, 5)) + require.NoError(t, next.Ready("r0", ref)) + require.Error(t, next.Ready("r0", protocol.ObjectRef{URI: "other"})) + require.NoError(t, next.Ready("empty", ref)) + empty, e := next.Assign("empty") + require.NoError(t, e) + require.NoError(t, next.Commit("empty", empty.Lease, 0)) + require.NoError(t, next.Init()) + all, e := next.List() + require.NoError(t, e) + require.Equal(t, "APPLIED", all[0].State) + require.Equal(t, "APPLIED", all[1].State) +} diff --git a/pkg/snapshot/store/tasks.go b/pkg/snapshot/store/tasks.go new file mode 100644 index 0000000000..25984ea217 --- /dev/null +++ b/pkg/snapshot/store/tasks.go @@ -0,0 +1,173 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package store + +import ( + "fmt" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +const PageSize = 256 + +type Task struct { + Range protocol.Span `json:"range"` + State string `json:"state"` + Export protocol.ObjectRef `json:"export"` + Lease uint64 `json:"lease"` + Rows uint64 `json:"rows"` + Ack string `json:"ack,omitempty"` +} +type Page struct { + Job string `json:"job"` + PlanDigest string `json:"plan_digest"` + Epoch uint64 `json:"epoch"` + Tasks []Task `json:"tasks"` +} +type Tasks struct { + Objects Local + Job string + Digest string + Epoch uint64 + Plan protocol.Plan +} + +func (t Tasks) key(page int) string { return fmt.Sprintf("cdc/%s/tasks/%06d.json", t.Job, page) } +func (t Tasks) Init() error { + for start := 0; start < len(t.Plan.Ranges); start += PageSize { + page := Page{Job: t.Job, PlanDigest: t.Digest, Epoch: t.Epoch} + end := min(start+PageSize, len(t.Plan.Ranges)) + for _, r := range t.Plan.Ranges[start:end] { + page.Tasks = append(page.Tasks, Task{Range: r, State: "WAIT_SOURCE"}) + } + _, e := t.Objects.CAS(t.key(start/PageSize), "", page) + if e != nil { + return e + } + e = t.edit(start/PageSize, func(p *Page) error { + if p.Epoch > t.Epoch { + return protocol.Invalid("stale task owner") + } + p.Epoch = t.Epoch + for i := range p.Tasks { + if p.Tasks[i].State == "APPLYING" { + p.Tasks[i].State = "READY" + } + } + return nil + }, true) + if e != nil { + return e + } + } + return nil +} + +func (t Tasks) edit(index int, fn func(*Page) error, adopt bool) error { + for retry := 0; retry < 20; retry++ { + var p Page + v, e := t.Objects.Read(t.key(index), &p) + if e != nil { + return e + } + if v == "" || p.Job != t.Job || p.PlanDigest != t.Digest || !adopt && p.Epoch != t.Epoch { + return protocol.Invalid("task page identity/epoch mismatch") + } + if e = fn(&p); e != nil { + return e + } + ok, e := t.Objects.CAS(t.key(index), v, p) + if e != nil { + return e + } + if ok { + return nil + } + } + return protocol.Invalid("task CAS contention") +} + +func (t Tasks) locate(id string) (int, int, error) { + for i, r := range t.Plan.Ranges { + if r.RangeID == id { + return i / PageSize, i % PageSize, nil + } + } + return 0, 0, protocol.Invalid("unknown range %s", id) +} + +func (t Tasks) Ready(id string, ref protocol.ObjectRef) error { + p, i, e := t.locate(id) + if e != nil { + return e + } + return t.edit(p, func(p *Page) error { + x := &p.Tasks[i] + if x.State != "WAIT_SOURCE" { + if x.Export != ref { + return protocol.Invalid("contradictory ready export") + } + return nil + } + x.Export = ref + x.State = "READY" + return nil + }, false) +} + +func (t Tasks) Assign(id string) (Task, error) { + var out Task + p, i, e := t.locate(id) + if e != nil { + return out, e + } + e = t.edit(p, func(p *Page) error { + x := &p.Tasks[i] + if x.State != "READY" { + return protocol.Invalid("range is not ready") + } + x.Lease++ + x.State = "APPLYING" + out = *x + return nil + }, false) + return out, e +} + +func (t Tasks) Commit(id string, lease, rows uint64) error { + p, i, e := t.locate(id) + if e != nil { + return e + } + return t.edit(p, func(p *Page) error { + x := &p.Tasks[i] + if x.Lease != lease { + return protocol.Invalid("stale receipt") + } + if x.State == "APPLIED" && x.Rows == rows { + return nil + } + if x.State != "APPLYING" { + return protocol.Invalid("receipt without assignment") + } + x.State = "APPLIED" + x.Rows = rows + x.Ack = "kafka-broker-ack" + return nil + }, false) +} + +func (t Tasks) List() ([]Task, error) { + var tasks []Task + for i := 0; i < len(t.Plan.Ranges); i += PageSize { + var p Page + v, e := t.Objects.Read(t.key(i/PageSize), &p) + if e != nil { + return nil, e + } + if v == "" || p.Epoch != t.Epoch || p.PlanDigest != t.Digest { + return nil, protocol.Invalid("invalid task page") + } + tasks = append(tasks, p.Tasks...) + } + return tasks, nil +} diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md new file mode 100644 index 0000000000..beafc0c427 --- /dev/null +++ b/tests/integration_tests/native_snapshot/README.md @@ -0,0 +1,163 @@ +# Native CSE snapshot demo + +This demo runs a normal TiCDC changefeed from a frozen CSE packed backup and then +continues consuming TiKV incremental events strictly after the backup TSO `B`. +It uses one TiCDC capture, Kafka open protocol, and a shared local artifact +directory. Snapshot rows are mounted with the schema at `B` and enter the same +capture-owned Kafka sink as incremental rows. + +## Modules + +| Module | Responsibility | +| --- | --- | +| CSE `cse-ctl snapshot` | Plan physical ranges and scan the immutable backup into bounded SnapshotKV chunks; no row decoding or sink | +| `pkg/snapshot/protocol` | Versioned artifacts, exact coverage checks, chunk decoder, stable row identity | +| `pkg/snapshot/provider`, `cmd/snapshot-provider` | Independent BR controller/Runner; launch CSE, publish one immutable RangeExport winner, reconcile publication gaps, serve cursor discovery | +| `pkg/snapshot/store` | Single-host durable file CAS, immutable objects and paged range tasks | +| `pkg/snapshot/bootstrap` | Generation, schema freeze, discovery, assignment, receipt and finalization controller | +| `coordinator/changefeed` | Persist the optional snapshot child **inside the existing ChangeFeedStatus key**, with status/info revision and owner-epoch checks | +| `maintainer/snapshot.go` | Gate normal dispatcher bootstrap until final marker is durable | +| `downstreamadapter/{dispatcherorchestrator,dispatchermanager}/snapshot.go` | Local capture assignment interface, mounting, broker acknowledgements, writer drain/fencing | + +No separate CDC global job key is introduced. Task pages contain only range +state. BR owns its source control state separately. Schema/spec/plan/export/chunk +objects are immutable; attempts never overwrite a winner. The final +`SNAPSHOT_COMMITTED` phase and global marker are one status CAS transaction. +Normal checkpoint, pause and epoch updates preserve the snapshot child. + +## Build + +Use the `codex/snapshot-e2e-demo` worktree in each repository. The CSE worktree +is based on `21e88dd874` (the packed backup reader); the TiCDC worktree is based +on `6a1cb553c`. Build on Linux for the development host: + +```sh +# TiCDC repository; VERSION is a demo build label, not a released artifact. +mkdir -p "$RUN/bin" +go build -tags=nextgen -ldflags '-X github.com/pingcap/ticdc/pkg/version.ReleaseVersion=v9.0.0 -X github.com/pingcap/ticdc/pkg/version.GitHash=6a1cb553c-dirty -X github.com/pingcap/ticdc/pkg/version.GitBranch=codex/snapshot-e2e-demo' -o "$RUN/bin/cdc" ./cmd/cdc +go build -o "$RUN/bin/snapshot-provider" ./cmd/snapshot-provider +go build -o "$RUN/bin/snapshot-verify" ./tests/integration_tests/native_snapshot/verify + +# CSE repository, pinned nightly toolchain from rust-toolchain.toml. +cargo build -p cse-ctl +``` + +## Run on 10.2.15.7 + +The installed run is `/data/nvme0n1/cse-snapshot-demo-20260921`: + +| Component | Address | +| --- | --- | +| Dedicated SQL / keyspace | `127.0.0.1:4400`, `snap_demo_0921` (102), root without password | +| Upstream PD / CSE TiKV | `127.0.0.1:2379`, `10.2.15.7:20160` | +| Native capture API | `http://10.2.15.7:18300` | +| BR Provider | `http://127.0.0.1:18400` | +| CSE lightweight backup worker | `http://127.0.0.1:39000` | +| Kafka | `10.2.15.7:9092` | +| Lab MinIO | `127.0.0.1:19000` | + +The upstream TiKV needs `[cdc] enable=true`. PD 8.5.5 requires the capture's +`enable-legacy-safepoint=true`; API v2 requires a `nextgen` capture build. +Keep TiDB GC retention long enough to cover preparation and incremental catchup. +The helper sets the dedicated SQL keyspace retention to 24 hours; standard CDC +GC protection applies after changefeed creation. Existing SQL port 4000 was +stopped because the old TiDB build's DDL-owner etcd namespace is shared between +keyspaces. Other downstream/Kafka services are unchanged. + +To inspect the existing result (run in the TiCDC checkout on the host): + +```sh +export RUN=/data/nvme0n1/cse-snapshot-demo-20260921 +python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" +python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" +curl -s 'http://127.0.0.1:18300/api/v2/changefeeds/native-snapshot-demo?keyspace=snap_demo_0921' +``` + +To prepare another fixture, use a **new run directory**, copy/build its binaries, +and stop the old demo processes before reusing the same service ports. Removing +old demo changefeeds or choosing a fresh keyspace avoids feeding fixture resets +into prior validation topics. `--reset-fixture` explicitly drops only the +`snapshot_demo` database. It does not rebuild the cluster. + +```sh +python3 tests/integration_tests/native_snapshot/demo.py stop --root "$OLD_RUN" +# A Python environment with boto3 is needed only for prepare; credentials are +# read from the existing CSE config and never put in the manifest or sink URI. +python3 tests/integration_tests/native_snapshot/demo.py prepare --root "$RUN" --reset-fixture +python3 tests/integration_tests/native_snapshot/demo.py start --root "$RUN" --cluster-id unique-demo-cluster +python3 tests/integration_tests/native_snapshot/demo.py create --root "$RUN" --name unique-demo-feed --topic unique-demo-topic +python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" --name unique-demo-feed +python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" --name unique-demo-feed --topic unique-demo-topic +``` + +Preparation writes 3,000 accounts and an empty table, takes a lightweight backup, +packs it, hashes the exact manifest, and records `B`. It then executes one update, +one delete, two inserts and `ADD COLUMN revision DEFAULT 0`. `wait` requires both +the durable snapshot marker and a checkpoint beyond those commits. `verify` +checks all original snapshot values and recomputes the stable record ID, rejects +snapshot output after incremental activation, replays DML/DDL, and compares every +final row and all four columns against SQL. It captures topic end offsets at +startup, so run it only after `wait` and without concurrent fixture writes. + +## Recovery and observed result + +The second changefeed `native-snapshot-recovery` uses topic +`native-snapshot-recovery-20260921`. Its capture was SIGKILLed during APPLYING, +after Kafka had accepted part of a range but before its receipt was durable. +Restart reused generation `faa21988-3856-4376-a900-317b9c5ce7da`, replayed that +range, and then committed the marker and started incremental dispatchers. + +| Scenario | Unique snapshot rows | Replay duplicates | Incremental DML | DDL | Final SQL rows | +| --- | ---: | ---: | ---: | ---: | ---: | +| Initial run | 3,000 | 0 | 4 | 1 | 3,001 | +| Capture killed during APPLYING | 3,000 | 2,816 | 4 | 1 | 3,001 | + +Both runs compare equal for every final row and column. This demonstrates +**at-least-once** snapshot delivery, with stable IDs for downstream deduplication. +An already committed marker prevents snapshot replay on subsequent capture +restarts. Source-controller recovery is also tested at the export-published / +journal-not-updated boundary; status/list polls restart reconciliation. + +## Contract and demo limits + +Snapshot metadata keys in Kafka open protocol are `snapshot_record_id`, +`snapshot_id`, `snapshot_ts`, `snapshot_schema` and `snapshot_schema_encoding`. +Schema encoding is `ticdc-table-info-base64-v1`: base64 of the existing TiCDC +`TableInfo.Marshal()` bytes, decoded with `UnmarshalJSONToTableInfo`. +Normal incremental event keys remain unchanged. + +Record ID is lowercase SHA-256 of `snapshot-key-v1\0`, u32-BE snapshot-ID byte +length, snapshot-ID UTF-8 bytes, u64-BE physical-table-ID, u32-BE inner-key length, +and the raw inner row key. It deliberately excludes attempt, lease and owner. + +SnapshotKV v1: `SNAPKV01`; u32-LE JSON-header length and header; repeated +u32-LE block length / u32-LE row count / framed records; zero block length, +u32-LE JSON-footer length, footer, `SNAPEND1`. Each record has u32-LE key/value +lengths, key, value. JSON byte fields are base64, counts are JSON u64. SHA-256 +covers the entire stored chunk. Footer and exact length/checksum are mandatory. + +This profile uses uncompressed 1 MiB blocks, 4 MiB target chunks (configurable +1–64 MiB in CSE), 16 MiB record ceiling plus the selected chunk budget, 64 KiB +header/footer, 4 MiB metadata and 512 MiB source file-memory quota. Metadata is +bounded before full allocation. Empty ranges publish a zero-row export/receipt. + +This is not a production distributed exporter: one local Runner processes ranges +sequentially; the plan is limited to 256 ranges and 2,048 chunks per range. Local +flock/fsync/rename CAS requires one host and shared paths. Capture fencing uses +the local manager epoch and process writer lock. Multi-capture transport, remote +object CAS, Kubernetes Runner pools, compressed/encrypted chunk output, source +repair/retry policy, lake/relational sinks and scale qualification remain outside +this demo. Source backup decryption uses the existing packed reader support. +Per-row schema envelopes favor a simple verifiable demo over Kafka efficiency. +The test replay utility supports this fixture's integer primary key and DDL; +it is not a general open-protocol consumer. + +## Tests + +```sh +go test -tags=intest ./pkg/snapshot/... ./coordinator/changefeed ./pkg/sink/codec/open +go test -tags=intest ./maintainer ./coordinator ./api/v2 ./downstreamadapter/dispatchermanager ./downstreamadapter/dispatcherorchestrator -run '^$' +# CSE repository +cargo test -p cse-ctl snapshot +cargo test -p native_br packed_reader +``` diff --git a/tests/integration_tests/native_snapshot/compare.py b/tests/integration_tests/native_snapshot/compare.py new file mode 100644 index 0000000000..0576b19107 --- /dev/null +++ b/tests/integration_tests/native_snapshot/compare.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +"""Compare every replayed demo row against SQL, including the post-B column.""" +import argparse +import json +import subprocess + +parser = argparse.ArgumentParser() +parser.add_argument("result") +parser.add_argument("--host", default="127.0.0.1") +parser.add_argument("--port", default="4400") +parser.add_argument("--user", default="root") +args = parser.parse_args() +result = json.load(open(args.result)) +sql = "SELECT JSON_OBJECT('id',id,'balance',balance,'note',note,'revision',revision) FROM snapshot_demo.accounts ORDER BY id" +data = subprocess.check_output(["mysql", "--batch", "--raw", "--skip-column-names", "-h"+args.host, "-P"+args.port, "-u"+args.user, "-e", sql], text=True) +expected = {str(row["id"]): row for row in map(json.loads, data.splitlines())} +assert result["final_rows"] == expected, "Kafka replay differs from SQL rows" +assert result["incremental_rows"] >= 4 and result["ddl_events"] >= 1 +print(json.dumps({"sql_rows": len(expected), "all_columns_equal": True, **{k: v for k, v in result.items() if k != "final_rows"}}, indent=2)) diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py new file mode 100644 index 0000000000..44bbea9956 --- /dev/null +++ b/tests/integration_tests/native_snapshot/demo.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Native snapshot demo operations. Run on the Linux host sharing the artifact FS.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import time +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["prepare", "start", "stop", "create", "wait", "verify"]) + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--keyspace", default="snap_demo_0921") + parser.add_argument("--pd", default="http://127.0.0.1:2379") + parser.add_argument("--sql-port", default="4400") + parser.add_argument("--broker", default="10.2.15.7:9092") + parser.add_argument("--server", default="http://127.0.0.1:18300") + parser.add_argument("--provider", default="http://127.0.0.1:18400") + parser.add_argument("--worker", default="http://127.0.0.1:39000") + parser.add_argument("--name", default="native-snapshot-demo") + parser.add_argument("--topic", default="native-snapshot-demo-20260921") + parser.add_argument("--cse-binary", default="/data/nvme0n1/cdc-snapshotkv-runner-20260909/target/debug/cse-ctl") + parser.add_argument("--cse-config", default="/data/nvme0n1/cdc-snapshotkv-runner-20260909/cse-pack-backup.toml") + parser.add_argument("--cluster-id", default="snapshot-demo-20260921") + parser.add_argument("--advertise-addr", default="10.2.15.7:18300") + parser.add_argument("--reset-fixture", action="store_true", help="drop only snapshot_demo before seeding") + args = parser.parse_args() + root = args.root.resolve() + root.mkdir(parents=True, exist_ok=True) + (root / "logs").mkdir(exist_ok=True) + + def sql(query): + return subprocess.check_output(["mysql", "--batch", "--raw", "--skip-column-names", "-h127.0.0.1", "-P"+args.sql_port, "-uroot", "-e", query], text=True) + + def http(url, data=None): + request = urllib.request.Request(url, data=None if data is None else json.dumps(data).encode(), headers={"Content-Type": "application/json"}) + return json.load(urllib.request.urlopen(request, timeout=120)) + + def write(name, value): + (root / name).write_text(json.dumps(value, indent=2)) + + def cse_config(): + text = Path(args.cse_config).read_text() + # The lab uses simple top-level string values. Secrets stay in memory. + def get(name): + return re.search(r"^"+name+r'\s*=\s*"([^"]*)"', text, re.M).group(1) + return get + + if args.action == "prepare": + if (root / "manifest.json").exists(): + raise SystemExit("use a fresh run directory; existing manifest is immutable") + if len(args.keyspace) > 20: + raise SystemExit("TiCDC keyspace names must be at most 20 characters") + if args.reset_fixture: + sql("DROP DATABASE IF EXISTS snapshot_demo") + sql('CREATE DATABASE snapshot_demo; CREATE TABLE snapshot_demo.accounts(id BIGINT PRIMARY KEY,balance BIGINT NOT NULL,note VARCHAR(100)); CREATE TABLE snapshot_demo.empty_table(id INT PRIMARY KEY); SET GLOBAL tidb_gc_life_time="24h";') + for start in range(1, 3001, 500): + values = ",".join("(%d,%d,'snapshot-%d')" % (i, i*10, i) for i in range(start, start+500)) + sql("INSERT INTO snapshot_demo.accounts VALUES " + values) + backup = http(args.worker+"/api/v1/x/cluster/lightweight_backup", {}) + write("backup.json", backup) + with (root / "logs/pack.log").open("w") as log: + subprocess.run([args.cse_binary, "pack-backup", "--config", args.cse_config, "--backup-name", backup["backup_name"], "--keyspace-name", args.keyspace, "--data-dir", str(root/"pack-work")], stdout=log, stderr=subprocess.STDOUT, check=True) + info = subprocess.check_output([args.cse_binary, "show", "backup", "--config", args.cse_config, "--name", backup["backup_name"]], stderr=subprocess.STDOUT, text=True) + (root / "logs/backup-info.log").write_text(info) + ts = int(re.search(r"backup_ts:\s*(\d+)", info).group(1)) + path = re.search(r"Copyable path: (\S+)", (root/"logs/pack.log").read_text()).group(1) + bucket, key = path.split("/", 1) + import boto3 # Only the backup preparation helper needs this dependency. + config = cse_config() + client = boto3.client("s3", endpoint_url=config("s3-endpoint"), aws_access_key_id=config("s3-key-id"), aws_secret_access_key=config("s3-secret-key")) + data = client.get_object(Bucket=bucket, Key=key)["Body"].read() + keyspace = http(args.pd+"/pd/api/v2/keyspaces/"+args.keyspace) + manifest = {"snapshot_ts": ts, "keyspace_id": keyspace["id"], "backup_uri": "s3://"+path+"?endpoint="+config("s3-endpoint")+"®ion=local", "backup_digest": hashlib.sha256(data).hexdigest()} + write("manifest.json", manifest) + sql("USE snapshot_demo; UPDATE accounts SET balance=99999,note='updated-after-B' WHERE id=1; DELETE FROM accounts WHERE id=2; INSERT INTO accounts VALUES(3001,30010,'inserted-after-B'); ALTER TABLE accounts ADD COLUMN revision INT DEFAULT 0; INSERT INTO accounts VALUES(3002,30020,'after-DDL',1);") + # An SQL snapshot TSO taken after all fixture commits bounds the wait. + target = int(sql("BEGIN; SELECT @@tidb_current_ts; COMMIT;").strip()) + write("target.json", {"checkpoint_ts": target}) + config_text = '[filter]\nrules=["snapshot_demo.*"]\n[snapshot]\n' + for k, v in {"backup-uri": manifest["backup_uri"], "backup-digest": manifest["backup_digest"], "provider-url": args.provider, "artifact-dir": str(root/"artifacts")}.items(): + config_text += k+"="+json.dumps(v)+"\n" + (root / "changefeed.toml").write_text(config_text) + print(json.dumps({"snapshot_ts": ts, "keyspace_id": keyspace["id"], "target_ts": target})) + elif args.action == "start": + (root / "cdc.toml").write_text("newarch = true\nenable-legacy-safepoint = true\n") + env = os.environ.copy() + config = cse_config() + env.update(DFS_S3_KEY_ID=config("s3-key-id"), DFS_S3_SECRET_KEY=config("s3-secret-key")) + from urllib.parse import urlsplit + commands = { + "provider": [str(root/"bin/snapshot-provider"), "-root", str(root/"artifacts"), "-cse-binary", args.cse_binary, "-listen", urlsplit(args.provider).netloc], + "cdc": [str(root/"bin/cdc"), "server", "--pd="+args.pd, "--addr=0.0.0.0:"+str(urlsplit(args.server).port), "--advertise-addr="+args.advertise_addr, "--cluster-id="+args.cluster_id, "--data-dir="+str(root/"cdc-data"), "--log-file="+str(root/"logs/cdc.log"), "--config="+str(root/"cdc.toml")], + } + for name, command in commands.items(): + pidfile = root/(name+".pid") + if pidfile.exists() and Path("/proc/"+pidfile.read_text()+"/cmdline").exists(): + raise SystemExit(name+" PID still exists; stop before starting") + with (root/("logs/"+name+"-stdout.log")).open("a") as log: + proc = subprocess.Popen(command, env=env if name=="provider" else None, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + pidfile.write_text(str(proc.pid)) + print(name, proc.pid) + for _ in range(300): + try: + if http(args.server+"/api/v2/status").get("is_owner"): + print("capture API and coordinator ready") + break + except (OSError, ValueError): + pass + time.sleep(.2) + else: + raise SystemExit("capture did not become ready; inspect logs/cdc.log") + elif args.action == "stop": + for name, binary in [("cdc", "cdc"), ("provider", "snapshot-provider")]: + pidfile = root/(name+".pid") + if not pidfile.exists(): + continue + pid = int(pidfile.read_text()) + proc = Path("/proc/%d/cmdline" % pid) + if proc.exists(): + if proc.read_bytes().split(b"\0")[0] != str(root/"bin"/binary).encode(): + raise SystemExit("refusing to stop a reused PID") + os.kill(pid, signal.SIGTERM) + for _ in range(300): + if not proc.exists(): + break + time.sleep(.1) + else: + raise SystemExit(name+" has not drained") + pidfile.unlink() + elif args.action == "create": + manifest = json.loads((root/"manifest.json").read_text()) + subprocess.run([str(root/"bin/cdc"), "cli", "changefeed", "create", "--server="+args.server, "--keyspace="+args.keyspace, "--changefeed-id="+args.name, "--sink-uri=kafka://"+args.broker+"/"+args.topic+"?protocol=open-protocol&partition-num=1&replication-factor=1&required-acks=-1", "--start-ts="+str(manifest["snapshot_ts"]), "--config="+str(root/"changefeed.toml"), "--no-confirm"], check=True) + elif args.action == "wait": + target = json.loads((root/"target.json").read_text())["checkpoint_ts"] + for _ in range(300): + state = http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace) + if state.get("bootstrap_complete") and state.get("checkpoint_ts", 0) >= target: + write(args.name+"-status.json", state) + print("snapshot committed and incremental checkpoint reached", target) + break + time.sleep(1) + else: + raise SystemExit("changefeed did not catch up: "+str(state.get("error"))) + elif args.action == "verify": + output = root/(args.name+"-verification.json") + subprocess.run([str(root/"bin/snapshot-verify"), "-broker", args.broker, "-topic", args.topic, "-output", str(output)], check=True) + subprocess.run(["python3", str(Path(__file__).with_name("compare.py")), str(output), "--port", args.sql_port], check=True) + + +if __name__ == "__main__": + main() diff --git a/tests/integration_tests/native_snapshot/verify/main.go b/tests/integration_tests/native_snapshot/verify/main.go new file mode 100644 index 0000000000..670953671a --- /dev/null +++ b/tests/integration_tests/native_snapshot/verify/main.go @@ -0,0 +1,225 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +// This verifier consumes a bounded, single-partition demo topic from offset zero. +package main + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "strings" + "time" + + "github.com/IBM/sarama" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/tidb/pkg/kv" + "github.com/pingcap/tidb/pkg/tablecodec" +) + +type key struct { + TS uint64 `json:"ts"` + Type int `json:"t"` + Table string `json:"tbl"` + ID string `json:"snapshot_record_id"` + Snapshot string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + Schema string `json:"snapshot_schema"` +} +type column struct { + Value any `json:"v"` +} +type value struct { + Upsert map[string]column `json:"u"` + Delete map[string]column `json:"d"` + Query string `json:"q"` +} + +func frame(b []byte) ([]byte, []byte) { + if len(b) < 8 { + log.Fatal("truncated frame") + } + n := binary.BigEndian.Uint64(b) + if n > uint64(len(b)-8) { + log.Fatal("invalid frame length") + } + return b[8 : 8+n], b[8+n:] +} + +func number(v any) int64 { + n, err := v.(json.Number).Int64() + if err != nil { + log.Fatal(err) + } + return n +} + +func decode(b []byte, out any) { + d := json.NewDecoder(bytes.NewReader(b)) + d.UseNumber() + if err := d.Decode(out); err != nil { + log.Fatal(err) + } +} + +func main() { + broker := flag.String("broker", "127.0.0.1:9092", "Kafka broker") + topic := flag.String("topic", "", "single partition topic") + out := flag.String("output", "verify.json", "result JSON") + seed := flag.Int("seed", 3000, "expected unique snapshot rows") + flag.Parse() + config := sarama.NewConfig() + config.Version = sarama.V2_4_0_0 + config.Consumer.Return.Errors = true + client, err := sarama.NewClient([]string{*broker}, config) + if err != nil { + log.Fatal(err) + } + defer client.Close() + partitions, err := client.Partitions(*topic) + if err != nil || len(partitions) != 1 { + log.Fatalf("expected one partition: %v %v", partitions, err) + } + end, err := client.GetOffset(*topic, 0, sarama.OffsetNewest) + if err != nil { + log.Fatal(err) + } + if end == 0 { + log.Fatal("empty topic") + } + consumer, err := sarama.NewConsumerFromClient(client) + if err != nil { + log.Fatal(err) + } + defer consumer.Close() + pc, err := consumer.ConsumePartition(*topic, 0, sarama.OffsetOldest) + if err != nil { + log.Fatal(err) + } + defer pc.Close() + rows := map[int64]map[string]any{} + seen := map[string]int64{} + snapshotRows := 0 + duplicates := 0 + incremental := 0 + ddls := 0 + var boundary uint64 + lastOffset := int64(-1) + for lastOffset < end-1 { + select { + case err := <-pc.Errors(): + log.Fatal(err) + case <-time.After(60 * time.Second): + log.Fatal("consumer timeout") + case msg := <-pc.Messages(): + lastOffset = msg.Offset + if len(msg.Key) < 8 || binary.BigEndian.Uint64(msg.Key) != 1 { + log.Fatal("unexpected open protocol version") + } + keys, values := msg.Key[8:], msg.Value + for len(keys) > 0 { + var kb, vb []byte + kb, keys = frame(keys) + vb, values = frame(values) + var k key + decode(kb, &k) + if k.Type == 3 { + continue + } + var v value + decode(vb, &v) + if k.Type == 2 { + ddls++ + // The fixture adds one column with a constant default. Apply + // its schema effect to already materialized snapshot rows. + if strings.Contains(strings.ToLower(v.Query), "revision") { + for _, row := range rows { + row["revision"] = json.Number("0") + } + } + if boundary != 0 && k.TS <= boundary { + log.Fatal("DDL at/below B") + } + continue + } + if k.Table != "accounts" { + log.Fatalf("unexpected row table %s", k.Table) + } + cols := v.Upsert + if cols == nil { + cols = v.Delete + } + id := number(cols["id"].Value) + if k.ID != "" { + if incremental > 0 || ddls > 0 { + log.Fatal("snapshot output after incremental activation") + } + if k.TS != k.SnapshotTS || k.SnapshotTS == 0 || boundary != 0 && boundary != k.TS { + log.Fatal("snapshot boundary changed") + } + boundary = k.TS + schema, err := base64.StdEncoding.DecodeString(k.Schema) + if err != nil { + log.Fatal(err) + } + ti, err := common.UnmarshalJSONToTableInfo(schema) + if err != nil { + log.Fatal(err) + } + rawKey := tablecodec.EncodeRowKeyWithHandle(ti.TableName.TableID, kv.IntHandle(id)) + if protocol.RecordID(k.Snapshot, ti.TableName.TableID, rawKey) != k.ID { + log.Fatal("record ID differs from domain hash") + } + if id < 1 || id > int64(*seed) || number(cols["balance"].Value) != id*10 || cols["note"].Value != fmt.Sprintf("snapshot-%d", id) || len(cols) != 3 { + log.Fatal("snapshot differs from frozen SQL fixture") + } + if old, ok := seen[k.ID]; ok { + if old != id { + log.Fatal("record ID collision") + } + duplicates++ + continue + } + seen[k.ID] = id + snapshotRows++ + } else { + if boundary == 0 || k.TS <= boundary { + log.Fatal("incremental before/at B") + } + incremental++ + } + if v.Delete != nil { + delete(rows, id) + continue + } + row := map[string]any{} + for name, c := range v.Upsert { + row[name] = c.Value + } + rows[id] = row + } + if len(values) != 0 { + log.Fatal("extra values") + } + } + } + if snapshotRows != *seed { + log.Fatalf("snapshot rows %d != %d", snapshotRows, *seed) + } + result := map[string]any{"snapshot_unique_rows": snapshotRows, "snapshot_duplicates": duplicates, "incremental_rows": incremental, "ddl_events": ddls, "snapshot_ts": boundary, "kafka_end_offset": end, "final_rows": rows} + f, err := os.Create(*out) + if err != nil { + log.Fatal(err) + } + defer f.Close() + enc := json.NewEncoder(f) + enc.SetIndent("", " ") + if err = enc.Encode(result); err != nil { + log.Fatal(err) + } + fmt.Printf("snapshot=%d duplicates=%d incremental=%d ddl=%d final=%d end_offset=%d\n", snapshotRows, duplicates, incremental, ddls, len(rows), end) +} From a7b274b9b85ed800ef885c4e61c690ffa82fa295 Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 21 Sep 2026 13:57:35 +0800 Subject: [PATCH 02/17] tests: validate live snapshot bootstrap with latest CSE reader Signed-off-by: dongmen <414110582@qq.com> --- .../native_snapshot/README.md | 45 +++++- .../integration_tests/native_snapshot/demo.py | 17 +- .../integration_tests/native_snapshot/live.py | 145 ++++++++++++++++++ 3 files changed, 203 insertions(+), 4 deletions(-) create mode 100644 tests/integration_tests/native_snapshot/live.py diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index beafc0c427..30fb28f98f 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -28,18 +28,21 @@ Normal checkpoint, pause and epoch updates preserve the snapshot child. ## Build Use the `codex/snapshot-e2e-demo` worktree in each repository. The CSE worktree -is based on `21e88dd874` (the packed backup reader); the TiCDC worktree is based -on `6a1cb553c`. Build on Linux for the development host: +is based on packed-reader PR #5709 at `ce471b0d203d3e5d3800355e1324a7ed12aa25de`; +the TiCDC worktree is based on `6a1cb553c`. CSE planning uses the current +`sample_range` coverage validation and materialization consumes its lazy +`scan_range` batch stream, retaining the reader's resource ownership. Build on Linux for the development host: ```sh # TiCDC repository; VERSION is a demo build label, not a released artifact. mkdir -p "$RUN/bin" -go build -tags=nextgen -ldflags '-X github.com/pingcap/ticdc/pkg/version.ReleaseVersion=v9.0.0 -X github.com/pingcap/ticdc/pkg/version.GitHash=6a1cb553c-dirty -X github.com/pingcap/ticdc/pkg/version.GitBranch=codex/snapshot-e2e-demo' -o "$RUN/bin/cdc" ./cmd/cdc +go build -tags=nextgen -ldflags "-X github.com/pingcap/ticdc/pkg/version.ReleaseVersion=v9.0.0 -X github.com/pingcap/ticdc/pkg/version.GitHash=$(git rev-parse HEAD) -X github.com/pingcap/ticdc/pkg/version.GitBranch=codex/snapshot-e2e-demo" -o "$RUN/bin/cdc" ./cmd/cdc go build -o "$RUN/bin/snapshot-provider" ./cmd/snapshot-provider go build -o "$RUN/bin/snapshot-verify" ./tests/integration_tests/native_snapshot/verify # CSE repository, pinned nightly toolchain from rust-toolchain.toml. cargo build -p cse-ctl +cp "${CARGO_TARGET_DIR:-target}/debug/cse-ctl" "$RUN/bin/cse-ctl" ``` ## Run on 10.2.15.7 @@ -99,6 +102,42 @@ snapshot output after incremental activation, replays DML/DDL, and compares ever final row and all four columns against SQL. It captures topic end offsets at startup, so run it only after `wait` and without concurrent fixture writes. +## Continuous incremental validation + +After `demo.py wait`, run the live workload against a fresh fixture: + +```sh +python3 tests/integration_tests/native_snapshot/live.py \ + --root "$RUN" --name unique-demo-feed --topic unique-demo-topic --duration 60 +``` + +The workload repeatedly commits an update, an insert and a delete in one SQL +optimistic transaction (the older lab CSE does not support TiDB's pessimistic +lock-conflict option). While writes are active, it samples Kafka end offsets and replays +the topic, requiring multiple advancing values of the live marker. After writes +stop, it waits for the final checkpoint and compares every row and column with +SQL, including the exact expected incremental event count. Reports and the write +journal stay under `$RUN`. The observed row age includes polling and replay +cost; it is a freshness observation, not a per-event latency benchmark. + +The latest-reader run uses `/data/nvme0n1/cse-snapshot-latest5709-20260921` and +installs its own `bin/cse-ctl`. Pass `--cse-binary "$RUN/bin/cse-ctl"` to +`demo.py prepare` and `start` so a later build cannot replace its exporter. + +The latest-reader validation seeded 3,000 rows plus an empty table at +`B=469229866966581249`. Initial catchup applied four DML events and one DDL, +matching all 3,001 SQL rows. The 60-second live phase committed 526 optimistic +transactions and 1,577 additional DML events; nine samples observed Kafka values +advancing while SQL writes were active. Final replay contained exactly 1,581 +incremental row events and matched all 3,002 SQL rows and columns. + +Killing the capture during `APPLYING` preserved generation +`6d38fc3d-ce47-4b81-ade1-2376cf9966c0`. Restart replayed 128 snapshot rows with +stable IDs; deduplication recovered the same 3,000 snapshot rows, all 1,581 +incremental events, and the matching 3,002 final rows. The already committed +feed retained zero snapshot duplicates after that restart. The wait helper +retries transient API failures while keyspace controllers initialize. + ## Recovery and observed result The second changefeed `native-snapshot-recovery` uses topic diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py index 44bbea9956..4ba17a9429 100644 --- a/tests/integration_tests/native_snapshot/demo.py +++ b/tests/integration_tests/native_snapshot/demo.py @@ -9,6 +9,7 @@ import signal import subprocess import time +import urllib.error import urllib.request @@ -139,8 +140,22 @@ def get(name): subprocess.run([str(root/"bin/cdc"), "cli", "changefeed", "create", "--server="+args.server, "--keyspace="+args.keyspace, "--changefeed-id="+args.name, "--sink-uri=kafka://"+args.broker+"/"+args.topic+"?protocol=open-protocol&partition-num=1&replication-factor=1&required-acks=-1", "--start-ts="+str(manifest["snapshot_ts"]), "--config="+str(root/"changefeed.toml"), "--no-confirm"], check=True) elif args.action == "wait": target = json.loads((root/"target.json").read_text())["checkpoint_ts"] + state = {} for _ in range(300): - state = http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace) + try: + state = http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace) + except urllib.error.HTTPError as error: + # The capture can own its election before keyspace controllers + # are ready after restart. Retry transient server responses. + if error.code not in (500, 502, 503, 504): + raise + state = {"error": error.read(4096).decode(errors="replace")} + time.sleep(1) + continue + except (urllib.error.URLError, TimeoutError) as error: + state = {"error": str(error)} + time.sleep(1) + continue if state.get("bootstrap_complete") and state.get("checkpoint_ts", 0) >= target: write(args.name+"-status.json", state) print("snapshot committed and incremental checkpoint reached", target) diff --git a/tests/integration_tests/native_snapshot/live.py b/tests/integration_tests/native_snapshot/live.py new file mode 100644 index 0000000000..35d478aa77 --- /dev/null +++ b/tests/integration_tests/native_snapshot/live.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Exercise live incremental delivery after demo.py wait, then compare all rows.""" +import argparse +import json +from pathlib import Path +import subprocess +import threading +import time +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--name", required=True) + parser.add_argument("--topic", required=True) + parser.add_argument("--keyspace", default="snap_demo_0921") + parser.add_argument("--server", default="http://127.0.0.1:18300") + parser.add_argument("--broker", default="10.2.15.7:9092") + parser.add_argument("--sql-port", default="4400") + parser.add_argument("--duration", type=float, default=60) + parser.add_argument("--interval", type=float, default=0.1) + args = parser.parse_args() + if args.duration < 15 or args.interval <= 0: + parser.error("duration must be at least 15 seconds and interval positive") + root = args.root.resolve() + journal = root / (args.name + "-live-writes.jsonl") + if journal.exists(): + raise SystemExit("use a fresh live run name; write journal already exists") + stop = threading.Event() + failures = [] + commits = {} + samples = [] + + def sql(query): + return subprocess.check_output([ + "mysql", "--batch", "--raw", "--skip-column-names", "-h127.0.0.1", + "-P" + args.sql_port, "-uroot", "-e", query, + ], text=True, timeout=30) + + def state(): + url = args.server + "/api/v2/changefeeds/" + args.name + "?keyspace=" + args.keyspace + with urllib.request.urlopen(url, timeout=10) as response: + return json.load(response) + + if not state().get("bootstrap_complete"): + raise SystemExit("run demo.py wait before the live workload") + if int(sql("SELECT COUNT(*) FROM snapshot_demo.accounts WHERE id>=10000")): + raise SystemExit("live workload ID range is already occupied") + + def writer(): + deadline = time.monotonic() + args.duration + try: + with journal.open("x") as log: + seq = 0 + while time.monotonic() < deadline and not stop.is_set(): + seq += 1 + # The CSE lab supports optimistic transactions; its older + # server rejects TiDB's pessimistic lock conflict option. + # One transaction changes an existing row, inserts a row, + # and removes the previous live row. Write the journal entry + # before starting the next transaction. + sql("USE snapshot_demo; BEGIN OPTIMISTIC; " + f"UPDATE accounts SET balance=balance+1,note='live-{seq}',revision={seq} WHERE id=1; " + f"INSERT INTO accounts VALUES({10000+seq},{seq},'live-insert-{seq}',{seq}); " + f"DELETE FROM accounts WHERE id={10000+seq-1}; COMMIT;") + committed = time.time() + commits[seq] = committed + log.write(json.dumps({"seq": seq, "committed_at": committed}) + "\n") + log.flush() + stop.wait(args.interval) + except Exception as error: + failures.append(str(error)) + stop.set() + + started = time.time() + thread = threading.Thread(target=writer) + thread.start() + try: + while thread.is_alive(): + # Capture Kafka's current end offset while SQL writes continue. + # This samples actual delivered values, not just CDC checkpoints. + time.sleep(5) + if not thread.is_alive(): + break + output = root / (args.name + f"-live-sample-{len(samples):02}.json") + subprocess.run([ + str(root / "bin/snapshot-verify"), "-broker", args.broker, + "-topic", args.topic, "-output", str(output), + ], check=True, timeout=90, stdout=subprocess.DEVNULL) + result = json.loads(output.read_text()) + note = result["final_rows"]["1"]["note"] + seq = int(note.removeprefix("live-")) if note.startswith("live-") else 0 + observed = time.time() + status = state() + sample = { + "observed_at": observed, "writer_active": thread.is_alive(), + "committed_seq": max(commits, default=0), "kafka_seq": seq, + "kafka_end_offset": result["kafka_end_offset"], + "incremental_rows": result["incremental_rows"], + "checkpoint_ts": status.get("checkpoint_ts"), + "state": status.get("state"), + } + if seq in commits: + # This includes polling/verification time; it is a freshness + # observation, not a per-event latency measurement. + sample["observed_row_age_seconds"] = observed - commits[seq] + samples.append(sample) + print(json.dumps(sample), flush=True) + finally: + stop.set() + thread.join(timeout=35) + if thread.is_alive(): + raise RuntimeError("writer failed to stop") + if failures: + raise RuntimeError("SQL workload failed: " + failures[0]) + final_seq = max(commits, default=0) + target = int(sql("BEGIN; SELECT @@tidb_current_ts; COMMIT;").strip()) + (root / "target.json").write_text(json.dumps({"checkpoint_ts": target})) + helper = Path(__file__).with_name("demo.py") + common = ["--root", str(root), "--name", args.name, "--topic", args.topic, + "--keyspace", args.keyspace, "--server", args.server, + "--broker", args.broker, "--sql-port", args.sql_port] + subprocess.run(["python3", str(helper), "wait", *common], check=True, timeout=330) + subprocess.run(["python3", str(helper), "verify", *common], check=True, timeout=120) + final = json.loads((root / (args.name + "-verification.json")).read_text()) + assert final["final_rows"]["1"]["note"] == f"live-{final_seq}" + # All transactions have update+insert; all except the first delete a row. + assert final["incremental_rows"] == 4 + 3 * final_seq - 1 + live_sequences = {s["kafka_seq"] for s in samples if s["writer_active"] and s["kafka_seq"] > 0} + assert len(live_sequences) >= 2, "Kafka did not demonstrate progress while SQL was writing" + summary = { + "started_at": started, "finished_at": time.time(), + "requested_write_duration_seconds": args.duration, + "transactions": final_seq, "live_dml_events": 3 * final_seq - 1, + "live_progress_samples": len(live_sequences), "samples": samples, + "target_ts": target, "all_columns_equal": True, + "final_sql_rows": len(final["final_rows"]), + } + (root / (args.name + "-live-summary.json")).write_text(json.dumps(summary, indent=2)) + print(json.dumps({k: v for k, v in summary.items() if k != "samples"}, indent=2)) + + +if __name__ == "__main__": + main() From 6ff1398e4f372936fd4169f3ff3d2442d06b182c Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 11:20:37 +0800 Subject: [PATCH 03/17] snapshot: verify and decode chunks from one bounded read Signed-off-by: dongmen <414110582@qq.com> --- pkg/snapshot/protocol/chunk.go | 29 +++++++++++++++----------- pkg/snapshot/protocol/protocol_test.go | 23 ++++++++++++++++---- 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/pkg/snapshot/protocol/chunk.go b/pkg/snapshot/protocol/chunk.go index 4fe7e7290d..5334b76753 100644 --- a/pkg/snapshot/protocol/chunk.go +++ b/pkg/snapshot/protocol/chunk.go @@ -10,32 +10,37 @@ import ( ) // DecodeChunk first verifies the entire immutable object before emitting rows. -// The local artifact backend doubles as a bounded spool (64 MiB per object). +// Keep the verified bytes in a bounded buffer (64 MiB per object), so decoding +// needs no second file read and cannot observe different bytes after validation. func DecodeChunk(ref Chunk, expected Header, span Span, emit func([]byte, []byte) error) (Footer, error) { var zero Footer if ref.Size < 0 || ref.Size > 64<<20 { return zero, Invalid("chunk exceeds demo size limit") } - info, err := os.Stat(ref.URI) + f, err := os.Open(ref.URI) + if err != nil { + return zero, Wrap(err) + } + defer f.Close() + info, err := f.Stat() if err != nil { return zero, Wrap(err) } if info.Size() != ref.Size { return zero, Invalid("chunk size mismatch") } - actual, err := Ref(ref.URI) - if err != nil { - return zero, err + b := make([]byte, int(ref.Size)) + if _, err := io.ReadFull(f, b); err != nil { + return zero, Wrap(err) } - if actual != ref.ObjectRef { - return zero, Invalid("chunk checksum/size mismatch") + var tail [1]byte + if n, err := f.Read(tail[:]); n != 0 || err != io.EOF { + return zero, Invalid("chunk size changed while reading") } - f, err := os.Open(ref.URI) - if err != nil { - return zero, Wrap(err) + if Digest(b) != ref.Digest { + return zero, Invalid("chunk checksum/size mismatch") } - defer f.Close() - return decode(f, expected, span, ref, emit) + return decode(bytes.NewReader(b), expected, span, ref, emit) } func readN(r io.Reader, n uint32, max uint32) ([]byte, error) { diff --git a/pkg/snapshot/protocol/protocol_test.go b/pkg/snapshot/protocol/protocol_test.go index afa1b5f4b1..234c6586ec 100644 --- a/pkg/snapshot/protocol/protocol_test.go +++ b/pkg/snapshot/protocol/protocol_test.go @@ -51,13 +51,28 @@ func TestRustGoldenAndCorruption(t *testing.T) { require.NoError(t, os.WriteFile(f, b, 0o600)) ref.ObjectRef, err = Ref(f) require.NoError(t, err) + got = nil + _, err = DecodeChunk(ref, expected, span, func(k, v []byte) error { + got = append(got, string(k)) + return nil + }) + require.NoError(t, err) + require.Equal(t, []string{"a", "b"}, got) bad = append([]byte(nil), b...) bad[len(bad)/2] ^= 1 - require.NoError(t, os.WriteFile(f, bad, 0o600)) - called := false - _, err = DecodeChunk(ref, expected, span, func([]byte, []byte) error { called = true; return nil }) + for _, data := range [][]byte{bad, b[:len(b)-1], append(append([]byte(nil), b...), 0)} { + require.NoError(t, os.WriteFile(f, data, 0o600)) + called := false + _, err = DecodeChunk(ref, expected, span, func([]byte, []byte) error { called = true; return nil }) + require.Error(t, err) + require.False(t, called) + } + ref.Size = (64 << 20) + 1 + _, err = DecodeChunk(ref, expected, span, func([]byte, []byte) error { + t.Fatal("oversized chunk must not emit rows") + return nil + }) require.Error(t, err) - require.False(t, called) } func TestStateRoundTrip(t *testing.T) { From 92647d4f7ffef93f6127de04cdeb76eb01943077 Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 11:59:33 +0800 Subject: [PATCH 04/17] snapshot: support bounded parallel local export workers Signed-off-by: dongmen <414110582@qq.com> --- cmd/snapshot-provider/main.go | 8 +- pkg/snapshot/provider/provider.go | 182 +++++++++++------- pkg/snapshot/provider/provider_test.go | 96 +++++++++ .../native_snapshot/README.md | 16 +- .../integration_tests/native_snapshot/demo.py | 3 +- 5 files changed, 235 insertions(+), 70 deletions(-) diff --git a/cmd/snapshot-provider/main.go b/cmd/snapshot-provider/main.go index 889aad7152..d67c81d2e0 100644 --- a/cmd/snapshot-provider/main.go +++ b/cmd/snapshot-provider/main.go @@ -17,7 +17,11 @@ func main() { root := flag.String("root", "", "shared artifact directory") binary := flag.String("cse-binary", "", "CSE batch binary") addr := flag.String("listen", "127.0.0.1:18400", "listen address") + workers := flag.Int("workers", 1, "maximum concurrent local range workers per job (1-32)") flag.Parse() + if *workers < 1 || *workers > 32 { + log.Fatal("workers must be between 1 and 32") + } if *root == "" || *binary == "" { log.Fatal("root and cse-binary required") } @@ -32,6 +36,8 @@ func main() { if e = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); e != nil { log.Fatal("another controller owns this demo store") } - s := http.Server{Addr: *addr, Handler: provider.New(*root, *binary), ReadHeaderTimeout: 5 * time.Second} + controller := provider.New(*root, *binary) + controller.Workers = *workers + s := http.Server{Addr: *addr, Handler: controller, ReadHeaderTimeout: 5 * time.Second} log.Fatal(s.ListenAndServe()) } diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/provider/provider.go index fa129ef625..c0b48bb635 100644 --- a/pkg/snapshot/provider/provider.go +++ b/pkg/snapshot/provider/provider.go @@ -15,10 +15,10 @@ import ( "strconv" "strings" "sync" - "time" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" + "golang.org/x/sync/errgroup" ) type Job struct { @@ -43,6 +43,9 @@ type Request struct { type Server struct { Objects store.Local Binary string + // Workers bounds concurrent local materialize-range processes per job. + // Configure before serving requests; values below one retain serial execution. + Workers int mu sync.Mutex running map[string]context.CancelFunc } @@ -136,11 +139,15 @@ func (s *Server) start(id string) { } func (s *Server) batch(ctx context.Context, id, command string, task map[string]any) (protocol.ObjectRef, error) { - attempt := fmt.Sprintf("%d", time.Now().UnixNano()) - dir := filepath.Join(s.Objects.Root, "br", id, "attempts", attempt) - if e := os.MkdirAll(dir, 0o700); e != nil { + parent := filepath.Join(s.Objects.Root, "br", id, "attempts") + if e := os.MkdirAll(parent, 0o700); e != nil { return protocol.ObjectRef{}, protocol.Wrap(e) } + dir, e := os.MkdirTemp(parent, "") + if e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + attempt := filepath.Base(dir) task["protocol_version"] = 1 task["output_dir"] = dir task["attempt_id"] = attempt @@ -175,15 +182,10 @@ func (s *Server) run(ctx context.Context, id string) error { if _, e := s.Objects.Read(key(id), &j); e != nil { return e } - active := func(j *Job) error { - if j.Phase == "CANCELED" || j.Phase == "FAILED" { - return protocol.Invalid("terminal source job") - } - return nil - } + if j.PlanRef.URI == "" { if e := s.update(id, func(j *Job) error { - if e := active(j); e != nil { + if e := activeJob(j); e != nil { return e } j.Phase = "PLANNING" @@ -206,7 +208,7 @@ func (s *Server) run(ctx context.Context, id string) error { return protocol.Invalid("demo supports at most 256 ranges") } if e = s.update(id, func(j *Job) error { - if e := active(j); e != nil { + if e := activeJob(j); e != nil { return e } if j.PlanRef.URI == "" { @@ -225,82 +227,128 @@ func (s *Server) run(ctx context.Context, id string) error { if e := protocol.Read(j.PlanRef, &plan); e != nil { return e } - // A deterministic URI is the completion authority. On recovery, reconcile it - // before launching work, including the export-published/control-not-saved gap. - for _, r := range plan.Ranges { - if e := ctx.Err(); e != nil { - return protocol.Wrap(e) - } - exportKey := "br/" + id + "/range-exports/" + r.RangeID + ".json" - var ex protocol.Export - v, e := s.Objects.Read(exportKey, &ex) - if e != nil { + workers := s.Workers + if workers < 1 { + workers = 1 + } + if e := materializeRanges(ctx, workers, plan.Ranges, func(ctx context.Context, r protocol.Span) error { + return s.materialize(ctx, id, j, r) + }); e != nil { + return e + } + return s.update(id, func(j *Job) error { + if e := activeJob(j); e != nil { return e } - if v == "" { - ref, e := s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 4 << 20}) - if e != nil { - return e - } - if e = protocol.Read(ref, &ex); e != nil { - return e - } - if e = protocol.ValidateExport(j.Spec, j.PlanRef, r, ex); e != nil { - return e + if len(j.Exports) != len(plan.Ranges) { + return protocol.Invalid("source coverage mismatch") + } + j.Phase = "SOURCE_COMPLETE" + return nil + }) +} + +func activeJob(j *Job) error { + if j.Phase == "CANCELED" || j.Phase == "FAILED" { + return protocol.Invalid("terminal source job") + } + return nil +} + +// Cancel and join all workers before the caller records a terminal job state. +func materializeRanges(ctx context.Context, workers int, ranges []protocol.Span, run func(context.Context, protocol.Span) error) error { + group, ctx := errgroup.WithContext(ctx) + jobs := make(chan protocol.Span) + group.Go(func() error { + defer close(jobs) + for _, r := range ranges { + select { + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + case jobs <- r: } - for _, chunk := range ex.Chunks { - info, e := os.Stat(chunk.URI) - if e != nil { + } + return nil + }) + for i := 0; i < workers; i++ { + group.Go(func() error { + for r := range jobs { + if e := ctx.Err(); e != nil { return protocol.Wrap(e) } - if info.Size() != chunk.Size { - return protocol.Invalid("incomplete upload") + if e := run(ctx, r); e != nil { + return e } } - _, e = s.Objects.CAS(exportKey, "", ex) - if e != nil { - return e - } - if _, e = s.Objects.Read(exportKey, &ex); e != nil { - return e - } + return nil + }) + } + return group.Wait() +} + +func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.Span) error { + // A deterministic URI is the completion authority. Recover a published + // winner before launching work, then reconcile the append-only journal. + exportKey := "br/" + id + "/range-exports/" + r.RangeID + ".json" + var ex protocol.Export + v, e := s.Objects.Read(exportKey, &ex) + if e != nil { + return e + } + if v == "" { + ref, e := s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 4 << 20}) + if e != nil { + return e } - if e = protocol.ValidateExport(j.Spec, j.PlanRef, r, ex); e != nil { + if e = protocol.Read(ref, &ex); e != nil { return e } - path, _ := s.Objects.Path(exportKey) - ref, e := protocol.Ref(path) - if e != nil { + if e = protocol.ValidateExport(j.Spec, j.PlanRef, r, ex); e != nil { return e } - if e = s.update(id, func(j *Job) error { - if e := active(j); e != nil { - return e + for _, chunk := range ex.Chunks { + info, e := os.Stat(chunk.URI) + if e != nil { + return protocol.Wrap(e) } - for _, old := range j.Exports { - if old.URI == ref.URI { - if old != ref { - return protocol.Invalid("export winner changed") - } - return nil - } + if info.Size() != chunk.Size { + return protocol.Invalid("incomplete upload") } - j.Exports = append(j.Exports, ref) - return nil - }); e != nil { + } + _, e = s.Objects.CAS(exportKey, "", ex) + if e != nil { + return e + } + if _, e = s.Objects.Read(exportKey, &ex); e != nil { return e } } - return s.update(id, func(j *Job) error { - if e := active(j); e != nil { + if e = protocol.ValidateExport(j.Spec, j.PlanRef, r, ex); e != nil { + return e + } + path, _ := s.Objects.Path(exportKey) + ref, e := protocol.Ref(path) + if e != nil { + return e + } + if e = s.update(id, func(j *Job) error { + if e := activeJob(j); e != nil { return e } - if len(j.Exports) != len(plan.Ranges) { - return protocol.Invalid("source coverage mismatch") + for _, old := range j.Exports { + if old.URI == ref.URI { + if old != ref { + return protocol.Invalid("export winner changed") + } + return nil + } } - j.Phase = "SOURCE_COMPLETE" + j.Exports = append(j.Exports, ref) return nil - }) + }); e != nil { + return e + } + return nil } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/snapshot/provider/provider_test.go b/pkg/snapshot/provider/provider_test.go index 9e1167d93f..7de96ed215 100644 --- a/pkg/snapshot/provider/provider_test.go +++ b/pkg/snapshot/provider/provider_test.go @@ -4,6 +4,8 @@ package provider import ( "context" "net/http/httptest" + "sync" + "sync/atomic" "testing" "time" @@ -13,6 +15,7 @@ import ( func TestPublishedExportRecoveredAndCursorFinalTail(t *testing.T) { s := New(t.TempDir(), "must-not-run") + s.Workers = 4 spec := protocol.Spec{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, SelectedSpans: []protocol.Span{{TableID: 1, Start: []byte("a"), End: []byte("z")}}} plan := protocol.Plan{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, Ranges: []protocol.Span{{RangeID: "r0", TableID: 1, Start: []byte("a"), End: []byte("m")}, {RangeID: "r1", TableID: 1, Start: []byte("m"), End: []byte("z")}}} ref, e := s.Objects.Put("plan", plan) @@ -51,3 +54,96 @@ func TestPublishedExportRecoveredAndCursorFinalTail(t *testing.T) { require.NoError(t, e) require.Error(t, client.Call(context.Background(), "ensure", Request{SpecRef: other}, &job)) } + +func TestMaterializeRangesBoundedAndComplete(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ranges := make([]protocol.Span, 20) + for i := range ranges { + ranges[i].TableID = int64(i) + } + var active, peak atomic.Int32 + var mu sync.Mutex + seen := make(map[int64]int) + started := make(chan struct{}, 20) + release := make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- materializeRanges(ctx, 4, ranges, func(ctx context.Context, r protocol.Span) error { + n := active.Add(1) + defer active.Add(-1) + for old := peak.Load(); n > old; old = peak.Load() { + if peak.CompareAndSwap(old, n) { + break + } + } + started <- struct{}{} + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } + mu.Lock() + seen[r.TableID]++ + mu.Unlock() + return nil + }) + }() + for i := 0; i < 4; i++ { + select { + case <-started: + case <-ctx.Done(): + t.Fatal("four workers did not start") + } + } + require.EqualValues(t, 4, active.Load()) + close(release) + require.NoError(t, <-done) + require.EqualValues(t, 4, peak.Load()) + require.Zero(t, active.Load()) + require.Len(t, seen, len(ranges)) + for _, count := range seen { + require.Equal(t, 1, count) + } +} + +func TestMaterializeRangesFailureCancelsAndJoins(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ranges := make([]protocol.Span, 20) + for i := range ranges { + ranges[i].TableID = int64(i) + } + failure := protocol.Invalid("worker failed") + started := make(chan struct{}, 4) + fail := make(chan struct{}) + var active atomic.Int32 + done := make(chan error, 1) + go func() { + done <- materializeRanges(ctx, 4, ranges, func(ctx context.Context, r protocol.Span) error { + active.Add(1) + defer active.Add(-1) + started <- struct{}{} + if r.TableID == 0 { + select { + case <-fail: + return failure + case <-ctx.Done(): + return ctx.Err() + } + } + <-ctx.Done() + return ctx.Err() + }) + }() + for i := 0; i < 4; i++ { + select { + case <-started: + case <-ctx.Done(): + t.Fatal("four workers did not start") + } + } + close(fail) + require.ErrorIs(t, <-done, failure) + require.Zero(t, active.Load()) +} diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index 30fb28f98f..04def1da8d 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -87,7 +87,7 @@ python3 tests/integration_tests/native_snapshot/demo.py stop --root "$OLD_RUN" # A Python environment with boto3 is needed only for prepare; credentials are # read from the existing CSE config and never put in the manifest or sink URI. python3 tests/integration_tests/native_snapshot/demo.py prepare --root "$RUN" --reset-fixture -python3 tests/integration_tests/native_snapshot/demo.py start --root "$RUN" --cluster-id unique-demo-cluster +python3 tests/integration_tests/native_snapshot/demo.py start --root "$RUN" --cluster-id unique-demo-cluster --provider-workers 1 python3 tests/integration_tests/native_snapshot/demo.py create --root "$RUN" --name unique-demo-feed --topic unique-demo-topic python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" --name unique-demo-feed python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" --name unique-demo-feed --topic unique-demo-topic @@ -200,3 +200,17 @@ go test -tags=intest ./maintainer ./coordinator ./api/v2 ./downstreamadapter/dis cargo test -p cse-ctl snapshot cargo test -p native_br packed_reader ``` + +### Local parallel export workers + +`demo.py start --provider-workers 4` runs up to four `cse-ctl snapshot +materialize-range` processes concurrently per job. The standalone Provider flag +is `-workers 4` (default 1; accepted range 1–32). Planning still runs once, and +TiCDC retains its existing snapshot consumption path. This is local process +concurrency, not Kubernetes scheduling or multiple TiCDC captures. + +Each worker has a separate attempt directory. Completed exports are validated +and published through the existing immutable winner/CAS journal. A worker error +cancels and joins the other workers before the job becomes FAILED; previously +published valid results remain durable. Recovery reconciles those winners +without exporting them again. diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py index 4ba17a9429..0e86bb3e5f 100644 --- a/tests/integration_tests/native_snapshot/demo.py +++ b/tests/integration_tests/native_snapshot/demo.py @@ -22,6 +22,7 @@ def main(): parser.add_argument("--sql-port", default="4400") parser.add_argument("--broker", default="10.2.15.7:9092") parser.add_argument("--server", default="http://127.0.0.1:18300") + parser.add_argument("--provider-workers", type=int, default=1) parser.add_argument("--provider", default="http://127.0.0.1:18400") parser.add_argument("--worker", default="http://127.0.0.1:39000") parser.add_argument("--name", default="native-snapshot-demo") @@ -96,7 +97,7 @@ def get(name): env.update(DFS_S3_KEY_ID=config("s3-key-id"), DFS_S3_SECRET_KEY=config("s3-secret-key")) from urllib.parse import urlsplit commands = { - "provider": [str(root/"bin/snapshot-provider"), "-root", str(root/"artifacts"), "-cse-binary", args.cse_binary, "-listen", urlsplit(args.provider).netloc], + "provider": [str(root/"bin/snapshot-provider"), "-root", str(root/"artifacts"), "-cse-binary", args.cse_binary, "-listen", urlsplit(args.provider).netloc, "-workers", str(args.provider_workers)], "cdc": [str(root/"bin/cdc"), "server", "--pd="+args.pd, "--addr=0.0.0.0:"+str(urlsplit(args.server).port), "--advertise-addr="+args.advertise_addr, "--cluster-id="+args.cluster_id, "--data-dir="+str(root/"cdc-data"), "--log-file="+str(root/"logs/cdc.log"), "--config="+str(root/"cdc.toml")], } for name, command in commands.items(): From fb0a9c91fcf3b8bd45b3858d68178f89c7ce9c22 Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 12:16:42 +0800 Subject: [PATCH 05/17] snapshot: record local worker resource usage per attempt Signed-off-by: dongmen <414110582@qq.com> --- pkg/snapshot/provider/provider.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/provider/provider.go index c0b48bb635..b5584cf10d 100644 --- a/pkg/snapshot/provider/provider.go +++ b/pkg/snapshot/provider/provider.go @@ -12,9 +12,12 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strconv" "strings" "sync" + "syscall" + "time" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" @@ -167,7 +170,24 @@ func (s *Server) batch(ctx context.Context, id, command string, task map[string] cmd := exec.CommandContext(ctx, s.Binary, "snapshot", command, "--task-spec", taskFile) cmd.Stdout = log cmd.Stderr = log - if e = cmd.Run(); e != nil { + started := time.Now() + e = cmd.Run() + // Observability only: worker resource accounting is not part of the export + // protocol and must never turn a completed export into a failed attempt. + if state := cmd.ProcessState; state != nil { + stats := map[string]any{"command": command, "pid": state.Pid(), "started_at": started.UnixNano(), "finished_at": time.Now().UnixNano(), "user_cpu_seconds": state.UserTime().Seconds(), "system_cpu_seconds": state.SystemTime().Seconds(), "success": state.Success()} + if usage, ok := state.SysUsage().(*syscall.Rusage); ok { + peakRSS := usage.Maxrss + if runtime.GOOS != "darwin" { + peakRSS *= 1024 + } + stats["peak_rss_bytes"] = peakRSS + } + if data, err := json.Marshal(stats); err == nil { + _ = os.WriteFile(filepath.Join(dir, "worker-stats.json"), data, 0o600) + } + } + if e != nil { return protocol.ObjectRef{}, protocol.Wrap(e) } name := "candidate.json" From a3ca336f413987d64ce3b38e13534810a0b037a7 Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 12:33:19 +0800 Subject: [PATCH 06/17] docs: describe snapshot worker resource diagnostics Signed-off-by: dongmen <414110582@qq.com> --- tests/integration_tests/native_snapshot/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index 04def1da8d..d8e4f4f1bb 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -214,3 +214,9 @@ and published through the existing immutable winner/CAS journal. A worker error cancels and joins the other workers before the job becomes FAILED; previously published valid results remain durable. Recovery reconciles those winners without exporting them again. + +Completed child processes also leave a diagnostic `worker-stats.json` in their +attempt directory, including user/system CPU seconds, peak RSS, elapsed wall +boundaries, and exit status. This file is optional observability data, not an +export receipt or part of the shared artifact protocol. A failure to write it +does not invalidate an otherwise completed export. From 0c1b420cc20c3dad7339a32809c65aaac02df25e Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 14:00:43 +0800 Subject: [PATCH 07/17] snapshot: batch native sink writes with bounded parallel apply --- .../dispatchermanager/dispatcher_manager.go | 7 +- .../dispatchermanager/snapshot.go | 225 +++++++++++++----- .../dispatchermanager/snapshot_test.go | 162 +++++++++++++ downstreamadapter/sink/helper/mq_row_event.go | 18 +- .../sink/helper/snapshot_test.go | 33 +++ maintainer/snapshot.go | 4 + pkg/common/event/row_change.go | 1 - pkg/sink/codec/open/codec.go | 2 - pkg/sink/codec/open/snapshot_test.go | 8 +- pkg/snapshot/bootstrap/controller.go | 94 ++++++-- pkg/snapshot/bootstrap/controller_test.go | 105 ++++++++ .../bootstrap/interfaces_mock_test.go | 130 ++++++++++ pkg/snapshot/protocol/chunk.go | 35 ++- pkg/snapshot/protocol/protocol_test.go | 31 +++ pkg/snapshot/protocol/types.go | 35 ++- scripts/generate-mock.sh | 1 + .../native_snapshot/README.md | 19 +- .../integration_tests/native_snapshot/demo.py | 2 +- .../native_snapshot/verify/main.go | 42 +++- 19 files changed, 847 insertions(+), 107 deletions(-) create mode 100644 downstreamadapter/dispatchermanager/snapshot_test.go create mode 100644 downstreamadapter/sink/helper/snapshot_test.go create mode 100644 pkg/snapshot/bootstrap/controller_test.go create mode 100644 pkg/snapshot/bootstrap/interfaces_mock_test.go diff --git a/downstreamadapter/dispatchermanager/dispatcher_manager.go b/downstreamadapter/dispatchermanager/dispatcher_manager.go index 1c594fc3c2..71c665f6ae 100644 --- a/downstreamadapter/dispatchermanager/dispatcher_manager.go +++ b/downstreamadapter/dispatchermanager/dispatcher_manager.go @@ -148,7 +148,10 @@ type DispatcherManager struct { // writeSink is the capture-write-gated view passed to dispatchers. // sink remains the concrete implementation used for lifecycle and // sink-specific recovery operations. - writeSink sink.Sink + writeSink sink.Sink + sinkStopped chan struct{} + snapshotMu sync.Mutex + snapshotRuntime *snapshotRuntime // redo related // redoEnabled is immutable and set to true if enabled. @@ -236,6 +239,7 @@ func NewDispatcherManager( } manager = &DispatcherManager{ + sinkStopped: make(chan struct{}), ctx: ctx, dispatcherMap: newDispatcherMap[*dispatcher.EventDispatcher](), currentOperatorMap: sync.Map{}, @@ -393,6 +397,7 @@ func NewDispatcherManager( go func() { defer manager.wg.Done() err := manager.sink.Run(ctx) + close(manager.sinkStopped) manager.handleError(ctx, err) }() diff --git a/downstreamadapter/dispatchermanager/snapshot.go b/downstreamadapter/dispatchermanager/snapshot.go index ad0c2308ac..90e44b7bb0 100644 --- a/downstreamadapter/dispatchermanager/snapshot.go +++ b/downstreamadapter/dispatchermanager/snapshot.go @@ -2,9 +2,10 @@ package dispatchermanager import ( + "bytes" "context" - "encoding/base64" "sync" + "sync/atomic" "time" "github.com/pingcap/ticdc/pkg/common" @@ -13,92 +14,200 @@ import ( "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/tidb/pkg/util/chunk" + "golang.org/x/sync/semaphore" ) -// ApplySnapshot is the second data entry to the same capture-owned sink. It -// mounts frozen schema, preserves ordinary row routing, and waits for broker -// callbacks. It does not start or own the CSE process. -func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - stop := context.AfterFunc(e.ctx, cancel) - defer stop() - if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { - return 0, protocol.Invalid("capture write authority lost") +const ( + snapshotBatchRows = 256 + snapshotBatchBytes = 1 << 20 + // Account for keys, row metadata and callback/queue overhead in addition to KV. + snapshotRowOverhead = 512 +) + +type snapshotRuntime struct { + spec protocol.Spec + tables map[int64]*common.TableInfo + budget *semaphore.Weighted + limit int64 +} + +// The immutable schema bundle is shared by all range workers of this capture. +// Its digest and snapshot identity prevent using live or another generation's +// TableInfo while decoding the frozen backup. +func (e *DispatcherManager) getSnapshotRuntime(spec protocol.Spec) (*snapshotRuntime, error) { + e.snapshotMu.Lock() + defer e.snapshotMu.Unlock() + if r := e.snapshotRuntime; r != nil { + if r.spec.JobID != spec.JobID || r.spec.SnapshotID != spec.SnapshotID || r.spec.SnapshotTS != spec.SnapshotTS || r.spec.SchemaRef != spec.SchemaRef { + return nil, protocol.Invalid("snapshot schema identity changed") + } + return r, nil + } + var cfg *protocol.Config + if e.config != nil { + cfg = e.config.Snapshot + } + if err := cfg.ValidateRuntime(); err != nil { + return nil, err } var bundle bootstrap.SchemaBundle if err := protocol.Read(spec.SchemaRef, &bundle); err != nil { - return 0, err + return nil, err } if bundle.SnapshotTS != spec.SnapshotTS { - return 0, protocol.Invalid("schema timestamp mismatch") + return nil, protocol.Invalid("schema timestamp mismatch") } - var table *common.TableInfo - var schema string + tables := make(map[int64]*common.TableInfo, len(bundle.Tables)) for _, s := range bundle.Tables { - if s.TableID == ex.Range.TableID { - var err error - table, err = common.UnmarshalJSONToTableInfo(s.Data) - if err != nil { - return 0, protocol.Wrap(err) + table, err := common.UnmarshalJSONToTableInfo(s.Data) + if err != nil { + return nil, protocol.Wrap(err) + } + if tables[s.TableID] != nil { + return nil, protocol.Invalid("invalid frozen table identity") + } + tables[s.TableID] = table + } + r := &snapshotRuntime{spec: spec, tables: tables, limit: cfg.InflightLimit(), budget: semaphore.NewWeighted(cfg.InflightLimit())} + e.snapshotRuntime = r + return r, nil +} + +// snapshotAcks observes existing sink PostFlush callbacks, not enqueue events. +// Cancellation never leaves a goroutine waiting forever for abandoned callbacks. +type snapshotAcks struct { + pending atomic.Int64 + changed chan struct{} +} + +func newSnapshotAcks() *snapshotAcks { return &snapshotAcks{changed: make(chan struct{}, 1)} } +func (a *snapshotAcks) add(release func()) func() { + a.pending.Add(1) + var once sync.Once + return func() { + once.Do(func() { + release() + if a.pending.Add(-1) == 0 { + select { + case a.changed <- struct{}{}: + default: + } + } + }) + } +} + +func (a *snapshotAcks) wait(ctx context.Context) error { + for a.pending.Load() != 0 { + select { + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + case <-a.changed: + } + } + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + return nil +} + +// ApplySnapshot mounts bounded batches into the existing capture-owned sink. +// Workers share a byte budget released by broker ACKs. Only range completion +// drains all its callbacks; ordinary submission keeps the sink pipeline fed. +func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + if e.sinkStopped != nil { + go func() { + select { + case <-e.sinkStopped: + cancel() + case <-ctx.Done(): } - schema = base64.StdEncoding.EncodeToString(s.Data) - break + }() + } + stop := context.AfterFunc(e.ctx, cancel) + defer stop() + authorized := func() error { + select { + case <-e.sinkStopped: + return protocol.Invalid("snapshot sink stopped") + default: } + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { + return protocol.Invalid("snapshot writer fenced") + } + return nil + } + if err := authorized(); err != nil { + return 0, err + } + runtime, err := e.getSnapshotRuntime(spec) + if err != nil { + return 0, err } + table := runtime.tables[ex.Range.TableID] if table == nil { return 0, protocol.Invalid("missing frozen table schema") } mounter := commonEvent.NewMounter(time.UTC, &integrity.Config{}) + acks := newSnapshotAcks() + dispatcherID := common.NewDispatcherID() var rows uint64 - done := make(chan struct{}, 128) - queued := 0 - wait := func() error { - for queued > 0 { - select { - case <-done: - queued-- - case <-ctx.Done(): - return protocol.Wrap(ctx.Err()) - } + var batch *commonEvent.DMLEvent + submit := func() error { + if batch == nil || batch.Length == 0 { + return nil + } + charge := batch.ApproximateSize + int64(batch.Length)*snapshotRowOverhead + if charge > runtime.limit { + return protocol.Invalid("snapshot batch exceeds in-flight byte budget") } + if err := runtime.budget.Acquire(ctx, charge); err != nil { + return protocol.Wrap(err) + } + if err := authorized(); err != nil { + runtime.budget.Release(charge) + return err + } + batch.AddPostFlushFunc(acks.add(func() { runtime.budget.Release(charge) })) + e.writeSink.AddDMLEvent(batch) + batch = nil return nil } for seq, c := range ex.Chunks { expected := protocol.Header{Version: 1, Compression: "none", JobID: spec.JobID, SnapshotID: spec.SnapshotID, SnapshotTS: spec.SnapshotTS, PlanDigest: ref.Digest, RangeID: ex.Range.RangeID, AttemptID: ex.AttemptID, TableID: ex.Range.TableID, Seq: uint64(seq)} _, err := protocol.DecodeChunk(c, expected, ex.Range, func(key, value []byte) error { - if err := ctx.Err(); err != nil { - return protocol.Wrap(err) + if err := authorized(); err != nil { + return err } - if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { - return protocol.Invalid("snapshot writer fenced") + if batch == nil { + batch = commonEvent.NewDMLEvent(dispatcherID, ex.Range.TableID, 0, spec.SnapshotTS, table) + batch.Rows = chunk.NewChunkWithCapacity(table.GetFieldSlice(), snapshotBatchRows) + batch.RowTypes = make([]common.RowType, 0, snapshotBatchRows) + batch.RowKeys = make([][]byte, 0, snapshotBatchRows) + batch.Snapshot = &commonEvent.SnapshotRow{SnapshotID: spec.SnapshotID, Timestamp: spec.SnapshotTS} } - chk := chunk.NewChunkWithCapacity(table.GetFieldSlice(), 1) raw := &common.RawKVEntry{Key: key, Value: value, CRTs: spec.SnapshotTS} - n, checksum, err := mounter.DecodeToChunk(raw, table, chk) + n, checksum, err := mounter.DecodeToChunk(raw, table, batch.Rows) if err != nil { return protocol.Wrap(err) } if n != 1 { return protocol.Invalid("snapshot KV did not mount to one row") } - ev := commonEvent.NewDMLEvent(common.NewDispatcherID(), ex.Range.TableID, 0, spec.SnapshotTS, table) - ev.Rows = chk - ev.Length = 1 - ev.RowTypes = []common.RowType{common.RowTypeInsert} - ev.RowKeys = [][]byte{key} - ev.ApproximateSize = int64(len(key) + len(value)) - ev.Snapshot = &commonEvent.SnapshotRow{ID: protocol.RecordID(spec.SnapshotID, ex.Range.TableID, key), SnapshotID: spec.SnapshotID, Timestamp: spec.SnapshotTS, Schema: schema} - if checksum != nil { - ev.Checksum = append(ev.Checksum, checksum) - } - var once sync.Once - ev.AddPostFlushFunc(func() { once.Do(func() { done <- struct{}{} }) }) - e.writeSink.AddDMLEvent(ev) - queued++ + batch.Length++ + batch.RowTypes = append(batch.RowTypes, common.RowTypeInsert) + // Do not retain a whole verified input file through a small row key. + batch.RowKeys = append(batch.RowKeys, bytes.Clone(key)) + batch.ApproximateSize += int64(len(key) + len(value)) + batch.Checksum = append(batch.Checksum, checksum) rows++ - if queued >= 128 { - return wait() + if batch.Length >= snapshotBatchRows || batch.ApproximateSize >= snapshotBatchBytes { + return submit() } return nil }) @@ -106,7 +215,13 @@ func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spe return rows, err } } - if err := wait(); err != nil { + if err := submit(); err != nil { + return rows, err + } + if err := acks.wait(ctx); err != nil { + return rows, err + } + if err := authorized(); err != nil { return rows, err } if rows != ex.KVCount { diff --git a/downstreamadapter/dispatchermanager/snapshot_test.go b/downstreamadapter/dispatchermanager/snapshot_test.go new file mode 100644 index 0000000000..096e66d883 --- /dev/null +++ b/downstreamadapter/dispatchermanager/snapshot_test.go @@ -0,0 +1,162 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package dispatchermanager + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/golang/mock/gomock" + "github.com/pingcap/ticdc/downstreamadapter/sink/mock" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/snapshot/store" + "github.com/stretchr/testify/require" +) + +func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + job := helper.DDL2Job("create table test.snap_batch (id int primary key, v varchar(50))") + table := helper.GetTableInfo(job) + raw := helper.DML2RawKv(table.TableName.TableID, table.GetUpdateTS(), + "insert into test.snap_batch values(1,'first')", "insert into test.snap_batch values(2,'second')", "insert into test.snap_batch values(3,'third')") + objects := store.Local{Root: t.TempDir()} + schema, err := table.Marshal() + require.NoError(t, err) + schemaRef, err := objects.Put("schema.json", bootstrap.SchemaBundle{SnapshotTS: 42, Tables: []bootstrap.Schema{{TableID: table.TableName.TableID, Data: schema}}}) + require.NoError(t, err) + spec := protocol.Spec{JobID: "j", SnapshotID: "s", SnapshotTS: 42, SchemaRef: schemaRef} + plan := protocol.ObjectRef{Digest: "p"} + span := protocol.Span{RangeID: "r", TableID: table.TableName.TableID, Start: raw[0].Key, End: append(bytes.Clone(raw[2].Key), 0)} + header := protocol.Header{Version: 1, Compression: "none", JobID: "j", SnapshotID: "s", SnapshotTS: 42, PlanDigest: "p", RangeID: "r", AttemptID: "a", TableID: span.TableID} + var file, block bytes.Buffer + u32 := func(b *bytes.Buffer, n int) { require.NoError(t, binary.Write(b, binary.LittleEndian, uint32(n))) } + metadata := func(v any) []byte { b, err := json.Marshal(v); require.NoError(t, err); return b } + file.WriteString("SNAPKV01") + h := metadata(header) + u32(&file, len(h)) + file.Write(h) + var size uint64 + for _, kv := range raw { + u32(&block, len(kv.Key)) + u32(&block, len(kv.Value)) + block.Write(kv.Key) + block.Write(kv.Value) + size += uint64(len(kv.Key) + len(kv.Value)) + } + u32(&file, block.Len()) + u32(&file, len(raw)) + file.Write(block.Bytes()) + footer := metadata(protocol.Footer{Blocks: 1, KVCount: 3, LogicalBytes: size, First: raw[0].Key, Last: raw[2].Key}) + u32(&file, 0) + u32(&file, len(footer)) + file.Write(footer) + file.WriteString("SNAPEND1") + path := filepath.Join(objects.Root, "chunk") + require.NoError(t, os.WriteFile(path, file.Bytes(), 0o600)) + object, err := protocol.Ref(path) + require.NoError(t, err) + ex := protocol.Export{Range: span, AttemptID: "a", KVCount: 3, Chunks: []protocol.Chunk{{ObjectRef: object, KVCount: 3, LogicalBytes: size, First: raw[0].Key, Last: raw[2].Key}}} + sk := mock.NewMockSink(gomock.NewController(t)) + submitted := make(chan *commonEvent.DMLEvent, 4) + sk.EXPECT().AddDMLEvent(gomock.Any()).Do(func(ev *commonEvent.DMLEvent) { submitted <- ev }).AnyTimes() + manager := &DispatcherManager{ctx: context.Background(), writeSink: sk, sinkStopped: make(chan struct{})} + manager.meta.maintainerEpoch = 7 + run := func(ctx context.Context) <-chan error { + done := make(chan error, 1) + go func() { + n, err := manager.ApplySnapshot(ctx, 7, spec, plan, ex) + if err == nil && n != 3 { + done <- protocol.Invalid("unexpected count") + return + } + done <- err + }() + return done + } + done := run(context.Background()) + var ev *commonEvent.DMLEvent + select { + case ev = <-submitted: + case <-time.After(10 * time.Second): + t.Fatal("no batch") + } + require.EqualValues(t, 3, ev.Length) + require.Equal(t, 3, ev.Rows.NumRows()) + require.Equal(t, "first", ev.Rows.GetRow(0).GetString(1)) + require.Equal(t, "third", ev.Rows.GetRow(2).GetString(1)) + require.Equal(t, raw[0].Key, ev.RowKeys[0]) + require.Equal(t, raw[2].Key, ev.RowKeys[2]) + select { + case <-done: + t.Fatal("range completed before ACK") + default: + } + ev.PostFlush() + ev.PostFlush() // duplicate callback must not release budget twice + require.NoError(t, <-done) + runtime, err := manager.getSnapshotRuntime(spec) + require.NoError(t, err) + require.True(t, runtime.budget.TryAcquire(runtime.limit)) + runtime.budget.Release(runtime.limit) + require.NoError(t, os.Remove(schemaRef.URI)) + cached, err := manager.getSnapshotRuntime(spec) + require.NoError(t, err) + require.Same(t, runtime, cached) + changed := spec + changed.SnapshotID = "other" + _, err = manager.getSnapshotRuntime(changed) + require.ErrorContains(t, err, "identity changed") + + // Backpressure can be canceled before submission, without leaking a waiter. + require.NoError(t, runtime.budget.Acquire(context.Background(), runtime.limit)) + ctx, cancel := context.WithCancel(context.Background()) + done = run(ctx) + cancel() + require.Error(t, <-done) + runtime.budget.Release(runtime.limit) + select { + case <-submitted: + t.Fatal("submitted without budget") + default: + } + + done = run(context.Background()) + ev = <-submitted + manager.writePathClosed.Store(true) + ev.PostFlush() + require.ErrorContains(t, <-done, "fenced") + manager.writePathClosed.Store(false) + done = run(context.Background()) + ev = <-submitted + close(manager.sinkStopped) + select { + case err := <-done: + require.Error(t, err) + case <-time.After(time.Second): + t.Fatal("sink failure stranded range ACK waiter") + } + ev.PostFlush() +} + +func TestSnapshotAcksCancellation(t *testing.T) { + acks := newSnapshotAcks() + released := 0 + first := acks.add(func() { released++ }) + second := acks.add(func() { released++ }) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + require.Error(t, acks.wait(ctx)) + first() + first() + second() + require.NoError(t, acks.wait(context.Background())) + require.Equal(t, 2, released) +} diff --git a/downstreamadapter/sink/helper/mq_row_event.go b/downstreamadapter/sink/helper/mq_row_event.go index a410da47ca..1901953b3c 100644 --- a/downstreamadapter/sink/helper/mq_row_event.go +++ b/downstreamadapter/sink/helper/mq_row_event.go @@ -17,6 +17,7 @@ import ( "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" "github.com/pingcap/ticdc/downstreamadapter/sink/eventrouter/partition" commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" ) func NewMQRowEvents( @@ -53,7 +54,7 @@ func NewMQRowEvents( TotalPartition: partitionNum, }, RowEvent: commonEvent.RowEvent{ - Snapshot: event.Snapshot, + Snapshot: snapshotRow(event, row), PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, StartTs: event.StartTs, @@ -86,7 +87,7 @@ func NewRowEvents( } events = append(events, &commonEvent.RowEvent{ - Snapshot: event.Snapshot, + Snapshot: snapshotRow(event, row), PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, StartTs: event.StartTs, @@ -99,3 +100,16 @@ func NewRowEvents( } return events } + +// A mounted snapshot batch shares generation metadata, but every row has its +// own identity. Never copy a batch-level record ID to all rows in the batch. +func snapshotRow(event *commonEvent.DMLEvent, row commonEvent.RowChange) *commonEvent.SnapshotRow { + if event.Snapshot == nil { + return nil + } + return &commonEvent.SnapshotRow{ + ID: protocol.RecordID(event.Snapshot.SnapshotID, event.PhysicalTableID, row.RowKey), + SnapshotID: event.Snapshot.SnapshotID, + Timestamp: event.Snapshot.Timestamp, + } +} diff --git a/downstreamadapter/sink/helper/snapshot_test.go b/downstreamadapter/sink/helper/snapshot_test.go new file mode 100644 index 0000000000..3074c90c29 --- /dev/null +++ b/downstreamadapter/sink/helper/snapshot_test.go @@ -0,0 +1,33 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package helper + +import ( + "testing" + + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestSnapshotBatchPreservesPerRowIdentity(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + helper.DDL2Job("create table test.snap_ids (id int primary key, v int)") + ev := helper.DML2Event("test", "snap_ids", "insert into test.snap_ids values(1,10)", "insert into test.snap_ids values(2,20)") + ev.Snapshot = &commonEvent.SnapshotRow{SnapshotID: "generation", Timestamp: 42} + flushed := 0 + ev.AddPostFlushFunc(func() { flushed++ }) + rows := NewRowEvents(ev, nil, NewPostFlushRowCallback(ev, uint64(ev.Len()))) + require.Len(t, rows, 2) + require.NotEqual(t, rows[0].Snapshot.ID, rows[1].Snapshot.ID) + for i, row := range rows { + require.Equal(t, protocol.RecordID("generation", ev.PhysicalTableID, ev.RowKeys[i]), row.Snapshot.ID) + require.Equal(t, uint64(42), row.Snapshot.Timestamp) + } + rows[1].Callback() + require.Zero(t, flushed) + rows[0].Callback() + require.Equal(t, 1, flushed) + ev.Snapshot = nil + require.Nil(t, snapshotRow(ev, rows[0].Event)) +} diff --git a/maintainer/snapshot.go b/maintainer/snapshot.go index c8be0bff97..bcc8832de1 100644 --- a/maintainer/snapshot.go +++ b/maintainer/snapshot.go @@ -25,6 +25,10 @@ func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb. return false } cfg := m.info.Config.Snapshot + if err := cfg.ValidateRuntime(); err != nil { + m.handleError(err) + return false + } uri, err := url.Parse(m.info.SinkURI) if err != nil { m.handleError(protocol.Wrap(err)) diff --git a/pkg/common/event/row_change.go b/pkg/common/event/row_change.go index 0b4a1b4ed0..da85a8db95 100644 --- a/pkg/common/event/row_change.go +++ b/pkg/common/event/row_change.go @@ -92,7 +92,6 @@ type SnapshotRow struct { ID string SnapshotID string Timestamp uint64 - Schema string } type RowEvent struct { diff --git a/pkg/sink/codec/open/codec.go b/pkg/sink/codec/open/codec.go index 75527f2567..0331572919 100644 --- a/pkg/sink/codec/open/codec.go +++ b/pkg/sink/codec/open/codec.go @@ -49,8 +49,6 @@ func encodeRowChangedEvent( keyWriter.WriteStringField("snapshot_record_id", e.Snapshot.ID) keyWriter.WriteStringField("snapshot_id", e.Snapshot.SnapshotID) keyWriter.WriteUint64Field("snapshot_ts", e.Snapshot.Timestamp) - keyWriter.WriteStringField("snapshot_schema", e.Snapshot.Schema) - keyWriter.WriteStringField("snapshot_schema_encoding", "ticdc-table-info-base64-v1") } keyWriter.WriteStringField("scm", e.TableInfo.GetTargetSchemaName()) keyWriter.WriteStringField("tbl", e.TableInfo.GetTargetTableName()) diff --git a/pkg/sink/codec/open/snapshot_test.go b/pkg/sink/codec/open/snapshot_test.go index 82536e1431..63ed043cdc 100644 --- a/pkg/sink/codec/open/snapshot_test.go +++ b/pkg/sink/codec/open/snapshot_test.go @@ -11,18 +11,20 @@ import ( "github.com/stretchr/testify/require" ) -func TestSnapshotEnvelopeKeepsIdentityAndInlineSchema(t *testing.T) { +func TestSnapshotEnvelopeKeepsIdentityWithoutInlineSchema(t *testing.T) { helper := commonEvent.NewEventTestHelper(t) defer helper.Close() helper.DDL2Job("create table test.snap (id int primary key, v int)") event := helper.DML2Event("test", "snap", "insert into test.snap values(1,10)") row, ok := event.GetNextRow() require.True(t, ok) - e := &commonEvent.RowEvent{PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, Event: row, CommitTs: 42, ColumnSelector: columnselector.NewDefaultColumnSelector(), Snapshot: &commonEvent.SnapshotRow{ID: "stable", SnapshotID: "generation", Timestamp: 42, Schema: "c2NoZW1h"}} + e := &commonEvent.RowEvent{PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, Event: row, CommitTs: 42, ColumnSelector: columnselector.NewDefaultColumnSelector(), Snapshot: &commonEvent.SnapshotRow{ID: "stable", SnapshotID: "generation", Timestamp: 42}} key, _, _, err := encodeRowChangedEvent(e, initColumnFlags(e.TableInfo), common.NewConfig(config.ProtocolOpen), false, "") require.NoError(t, err) require.Contains(t, string(key), `"snapshot_record_id":"stable"`) - require.Contains(t, string(key), `"snapshot_schema":"c2NoZW1h"`) + require.NotContains(t, string(key), "snapshot_schema") + require.Contains(t, string(key), `"snapshot_id":"generation"`) + require.Contains(t, string(key), `"snapshot_ts":42`) e.Snapshot = nil key, _, _, err = encodeRowChangedEvent(e, initColumnFlags(e.TableInfo), common.NewConfig(config.ProtocolOpen), false, "") require.NoError(t, err) diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go index 39b973dff7..17663ec3ac 100644 --- a/pkg/snapshot/bootstrap/controller.go +++ b/pkg/snapshot/bootstrap/controller.go @@ -5,6 +5,7 @@ import ( "context" "os" "path/filepath" + "sync" "syscall" "time" @@ -13,6 +14,7 @@ import ( "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/provider" "github.com/pingcap/ticdc/pkg/snapshot/store" + "golang.org/x/sync/errgroup" ) type Controller struct { @@ -27,6 +29,9 @@ type Controller struct { } func (c Controller) Run(ctx context.Context) (result error) { + if err := c.Config.ValidateRuntime(); err != nil { + return err + } objects := store.Local{Root: c.Config.ArtifactDir} dir := filepath.Join(objects.Root, "cdc", c.ID.ID().String()) if err := os.MkdirAll(dir, 0o700); err != nil { @@ -138,34 +143,18 @@ func (c Controller) Run(ctx context.Context) (result error) { return err } applied := 0 + var ready []store.Task for _, task := range all { if task.State == "APPLIED" { applied++ - continue - } - if task.State != "READY" { - continue - } - assigned, err := tasks.Assign(task.Range.RangeID) - if err != nil { - return err + } else if task.State == "READY" { + ready = append(ready, task) } - var ex protocol.Export - if err = protocol.Read(assigned.Export, &ex); err != nil { - return err - } - if err = protocol.ValidateExport(spec, state.PlanRef, task.Range, ex); err != nil { - return err - } - rows, err := c.Capture.ApplySnapshot(ctx, c.ID, c.Epoch, spec, state.PlanRef, ex) - if err != nil { - return err - } - if err = tasks.Commit(task.Range.RangeID, assigned.Lease, rows); err != nil { - return err - } - applied++ } + if err = c.applyReady(ctx, tasks, spec, state.PlanRef, ready); err != nil { + return err + } + applied += len(ready) state.Applied = applied if err = save(); err != nil { return err @@ -237,3 +226,62 @@ func (c Controller) Run(ctx context.Context) (result error) { state.Phase = "SNAPSHOT_COMMITTED" return save() } + +// All workers are joined before Run can abort the sink or release writer.lock. +// Task page writes stay serialized; data application is bounded and concurrent. +func (c Controller) applyReady(ctx context.Context, tasks store.Tasks, spec protocol.Spec, ref protocol.ObjectRef, ready []store.Task) error { + if len(ready) == 0 { + return nil + } + group, ctx := errgroup.WithContext(ctx) + jobs := make(chan store.Task) + var taskMu sync.Mutex + group.Go(func() error { + defer close(jobs) + for _, task := range ready { + select { + case jobs <- task: + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + } + } + return nil + }) + for i := 0; i < min(c.Config.ApplyConcurrency(), len(ready)); i++ { + group.Go(func() error { + for task := range jobs { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + taskMu.Lock() + assigned, err := tasks.Assign(task.Range.RangeID) + taskMu.Unlock() + if err != nil { + return err + } + var ex protocol.Export + if err = protocol.Read(assigned.Export, &ex); err != nil { + return err + } + if err = protocol.ValidateExport(spec, ref, task.Range, ex); err != nil { + return err + } + rows, err := c.Capture.ApplySnapshot(ctx, c.ID, c.Epoch, spec, ref, ex) + if err != nil { + return err + } + if err = ctx.Err(); err != nil { + return protocol.Wrap(err) + } + taskMu.Lock() + err = tasks.Commit(task.Range.RangeID, assigned.Lease, rows) + taskMu.Unlock() + if err != nil { + return err + } + } + return nil + }) + } + return group.Wait() +} diff --git a/pkg/snapshot/bootstrap/controller_test.go b/pkg/snapshot/bootstrap/controller_test.go new file mode 100644 index 0000000000..7b0203ff5a --- /dev/null +++ b/pkg/snapshot/bootstrap/controller_test.go @@ -0,0 +1,105 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package bootstrap + +import ( + "context" + "fmt" + "sync/atomic" + "testing" + "time" + + "github.com/golang/mock/gomock" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/snapshot/store" + "github.com/stretchr/testify/require" +) + +func TestApplyReadyBoundedReceiptsAndCancellation(t *testing.T) { + for _, fail := range []bool{false, true} { + t.Run(fmt.Sprintf("failure=%v", fail), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + objects := store.Local{Root: t.TempDir()} + spec := protocol.Spec{ProtocolVersion: 1, JobID: "j", SnapshotID: "s", SnapshotTS: 42} + plan := protocol.Plan{ProtocolVersion: 1, JobID: "j", SnapshotID: "s", SnapshotTS: 42} + for i := 0; i < 6; i++ { + plan.Ranges = append(plan.Ranges, protocol.Span{RangeID: fmt.Sprint(i), TableID: int64(i + 1), Start: []byte("a"), End: []byte("z")}) + } + ref, err := objects.Put("plan", plan) + require.NoError(t, err) + tasks := store.Tasks{Objects: objects, Job: "j", Digest: ref.Digest, Epoch: 1, Plan: plan} + require.NoError(t, tasks.Init()) + for _, r := range plan.Ranges { + ex := protocol.Export{ProtocolVersion: 1, JobID: "j", SnapshotID: "s", SnapshotTS: 42, PlanDigest: ref.Digest, Range: r, AttemptID: "a"} + export, err := objects.Put("export-"+r.RangeID, ex) + require.NoError(t, err) + require.NoError(t, tasks.Ready(r.RangeID, export)) + } + ready, err := tasks.List() + require.NoError(t, err) + capture := NewMockCapture(gomock.NewController(t)) + started := make(chan struct{}, 6) + release := make(chan struct{}) + var active, peak atomic.Int32 + failure := protocol.Invalid("injected sink failure") + capture.EXPECT().ApplySnapshot(gomock.Any(), gomock.Any(), uint64(1), spec, ref, gomock.Any()).DoAndReturn(func(ctx context.Context, _ common.ChangeFeedID, _ uint64, _ protocol.Spec, _ protocol.ObjectRef, ex protocol.Export) (uint64, error) { + n := active.Add(1) + defer active.Add(-1) + for old := peak.Load(); n > old; old = peak.Load() { + if peak.CompareAndSwap(old, n) { + break + } + } + started <- struct{}{} + if fail && ex.Range.RangeID != "0" { + <-ctx.Done() + return 0, protocol.Wrap(ctx.Err()) + } + select { + case <-release: + case <-ctx.Done(): + return 0, protocol.Wrap(ctx.Err()) + } + if fail { + return 0, failure + } + return 0, nil + }).AnyTimes() + c := Controller{Epoch: 1, Config: &protocol.Config{ApplyWorkers: 2}, Capture: capture} + done := make(chan error, 1) + go func() { done <- c.applyReady(ctx, tasks, spec, ref, ready) }() + for i := 0; i < 2; i++ { + select { + case <-started: + case <-ctx.Done(): + t.Fatal("workers did not start") + } + } + require.EqualValues(t, 2, active.Load()) + inProgress, err := tasks.List() + require.NoError(t, err) + for _, task := range inProgress { + require.NotEqual(t, "APPLIED", task.State) + } + close(release) + err = <-done + if fail { + require.ErrorIs(t, err, failure) + } else { + require.NoError(t, err) + } + require.Zero(t, active.Load()) + require.EqualValues(t, 2, peak.Load()) + final, err := tasks.List() + require.NoError(t, err) + for _, task := range final { + if fail { + require.NotEqual(t, "APPLIED", task.State) + } else { + require.Equal(t, "APPLIED", task.State) + } + } + }) + } +} diff --git a/pkg/snapshot/bootstrap/interfaces_mock_test.go b/pkg/snapshot/bootstrap/interfaces_mock_test.go new file mode 100644 index 0000000000..ec33e40a6b --- /dev/null +++ b/pkg/snapshot/bootstrap/interfaces_mock_test.go @@ -0,0 +1,130 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pkg/snapshot/bootstrap/interfaces.go + +// Package bootstrap is a generated GoMock package. +package bootstrap + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + common "github.com/pingcap/ticdc/pkg/common" + protocol "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +// MockRepository is a mock of Repository interface. +type MockRepository struct { + ctrl *gomock.Controller + recorder *MockRepositoryMockRecorder +} + +// MockRepositoryMockRecorder is the mock recorder for MockRepository. +type MockRepositoryMockRecorder struct { + mock *MockRepository +} + +// NewMockRepository creates a new mock instance. +func NewMockRepository(ctrl *gomock.Controller) *MockRepository { + mock := &MockRepository{ctrl: ctrl} + mock.recorder = &MockRepositoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { + return m.recorder +} + +// LoadSnapshot mocks base method. +func (m *MockRepository) LoadSnapshot(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64) (*protocol.State, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "LoadSnapshot", arg0, arg1, arg2) + ret0, _ := ret[0].(*protocol.State) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// LoadSnapshot indicates an expected call of LoadSnapshot. +func (mr *MockRepositoryMockRecorder) LoadSnapshot(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LoadSnapshot", reflect.TypeOf((*MockRepository)(nil).LoadSnapshot), arg0, arg1, arg2) +} + +// SaveSnapshot mocks base method. +func (m *MockRepository) SaveSnapshot(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64, arg3 *protocol.State) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SaveSnapshot", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(error) + return ret0 +} + +// SaveSnapshot indicates an expected call of SaveSnapshot. +func (mr *MockRepositoryMockRecorder) SaveSnapshot(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveSnapshot", reflect.TypeOf((*MockRepository)(nil).SaveSnapshot), arg0, arg1, arg2, arg3) +} + +// MockCapture is a mock of Capture interface. +type MockCapture struct { + ctrl *gomock.Controller + recorder *MockCaptureMockRecorder +} + +// MockCaptureMockRecorder is the mock recorder for MockCapture. +type MockCaptureMockRecorder struct { + mock *MockCapture +} + +// NewMockCapture creates a new mock instance. +func NewMockCapture(ctrl *gomock.Controller) *MockCapture { + mock := &MockCapture{ctrl: ctrl} + mock.recorder = &MockCaptureMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockCapture) EXPECT() *MockCaptureMockRecorder { + return m.recorder +} + +// AbortSnapshot mocks base method. +func (m *MockCapture) AbortSnapshot(arg0 common.ChangeFeedID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AbortSnapshot", arg0) +} + +// AbortSnapshot indicates an expected call of AbortSnapshot. +func (mr *MockCaptureMockRecorder) AbortSnapshot(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AbortSnapshot", reflect.TypeOf((*MockCapture)(nil).AbortSnapshot), arg0) +} + +// ApplySnapshot mocks base method. +func (m *MockCapture) ApplySnapshot(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64, arg3 protocol.Spec, arg4 protocol.ObjectRef, arg5 protocol.Export) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ApplySnapshot", arg0, arg1, arg2, arg3, arg4, arg5) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ApplySnapshot indicates an expected call of ApplySnapshot. +func (mr *MockCaptureMockRecorder) ApplySnapshot(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplySnapshot", reflect.TypeOf((*MockCapture)(nil).ApplySnapshot), arg0, arg1, arg2, arg3, arg4, arg5) +} + +// DrainSnapshot mocks base method. +func (m *MockCapture) DrainSnapshot(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DrainSnapshot", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// DrainSnapshot indicates an expected call of DrainSnapshot. +func (mr *MockCaptureMockRecorder) DrainSnapshot(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DrainSnapshot", reflect.TypeOf((*MockCapture)(nil).DrainSnapshot), arg0, arg1, arg2) +} diff --git a/pkg/snapshot/protocol/chunk.go b/pkg/snapshot/protocol/chunk.go index 5334b76753..276afae988 100644 --- a/pkg/snapshot/protocol/chunk.go +++ b/pkg/snapshot/protocol/chunk.go @@ -40,19 +40,50 @@ func DecodeChunk(ref Chunk, expected Header, span Span, emit func([]byte, []byte if Digest(b) != ref.Digest { return zero, Invalid("chunk checksum/size mismatch") } - return decode(bytes.NewReader(b), expected, span, ref, emit) + return decode(&bufferReader{data: b}, expected, span, ref, emit) } +// bufferReader slices an already verified, owned file buffer. Emitted slices +// are read-only and remain valid when retained; the buffer is never pooled. +type bufferReader struct{ data []byte } + +func (r *bufferReader) Len() int { return len(r.data) } +func (r *bufferReader) Read(p []byte) (int, error) { + if len(r.data) == 0 { + return 0, io.EOF + } + n := copy(p, r.data) + r.data = r.data[n:] + return n, nil +} +func (r *bufferReader) take(n uint32) ([]byte, error) { + if uint64(n) > uint64(len(r.data)) { + return nil, Wrap(io.ErrUnexpectedEOF) + } + b := r.data[:n:n] + r.data = r.data[n:] + return b, nil +} func readN(r io.Reader, n uint32, max uint32) ([]byte, error) { if n > max { return nil, Invalid("frame exceeds limit") } + if r, ok := r.(*bufferReader); ok { + return r.take(n) + } b := make([]byte, n) _, e := io.ReadFull(r, b) return b, Wrap(e) } func readU32(r io.Reader) (uint32, error) { + if r, ok := r.(*bufferReader); ok { + b, err := r.take(4) + if err != nil { + return 0, err + } + return binary.LittleEndian.Uint32(b), nil + } var b [4]byte _, e := io.ReadFull(r, b[:]) return binary.LittleEndian.Uint32(b[:]), Wrap(e) @@ -123,7 +154,7 @@ func decode(r io.Reader, expected Header, span Span, ref Chunk, emit func([]byte if e != nil { return seen, e } - block := bytes.NewReader(b) + block := &bufferReader{data: b} for i := uint32(0); i < count; i++ { kl, e := readU32(block) if e != nil { diff --git a/pkg/snapshot/protocol/protocol_test.go b/pkg/snapshot/protocol/protocol_test.go index 234c6586ec..d7485a7fcd 100644 --- a/pkg/snapshot/protocol/protocol_test.go +++ b/pkg/snapshot/protocol/protocol_test.go @@ -83,3 +83,34 @@ func TestStateRoundTrip(t *testing.T) { require.NoError(t, json.Unmarshal(b, &out)) require.Equal(t, state, out) } + +func TestVerifiedBufferTruncationAndRetainedRows(t *testing.T) { + b, err := os.ReadFile("testdata/rust-v1.skv") + require.NoError(t, err) + expected := Header{Version: 1, Compression: "none", JobID: "golden", SnapshotID: "golden", SnapshotTS: 42, PlanDigest: "golden", RangeID: "r0", AttemptID: "a0", TableID: 1} + ref := Chunk{KVCount: 2, LogicalBytes: 12, First: []byte("a"), Last: []byte("b")} + span := Span{Start: []byte("a"), End: []byte("z")} + for i := 0; i < len(b); i++ { + _, err := decode(&bufferReader{data: b[:i]}, expected, span, ref, func([]byte, []byte) error { return nil }) + require.Error(t, err, "truncation at %d", i) + } + var keys, values [][]byte + _, err = decode(&bufferReader{data: b}, expected, span, ref, func(k, v []byte) error { keys = append(keys, k); values = append(values, v); return nil }) + require.NoError(t, err) + require.Equal(t, []byte("a"), keys[0]) + require.Equal(t, []byte("b"), keys[1]) + for _, row := range append(keys, values...) { + require.Equal(t, len(row), cap(row), "append must not overwrite the following frame") + } +} + +func TestRuntimeLimits(t *testing.T) { + var defaults *Config + require.NoError(t, defaults.ValidateRuntime()) + require.Equal(t, 4, defaults.ApplyConcurrency()) + require.EqualValues(t, 64<<20, defaults.InflightLimit()) + for _, c := range []Config{{ApplyWorkers: -1}, {ApplyWorkers: 33}, {InflightBytes: 1}, {InflightBytes: (1 << 30) + 1}} { + require.Error(t, c.ValidateRuntime()) + } + require.NoError(t, (&Config{ApplyWorkers: 16, InflightBytes: 32 << 20}).ValidateRuntime()) +} diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go index 034eea58ba..0060a9597d 100644 --- a/pkg/snapshot/protocol/types.go +++ b/pkg/snapshot/protocol/types.go @@ -117,10 +117,37 @@ type Marker struct { // Config is opt-in. The initial deployment uses one capture and a shared local // artifact directory. Provider and capture are independent modules. type Config struct { - BackupURI string `toml:"backup-uri" json:"backup-uri"` - BackupDigest string `toml:"backup-digest" json:"backup-digest"` - ProviderURL string `toml:"provider-url" json:"provider-url"` - ArtifactDir string `toml:"artifact-dir" json:"artifact-dir"` + ApplyWorkers int `toml:"apply-workers" json:"apply-workers,omitempty"` + InflightBytes int64 `toml:"inflight-bytes" json:"inflight-bytes,omitempty"` + BackupURI string `toml:"backup-uri" json:"backup-uri"` + BackupDigest string `toml:"backup-digest" json:"backup-digest"` + ProviderURL string `toml:"provider-url" json:"provider-url"` + ArtifactDir string `toml:"artifact-dir" json:"artifact-dir"` +} + +// ApplyConcurrency and InflightLimit bound capture-side work independently of +// provider export workers. The byte budget covers mounted data awaiting ACK; +// each worker additionally owns at most one bounded input chunk and batch. +func (c *Config) ApplyConcurrency() int { + if c == nil || c.ApplyWorkers == 0 { + return 4 + } + return c.ApplyWorkers +} +func (c *Config) InflightLimit() int64 { + if c == nil || c.InflightBytes == 0 { + return 64 << 20 + } + return c.InflightBytes +} +func (c *Config) ValidateRuntime() error { + if c.ApplyConcurrency() < 1 || c.ApplyConcurrency() > 32 { + return Invalid("apply-workers must be between 1 and 32") + } + if c.InflightLimit() < 32<<20 || c.InflightLimit() > 1<<30 { + return Invalid("inflight-bytes must be between 32 MiB and 1 GiB") + } + return nil } func Digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } diff --git a/scripts/generate-mock.sh b/scripts/generate-mock.sh index 5de36bc89f..ef89afae77 100755 --- a/scripts/generate-mock.sh +++ b/scripts/generate-mock.sh @@ -69,5 +69,6 @@ run_mockgen -source pkg/txnutil/gc/gc_client.go -destination pkg/txnutil/gc/gc_c run_mockgen -source pkg/redo/writer/writer.go -destination pkg/redo/writer/writer_mock.go -package writer run_mockgen -source downstreamadapter/sink/sink.go -destination downstreamadapter/sink/mock/sink_mock.go -package mock run_mockgen -destination pkg/messaging/mock/message_center_mock.go -package mock github.com/pingcap/ticdc/pkg/messaging MessageCenter +run_mockgen -source pkg/snapshot/bootstrap/interfaces.go -destination pkg/snapshot/bootstrap/interfaces_mock_test.go -package bootstrap wait_for_batch diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index d8e4f4f1bb..b565f01d8b 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -160,9 +160,22 @@ journal-not-updated boundary; status/list polls restart reconciliation. ## Contract and demo limits Snapshot metadata keys in Kafka open protocol are `snapshot_record_id`, -`snapshot_id`, `snapshot_ts`, `snapshot_schema` and `snapshot_schema_encoding`. -Schema encoding is `ticdc-table-info-base64-v1`: base64 of the existing TiCDC -`TableInfo.Marshal()` bytes, decoded with `UnmarshalJSONToTableInfo`. +`snapshot_id` and `snapshot_ts`. Full TableInfo is **not** repeated in Kafka rows +or SnapshotKV records. The immutable `schema.json` bundle is referenced by +`Spec.SchemaRef` (size + SHA-256), using the existing `TableInfo.Marshal()` bytes. +Capture verifies and caches it once per snapshot, decoded with +`UnmarshalJSONToTableInfo`. The verifier receives `-spec ` to validate +record identities against this same frozen metadata. + +Capture `[snapshot]` options `apply-workers` (default 4, range 1–32) and +`inflight-bytes` (default 64 MiB, range 32 MiB–1 GiB) are independent of Provider +`-workers`. Mounted batches share one capture-side byte budget, released only by +sink PostFlush callbacks. Each worker additionally holds at most one input chunk +(up to 64 MiB) and one batch (up to 256 rows or about 1 MiB, plus one oversized +record bounded by the 16 MiB record limit). Kafka encoding buffers and the rest +of the capture have their own memory overhead; this budget is not a total RSS +limit. Range workers join before abort or global commit. Per-row RecordIDs remain +independent of batching and concurrency. Normal incremental event keys remain unchanged. Record ID is lowercase SHA-256 of `snapshot-key-v1\0`, u32-BE snapshot-ID byte diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py index 0e86bb3e5f..039bd628ad 100644 --- a/tests/integration_tests/native_snapshot/demo.py +++ b/tests/integration_tests/native_snapshot/demo.py @@ -166,7 +166,7 @@ def get(name): raise SystemExit("changefeed did not catch up: "+str(state.get("error"))) elif args.action == "verify": output = root/(args.name+"-verification.json") - subprocess.run([str(root/"bin/snapshot-verify"), "-broker", args.broker, "-topic", args.topic, "-output", str(output)], check=True) + subprocess.run([str(root/"bin/snapshot-verify"), "-broker", args.broker, "-topic", args.topic, "-output", str(output), "-spec", http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace)["snapshot"]["spec_ref"]["uri"]], check=True) subprocess.run(["python3", str(Path(__file__).with_name("compare.py")), str(output), "--port", args.sql_port], check=True) diff --git a/tests/integration_tests/native_snapshot/verify/main.go b/tests/integration_tests/native_snapshot/verify/main.go index 670953671a..cd6fd82828 100644 --- a/tests/integration_tests/native_snapshot/verify/main.go +++ b/tests/integration_tests/native_snapshot/verify/main.go @@ -4,7 +4,6 @@ package main import ( "bytes" - "encoding/base64" "encoding/binary" "encoding/json" "flag" @@ -16,12 +15,14 @@ import ( "github.com/IBM/sarama" "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/tidb/pkg/kv" "github.com/pingcap/tidb/pkg/tablecodec" ) type key struct { + DB string `json:"scm"` TS uint64 `json:"ts"` Type int `json:"t"` Table string `json:"tbl"` @@ -71,7 +72,31 @@ func main() { topic := flag.String("topic", "", "single partition topic") out := flag.String("output", "verify.json", "result JSON") seed := flag.Int("seed", 3000, "expected unique snapshot rows") + specFile := flag.String("spec", "", "immutable snapshot spec.json (schema remains external to row messages)") flag.Parse() + specRef, err := protocol.Ref(*specFile) + if err != nil { + log.Fatal(err) + } + var spec protocol.Spec + if err := protocol.Read(specRef, &spec); err != nil { + log.Fatal(err) + } + var bundle bootstrap.SchemaBundle + if err := protocol.Read(spec.SchemaRef, &bundle); err != nil { + log.Fatal(err) + } + if bundle.SnapshotTS != spec.SnapshotTS { + log.Fatal("schema boundary mismatch") + } + tableIDs := map[string]int64{} + for _, frozen := range bundle.Tables { + ti, err := common.UnmarshalJSONToTableInfo(frozen.Data) + if err != nil { + log.Fatal(err) + } + tableIDs[ti.GetSchemaName()+"."+ti.GetTableName()] = frozen.TableID + } config := sarama.NewConfig() config.Version = sarama.V2_4_0_0 config.Consumer.Return.Errors = true @@ -162,16 +187,13 @@ func main() { log.Fatal("snapshot boundary changed") } boundary = k.TS - schema, err := base64.StdEncoding.DecodeString(k.Schema) - if err != nil { - log.Fatal(err) - } - ti, err := common.UnmarshalJSONToTableInfo(schema) - if err != nil { - log.Fatal(err) + + tableID := tableIDs[k.DB+"."+k.Table] + if k.Schema != "" || tableID == 0 || k.Snapshot != spec.SnapshotID || k.SnapshotTS != spec.SnapshotTS { + log.Fatal("snapshot metadata mismatch") } - rawKey := tablecodec.EncodeRowKeyWithHandle(ti.TableName.TableID, kv.IntHandle(id)) - if protocol.RecordID(k.Snapshot, ti.TableName.TableID, rawKey) != k.ID { + rawKey := tablecodec.EncodeRowKeyWithHandle(tableID, kv.IntHandle(id)) + if protocol.RecordID(k.Snapshot, tableID, rawKey) != k.ID { log.Fatal("record ID differs from domain hash") } if id < 1 || id > int64(*seed) || number(cols["balance"].Value) != id*10 || cols["note"].Value != fmt.Sprintf("snapshot-%d", id) || len(cols) != 3 { From d2415b8aa05565e9a125edc39177d31e4b76685d Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 16:37:55 +0800 Subject: [PATCH 08/17] snapshot: default export chunks to 64 MiB Signed-off-by: dongmen <414110582@qq.com> --- pkg/snapshot/provider/provider.go | 2 +- tests/integration_tests/native_snapshot/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/provider/provider.go index b5584cf10d..0f02c02611 100644 --- a/pkg/snapshot/provider/provider.go +++ b/pkg/snapshot/provider/provider.go @@ -316,7 +316,7 @@ func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.S return e } if v == "" { - ref, e := s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 4 << 20}) + ref, e := s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 64 << 20}) if e != nil { return e } diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index b565f01d8b..f9a5dce801 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -188,7 +188,7 @@ u32-LE JSON-footer length, footer, `SNAPEND1`. Each record has u32-LE key/value lengths, key, value. JSON byte fields are base64, counts are JSON u64. SHA-256 covers the entire stored chunk. Footer and exact length/checksum are mandatory. -This profile uses uncompressed 1 MiB blocks, 4 MiB target chunks (configurable +This profile uses uncompressed 1 MiB blocks, 64 MiB target chunks (configurable 1–64 MiB in CSE), 16 MiB record ceiling plus the selected chunk budget, 64 KiB header/footer, 4 MiB metadata and 512 MiB source file-memory quota. Metadata is bounded before full allocation. Empty ranges publish a zero-row export/receipt. From 17a5cdf24cc2f4f935424689f9b1bcb30ec3082b Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Wed, 23 Sep 2026 18:11:11 +0800 Subject: [PATCH 09/17] snapshot: allow larger bounded export plans Signed-off-by: dongmen <414110582@qq.com> --- pkg/snapshot/provider/provider.go | 4 ++-- tests/integration_tests/native_snapshot/README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/provider/provider.go index 0f02c02611..2b0808e76e 100644 --- a/pkg/snapshot/provider/provider.go +++ b/pkg/snapshot/provider/provider.go @@ -224,8 +224,8 @@ func (s *Server) run(ctx context.Context, id string) error { if e = protocol.ValidatePlan(j.Spec, plan); e != nil { return e } - if len(plan.Ranges) > 256 { - return protocol.Invalid("demo supports at most 256 ranges") + if len(plan.Ranges) > 4096 { + return protocol.Invalid("demo supports at most 4096 ranges") } if e = s.update(id, func(j *Job) error { if e := activeJob(j); e != nil { diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index f9a5dce801..48a71824e5 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -193,8 +193,8 @@ This profile uses uncompressed 1 MiB blocks, 64 MiB target chunks (configurable header/footer, 4 MiB metadata and 512 MiB source file-memory quota. Metadata is bounded before full allocation. Empty ranges publish a zero-row export/receipt. -This is not a production distributed exporter: one local Runner processes ranges -sequentially; the plan is limited to 256 ranges and 2,048 chunks per range. Local +This is not a production distributed exporter: one Provider runs a bounded pool +of local CSE processes; the plan is limited to 4,096 ranges and 2,048 chunks per range. Local flock/fsync/rename CAS requires one host and shared paths. Capture fencing uses the local manager epoch and process writer lock. Multi-capture transport, remote object CAS, Kubernetes Runner pools, compressed/encrypted chunk output, source From 25f23905b9e608d715d1d447f960918d56cfef8e Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Thu, 29 Oct 2026 01:19:14 +0800 Subject: [PATCH 10/17] Embed local CSE snapshot runner in TiCDC --- cmd/cdc/server/server.go | 12 ++ coordinator/changefeed/snapshot.go | 2 +- coordinator/changefeed/snapshot_test.go | 2 +- maintainer/snapshot.go | 12 +- pkg/config/server.go | 28 +++- pkg/snapshot/bootstrap/cleanup.go | 70 ++++++++ pkg/snapshot/bootstrap/cleanup_test.go | 29 ++++ pkg/snapshot/bootstrap/controller.go | 57 +++++-- pkg/snapshot/protocol/types.go | 5 +- pkg/snapshot/provider/client.go | 23 +++ pkg/snapshot/provider/provider.go | 150 +++++++++++++++--- pkg/snapshot/provider/provider_test.go | 65 ++++++++ .../native_snapshot/README.md | 87 ++++++++-- .../native_snapshot/compare.py | 5 +- .../integration_tests/native_snapshot/demo.py | 31 ++-- 15 files changed, 511 insertions(+), 67 deletions(-) create mode 100644 pkg/snapshot/bootstrap/cleanup.go create mode 100644 pkg/snapshot/bootstrap/cleanup_test.go diff --git a/cmd/cdc/server/server.go b/cmd/cdc/server/server.go index 5f852591bc..a324c9531e 100644 --- a/cmd/cdc/server/server.go +++ b/cmd/cdc/server/server.go @@ -76,6 +76,10 @@ func (o *options) addFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.serverConfig.LogLevel, "log-level", o.serverConfig.LogLevel, "log level (etc: debug|info|warn|error)") cmd.Flags().StringVar(&o.serverConfig.DataDir, "data-dir", o.serverConfig.DataDir, "the path to the directory used to store TiCDC-generated data") + cmd.Flags().StringVar(&o.serverConfig.SnapshotCSEBinary, "snapshot-cse-binary", o.serverConfig.SnapshotCSEBinary, "CSE binary for embedded packed-backup snapshot export") + cmd.Flags().StringVar(&o.serverConfig.SnapshotArtifactDir, "snapshot-artifact-dir", o.serverConfig.SnapshotArtifactDir, "persistent artifact directory for embedded snapshot export") + cmd.Flags().IntVar(&o.serverConfig.SnapshotExportWorkers, "snapshot-export-workers", o.serverConfig.SnapshotExportWorkers, "maximum concurrent local snapshot export processes per changefeed") + cmd.Flags().Int64Var(&o.serverConfig.SnapshotMinFreeBytes, "snapshot-min-free-bytes", o.serverConfig.SnapshotMinFreeBytes, "minimum free bytes before starting another snapshot range") cmd.Flags().StringSliceVar(&o.pdEndpoints, "pd", []string{"http://127.0.0.1:2379"}, "Set the PD endpoints to use. Use ',' to separate multiple PDs") cmd.Flags().StringVar(&o.serverConfigFilePath, "config", "", "Path of the configuration file") @@ -212,6 +216,14 @@ func (o *options) complete(command *cobra.Command) error { cfg.LogLevel = o.serverConfig.LogLevel case "data-dir": cfg.DataDir = o.serverConfig.DataDir + case "snapshot-cse-binary": + cfg.SnapshotCSEBinary = o.serverConfig.SnapshotCSEBinary + case "snapshot-artifact-dir": + cfg.SnapshotArtifactDir = o.serverConfig.SnapshotArtifactDir + case "snapshot-export-workers": + cfg.SnapshotExportWorkers = o.serverConfig.SnapshotExportWorkers + case "snapshot-min-free-bytes": + cfg.SnapshotMinFreeBytes = o.serverConfig.SnapshotMinFreeBytes case "ca": cfg.Security.CAPath = o.serverConfig.Security.CAPath case "cert": diff --git a/coordinator/changefeed/snapshot.go b/coordinator/changefeed/snapshot.go index 5352718f5d..60e28d812c 100644 --- a/coordinator/changefeed/snapshot.go +++ b/coordinator/changefeed/snapshot.go @@ -56,7 +56,7 @@ func (b *EtcdBackend) SaveSnapshot(ctx context.Context, id common.ChangeFeedID, return protocol.Invalid("cannot roll back snapshot marker") } } - if next.Marker != nil && (next.Phase != "SNAPSHOT_COMMITTED" || next.Marker.PlanDigest != next.PlanRef.Digest || next.Marker.SnapshotTS != next.SnapshotTS) { + if next.Marker != nil && (next.Phase != "SNAPSHOT_COMMITTED" || next.PlanRef.URI == "" || next.Marker.SnapshotID != next.SnapshotID || next.Marker.SnapshotTS != next.SnapshotTS) { return protocol.Invalid("marker/phase mismatch") } status.Snapshot = next diff --git a/coordinator/changefeed/snapshot_test.go b/coordinator/changefeed/snapshot_test.go index dcfb08c429..beff6cbe15 100644 --- a/coordinator/changefeed/snapshot_test.go +++ b/coordinator/changefeed/snapshot_test.go @@ -24,7 +24,7 @@ func TestCheckpointPreservesSnapshotAcrossConflict(t *testing.T) { backend := NewEtcdBackend(cdc) id := common.NewChangeFeedIDWithName("demo", common.DefaultKeyspaceName) first := &config.ChangeFeedStatus{CheckpointTs: 42, Snapshot: &protocol.State{Generation: "g", Phase: "APPLYING"}} - marker := &protocol.Marker{SnapshotTS: 42, SnapshotID: "s", PlanDigest: "p"} + marker := &protocol.Marker{SnapshotTS: 42, SnapshotID: "s"} second := &config.ChangeFeedStatus{CheckpointTs: 42, Progress: config.ProgressStopping, Snapshot: &protocol.State{Generation: "g", Phase: "SNAPSHOT_COMMITTED", Marker: marker}} gomock.InOrder(cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(first, int64(1), nil), raw.EXPECT().Txn(gomock.Any(), gomock.Len(1), gomock.Any(), gomock.Any()).Return(&clientv3.TxnResponse{}, nil), cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(second, int64(2), nil), raw.EXPECT().Txn(gomock.Any(), gomock.Len(1), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ []clientv3.Cmp, ops []clientv3.Op, _ []clientv3.Op) (*clientv3.TxnResponse, error) { var s config.ChangeFeedStatus diff --git a/maintainer/snapshot.go b/maintainer/snapshot.go index bcc8832de1..055f6181c6 100644 --- a/maintainer/snapshot.go +++ b/maintainer/snapshot.go @@ -8,6 +8,7 @@ import ( "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/logservice/schemastore" appcontext "github.com/pingcap/ticdc/pkg/common/context" + "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/node" "github.com/pingcap/ticdc/pkg/sink/kafka" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" @@ -25,6 +26,11 @@ func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb. return false } cfg := m.info.Config.Snapshot + serverCfg := config.GetGlobalServerConfig() + artifactDir := cfg.ArtifactDir + if cfg.ProviderURL == "" { + artifactDir = serverCfg.SnapshotArtifactDir + } if err := cfg.ValidateRuntime(); err != nil { m.handleError(err) return false @@ -34,8 +40,8 @@ func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb. m.handleError(protocol.Wrap(err)) return false } - if len(responses) != 1 || responses[m.selfNode.ID] == nil || uri.Scheme != "kafka" || uri.Query().Get("protocol") != "open-protocol" || cfg.ArtifactDir == "" || cfg.ProviderURL == "" || cfg.BackupURI == "" || len(cfg.BackupDigest) != 64 || m.enableRedo || len(m.info.Config.Filter.EventFilters) > 0 { - m.handleError(protocol.Invalid("snapshot demo requires single capture, kafka open-protocol, frozen backup digest, artifact dir, Provider and no redo/event filters")) + if len(responses) != 1 || responses[m.selfNode.ID] == nil || uri.Scheme != "kafka" || uri.Query().Get("protocol") != "open-protocol" || artifactDir == "" || (cfg.ProviderURL == "" && serverCfg.SnapshotCSEBinary == "") || cfg.BackupURI == "" || len(cfg.BackupDigest) != 64 || m.enableRedo || len(m.info.Config.Filter.EventFilters) > 0 { + m.handleError(protocol.Invalid("snapshot requires one capture, kafka open-protocol, frozen backup digest, artifact directory, CSE binary, and no redo/event filters")) return false } options := kafka.NewOptions() @@ -57,7 +63,7 @@ func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb. m.handleError(protocol.Invalid("capture snapshot capability unavailable")) return false } - controller := bootstrap.Controller{ID: m.changefeedID, Epoch: m.info.Epoch, TS: m.info.StartTs, Keyspace: m.controller.keyspaceMeta.ID, Config: cfg, Repository: repo, Capture: capture, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { + controller := bootstrap.Controller{ID: m.changefeedID, Epoch: m.info.Epoch, TS: m.info.StartTs, Keyspace: m.controller.keyspaceMeta.ID, Config: cfg, ArtifactDir: artifactDir, CSEBinary: serverCfg.SnapshotCSEBinary, ExportWorkers: serverCfg.SnapshotExportWorkers, MinFreeBytes: serverCfg.SnapshotMinFreeBytes, Repository: repo, Capture: capture, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { bundle := bootstrap.SchemaBundle{SnapshotTS: m.info.StartTs} tables, err := m.controller.loadTables(m.info.StartTs) if err != nil { diff --git a/pkg/config/server.go b/pkg/config/server.go index e6ff878ddc..34a319958b 100644 --- a/pkg/config/server.go +++ b/pkg/config/server.go @@ -17,6 +17,7 @@ import ( "encoding/json" "fmt" "net" + "path/filepath" "regexp" "strings" "sync/atomic" @@ -102,9 +103,11 @@ var defaultServerConfig = &ServerConfig{ }, InternalErrOutput: "stderr", }, - DataDir: "", - GcTTL: 24 * 60 * 60, // 24H - TZ: "System", + DataDir: "", + SnapshotExportWorkers: 1, + SnapshotMinFreeBytes: 10 << 30, + GcTTL: 24 * 60 * 60, // 24H + TZ: "System", // Disabled by default. When enabled in next-gen mode, TiCDC uses // service safepoint v2 instead of GC barriers. EnableLegacySafePoint: false, @@ -149,6 +152,13 @@ type ServerConfig struct { DataDir string `toml:"data-dir" json:"data-dir"` + // SnapshotCSEBinary enables the embedded local CSE packed-backup exporter. + // It is a server setting, never a changefeed-provided executable path. + SnapshotCSEBinary string `toml:"snapshot-cse-binary" json:"snapshot-cse-binary"` + SnapshotArtifactDir string `toml:"snapshot-artifact-dir" json:"snapshot-artifact-dir"` + SnapshotExportWorkers int `toml:"snapshot-export-workers" json:"snapshot-export-workers"` + SnapshotMinFreeBytes int64 `toml:"snapshot-min-free-bytes" json:"snapshot-min-free-bytes"` + GcTTL int64 `toml:"gc-ttl" json:"gc-ttl"` TZ string `toml:"tz" json:"tz"` @@ -256,6 +266,18 @@ func (c *ServerConfig) Clone() *ServerConfig { // ValidateAndAdjust validates and adjusts the server configuration func (c *ServerConfig) ValidateAndAdjust() error { + if c.SnapshotExportWorkers == 0 { + c.SnapshotExportWorkers = 1 + } + if c.SnapshotExportWorkers < 1 || c.SnapshotExportWorkers > 32 { + return cerror.ErrInvalidServerOption.GenWithStack("snapshot-export-workers must be between 1 and 32") + } + if c.SnapshotMinFreeBytes < 0 { + return cerror.ErrInvalidServerOption.GenWithStack("snapshot-min-free-bytes cannot be negative") + } + if c.SnapshotCSEBinary != "" && (!filepath.IsAbs(c.SnapshotCSEBinary) || !filepath.IsAbs(c.SnapshotArtifactDir)) { + return cerror.ErrInvalidServerOption.GenWithStack("embedded snapshot requires absolute snapshot-cse-binary and snapshot-artifact-dir paths") + } if !isValidClusterID(c.ClusterID) { return cerror.ErrInvalidServerOption.GenWithStack(fmt.Sprintf("bad cluster-id"+ "please match the pattern \"^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$\", and not the list of"+ diff --git a/pkg/snapshot/bootstrap/cleanup.go b/pkg/snapshot/bootstrap/cleanup.go new file mode 100644 index 0000000000..d774de24c8 --- /dev/null +++ b/pkg/snapshot/bootstrap/cleanup.go @@ -0,0 +1,70 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package bootstrap + +import ( + "os" + "path/filepath" + "strings" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/snapshot/store" +) + +// Applied task pages are the durable permission to remove their local chunks. +// Repeating this sweep after restart closes the receipt-then-cleanup crash gap. +func cleanupAppliedChunks(root, job string, tasks store.Tasks) error { + all, err := tasks.List() + if err != nil { + return err + } + for _, task := range all { + if task.State != "APPLIED" { + continue + } + var export protocol.Export + if err := protocol.Read(task.Export, &export); err != nil { + return err + } + if err := removeExportChunks(root, job, export); err != nil { + return err + } + } + return nil +} + +func removeExportChunks(root, job string, export protocol.Export) error { + if export.JobID != job { + return protocol.Invalid("chunk cleanup job mismatch") + } + if len(export.Chunks) == 0 { + return nil + } + allowed, err := filepath.EvalSymlinks(filepath.Join(root, "br", job, "attempts")) + if err != nil { + return protocol.Wrap(err) + } + for _, chunk := range export.Chunks { + name := filepath.Base(chunk.URI) + if !filepath.IsAbs(chunk.URI) || !strings.HasPrefix(name, "chunk-") || !strings.HasSuffix(name, ".skv") { + return protocol.Invalid("invalid local chunk cleanup path") + } + parent, err := filepath.EvalSymlinks(filepath.Dir(chunk.URI)) + if os.IsNotExist(err) { + continue + } + if err != nil { + return protocol.Wrap(err) + } + rel, err := filepath.Rel(allowed, parent) + if err != nil { + return protocol.Wrap(err) + } + if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return protocol.Invalid("chunk cleanup path outside job attempts") + } + if err := os.Remove(chunk.URI); err != nil && !os.IsNotExist(err) { + return protocol.Wrap(err) + } + } + return nil +} diff --git a/pkg/snapshot/bootstrap/cleanup_test.go b/pkg/snapshot/bootstrap/cleanup_test.go new file mode 100644 index 0000000000..ff33c6f9a0 --- /dev/null +++ b/pkg/snapshot/bootstrap/cleanup_test.go @@ -0,0 +1,29 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package bootstrap + +import ( + "os" + "path/filepath" + "testing" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestRemoveAppliedChunksOnlyInsideJobAttempts(t *testing.T) { + root := t.TempDir() + attempt := filepath.Join(root, "br", "job", "attempts", "a1") + require.NoError(t, os.MkdirAll(attempt, 0o700)) + chunk := filepath.Join(attempt, "chunk-000000.skv") + require.NoError(t, os.WriteFile(chunk, []byte("data"), 0o600)) + export := protocol.Export{JobID: "job", Chunks: []protocol.Chunk{{ObjectRef: protocol.ObjectRef{URI: chunk}}}} + require.NoError(t, removeExportChunks(root, "job", export)) + require.NoFileExists(t, chunk) + require.NoError(t, removeExportChunks(root, "job", export)) + + outside := filepath.Join(t.TempDir(), "chunk-000000.skv") + require.NoError(t, os.WriteFile(outside, []byte("keep"), 0o600)) + export.Chunks[0].URI = outside + require.ErrorContains(t, removeExportChunks(root, "job", export), "outside job attempts") + require.FileExists(t, outside) +} diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go index 17663ec3ac..d04f99f7ba 100644 --- a/pkg/snapshot/bootstrap/controller.go +++ b/pkg/snapshot/bootstrap/controller.go @@ -18,21 +18,29 @@ import ( ) type Controller struct { - ID common.ChangeFeedID - Epoch uint64 - TS uint64 - Keyspace uint32 - Config *protocol.Config - Repository Repository - Capture Capture - Freeze func() (SchemaBundle, []protocol.Span, error) + ID common.ChangeFeedID + Epoch uint64 + TS uint64 + Keyspace uint32 + Config *protocol.Config + ArtifactDir string + CSEBinary string + ExportWorkers int + MinFreeBytes int64 + Repository Repository + Capture Capture + Freeze func() (SchemaBundle, []protocol.Span, error) } func (c Controller) Run(ctx context.Context) (result error) { if err := c.Config.ValidateRuntime(); err != nil { return err } - objects := store.Local{Root: c.Config.ArtifactDir} + artifactDir := c.ArtifactDir + if artifactDir == "" { + artifactDir = c.Config.ArtifactDir + } + objects := store.Local{Root: artifactDir} dir := filepath.Join(objects.Root, "cdc", c.ID.ID().String()) if err := os.MkdirAll(dir, 0o700); err != nil { return protocol.Wrap(err) @@ -91,7 +99,17 @@ func (c Controller) Run(ctx context.Context) (result error) { if err = protocol.Read(state.SpecRef, &spec); err != nil { return err } - client := provider.Client{URL: c.Config.ProviderURL} + var client provider.Caller = provider.Client{URL: c.Config.ProviderURL} + if c.Config.ProviderURL == "" { + if c.CSEBinary == "" { + return protocol.Invalid("embedded snapshot export requires a configured CSE binary") + } + local := provider.New(artifactDir, c.CSEBinary) + local.Workers = c.ExportWorkers + local.MinFreeBytes = c.MinFreeBytes + defer local.Close() + client = provider.LocalClient{Server: local} + } var job provider.Job if err = client.Call(ctx, "ensure", provider.Request{SpecRef: state.SpecRef}, &job); err != nil { return err @@ -136,6 +154,11 @@ func (c Controller) Run(ctx context.Context) (result error) { if err = tasks.Init(); err != nil { return err } + if c.Config.ProviderURL == "" { + if err = cleanupAppliedChunks(artifactDir, spec.JobID, tasks); err != nil { + return err + } + } complete := false for { all, err := tasks.List() @@ -222,7 +245,7 @@ func (c Controller) Run(ctx context.Context) (result error) { return protocol.Invalid("incomplete exact range receipts") } } - state.Marker = &protocol.Marker{SnapshotTS: spec.SnapshotTS, SnapshotID: spec.SnapshotID, PlanDigest: state.PlanRef.Digest, OutputFence: "single-capture-all-broker-acks"} + state.Marker = &protocol.Marker{SnapshotTS: spec.SnapshotTS, SnapshotID: spec.SnapshotID, OutputFence: "single-capture-all-broker-acks"} state.Phase = "SNAPSHOT_COMMITTED" return save() } @@ -279,9 +302,21 @@ func (c Controller) applyReady(ctx context.Context, tasks store.Tasks, spec prot if err != nil { return err } + if c.Config.ProviderURL == "" { + if err = removeExportChunks(c.artifactDir(), spec.JobID, ex); err != nil { + return err + } + } } return nil }) } return group.Wait() } + +func (c Controller) artifactDir() string { + if c.ArtifactDir != "" { + return c.ArtifactDir + } + return c.Config.ArtifactDir +} diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go index 0060a9597d..95ed21e531 100644 --- a/pkg/snapshot/protocol/types.go +++ b/pkg/snapshot/protocol/types.go @@ -110,12 +110,11 @@ type State struct { type Marker struct { SnapshotTS uint64 `json:"snapshot_ts"` SnapshotID string `json:"snapshot_id"` - PlanDigest string `json:"plan_digest"` OutputFence string `json:"output_fence"` } -// Config is opt-in. The initial deployment uses one capture and a shared local -// artifact directory. Provider and capture are independent modules. +// Config is opt-in. An empty ProviderURL selects the embedded local runner; +// ArtifactDir and ProviderURL remain for the standalone demo adapter. type Config struct { ApplyWorkers int `toml:"apply-workers" json:"apply-workers,omitempty"` InflightBytes int64 `toml:"inflight-bytes" json:"inflight-bytes,omitempty"` diff --git a/pkg/snapshot/provider/client.go b/pkg/snapshot/provider/client.go index bcf16fa0ff..8859b4d8bf 100644 --- a/pkg/snapshot/provider/client.go +++ b/pkg/snapshot/provider/client.go @@ -14,6 +14,29 @@ import ( type Client struct{ URL string } +// Caller keeps the snapshot bootstrap independent of whether the Provider is +// reached over HTTP or embedded in the TiCDC process. +type Caller interface { + Call(context.Context, string, Request, any) error +} + +type LocalClient struct{ Server *Server } + +func (c LocalClient) Call(ctx context.Context, method string, req Request, out any) error { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + result, err := c.Server.invoke(method, req) + if err != nil { + return err + } + b, err := json.Marshal(result) + if err != nil { + return protocol.Wrap(err) + } + return protocol.Wrap(json.Unmarshal(b, out)) +} + func (c Client) Call(ctx context.Context, method string, req Request, out any) error { b, e := json.Marshal(req) if e != nil { diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/provider/provider.go index 2b0808e76e..182d6dd1de 100644 --- a/pkg/snapshot/provider/provider.go +++ b/pkg/snapshot/provider/provider.go @@ -46,11 +46,15 @@ type Request struct { type Server struct { Objects store.Local Binary string + // MinFreeBytes pauses new ranges while the artifact filesystem is low on space. + MinFreeBytes int64 // Workers bounds concurrent local materialize-range processes per job. // Configure before serving requests; values below one retain serial execution. Workers int mu sync.Mutex running map[string]context.CancelFunc + closed bool + workers sync.WaitGroup } func New(root, binary string) *Server { @@ -122,14 +126,24 @@ func (s *Server) Ensure(ref protocol.ObjectRef) (Job, error) { func (s *Server) start(id string) { s.mu.Lock() defer s.mu.Unlock() + if s.closed { + return + } if _, ok := s.running[id]; ok { return } ctx, cancel := context.WithCancel(context.Background()) s.running[id] = cancel + s.workers.Add(1) go func() { - defer func() { cancel(); s.mu.Lock(); delete(s.running, id); s.mu.Unlock() }() - if e := s.run(ctx, id); e != nil { + defer func() { + cancel() + s.mu.Lock() + delete(s.running, id) + s.mu.Unlock() + s.workers.Done() + }() + if e := s.run(ctx, id); e != nil && ctx.Err() == nil { _ = s.update(id, func(j *Job) error { if j.Phase != "CANCELED" { j.Phase = "FAILED" @@ -141,6 +155,17 @@ func (s *Server) start(id string) { }() } +// Close stops all local export processes and waits for their work to finish. +func (s *Server) Close() { + s.mu.Lock() + s.closed = true + for _, cancel := range s.running { + cancel() + } + s.mu.Unlock() + s.workers.Wait() +} + func (s *Server) batch(ctx context.Context, id, command string, task map[string]any) (protocol.ObjectRef, error) { parent := filepath.Join(s.Objects.Root, "br", id, "attempts") if e := os.MkdirAll(parent, 0o700); e != nil { @@ -213,7 +238,9 @@ func (s *Server) run(ctx context.Context, id string) error { }); e != nil { return e } - ref, e := s.batch(ctx, id, "plan", map[string]any{"spec": j.Spec}) + ref, e := retryBatch(ctx, func() (protocol.ObjectRef, error) { + return s.batch(ctx, id, "plan", map[string]any{"spec": j.Spec}) + }) if e != nil { return e } @@ -316,7 +343,12 @@ func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.S return e } if v == "" { - ref, e := s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 64 << 20}) + if e = s.waitForSpace(ctx, id); e != nil { + return e + } + ref, e := retryBatch(ctx, func() (protocol.ObjectRef, error) { + return s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 64 << 20}) + }) if e != nil { return e } @@ -371,20 +403,82 @@ func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.S return nil } -func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - if r.Method != "POST" { - http.Error(w, "POST required", 405) - return +// A failed CSE process gets a fresh attempt directory. Published range winners +// are never retried; callers validate each successful candidate before publish. +func retryBatch(ctx context.Context, run func() (protocol.ObjectRef, error)) (protocol.ObjectRef, error) { + var err error + for attempt := 0; attempt < 3; attempt++ { + if e := ctx.Err(); e != nil { + return protocol.ObjectRef{}, protocol.Wrap(e) + } + var ref protocol.ObjectRef + ref, err = run() + if err == nil { + return ref, nil + } + if attempt == 2 { + break + } + timer := time.NewTimer(time.Duration(attempt+1) * time.Second) + select { + case <-ctx.Done(): + timer.Stop() + return protocol.ObjectRef{}, protocol.Wrap(ctx.Err()) + case <-timer.C: + } } - var req Request - if e := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); e != nil { - http.Error(w, "invalid request", 400) - return + return protocol.ObjectRef{}, err +} + +func (s *Server) waitForSpace(ctx context.Context, id string) error { + if s.MinFreeBytes == 0 { + return nil } + blocked := false + for { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + var stat syscall.Statfs_t + if err := syscall.Statfs(s.Objects.Root, &stat); err != nil { + return protocol.Wrap(err) + } + if int64(stat.Bavail)*int64(stat.Bsize) >= s.MinFreeBytes { + if blocked { + return s.update(id, func(j *Job) error { + if err := activeJob(j); err != nil { + return err + } + j.Phase = "MATERIALIZING" + return nil + }) + } + return nil + } + if !blocked { + if err := s.update(id, func(j *Job) error { + if err := activeJob(j); err != nil { + return err + } + j.Phase = "BLOCKED_SPACE" + return nil + }); err != nil { + return err + } + blocked = true + } + select { + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + case <-time.After(time.Second): + } + } +} + +func (s *Server) invoke(method string, req Request) (any, error) { var out any var err error - if r.URL.Path == "/ensure" { + if method == "ensure" { out, err = s.Ensure(req.SpecRef) } else if !validID(req.JobID) { err = protocol.Invalid("invalid job ID") @@ -398,13 +492,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err == nil { // A Provider can restart between CDC polls without losing an HTTP // request. Reconcile durable work even when Ensure is not repeated. - if (r.URL.Path == "/status" || r.URL.Path == "/list") && j.Phase != "SOURCE_COMPLETE" && j.Phase != "FAILED" && j.Phase != "CANCELED" { + if (method == "status" || method == "list") && j.Phase != "SOURCE_COMPLETE" && j.Phase != "FAILED" && j.Phase != "CANCELED" { s.start(req.JobID) } - switch r.URL.Path { - case "/status": + switch method { + case "status": out = j - case "/list": + case "list": var offset int if req.Cursor != "" { b, e := base64.RawURLEncoding.DecodeString(req.Cursor) @@ -434,7 +528,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { end := min(offset+limit, len(j.Exports)) cursor := base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s:%d", req.JobID, j.PlanRef.Digest, end))) out = Page{j.Exports[offset:end], cursor, j.Phase == "SOURCE_COMPLETE" && end == len(j.Exports)} - case "/cancel": + case "cancel": err = s.update(req.JobID, func(j *Job) error { j.Phase = "CANCELED"; return nil }) s.mu.Lock() if cancel := s.running[req.JobID]; cancel != nil { @@ -443,11 +537,25 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mu.Unlock() out = map[string]bool{"canceled": true} default: - http.NotFound(w, r) - return + err = protocol.Invalid("unknown provider method") } } } + return out, err +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method != "POST" { + http.Error(w, "POST required", 405) + return + } + var req Request + if e := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); e != nil { + http.Error(w, "invalid request", 400) + return + } + out, err := s.invoke(strings.TrimPrefix(r.URL.Path, "/"), req) if err != nil { http.Error(w, err.Error(), 400) return diff --git a/pkg/snapshot/provider/provider_test.go b/pkg/snapshot/provider/provider_test.go index 7de96ed215..16ebe4b312 100644 --- a/pkg/snapshot/provider/provider_test.go +++ b/pkg/snapshot/provider/provider_test.go @@ -4,6 +4,8 @@ package provider import ( "context" "net/http/httptest" + "os" + "path/filepath" "sync" "sync/atomic" "testing" @@ -46,6 +48,8 @@ func TestPublishedExportRecoveredAndCursorFinalTail(t *testing.T) { require.NoError(t, client.Call(context.Background(), "list", Request{JobID: "job", Limit: 1, Cursor: first}, &page)) require.True(t, page.Complete) require.Len(t, page.Exports, 1) + require.NoError(t, (LocalClient{Server: s}).Call(context.Background(), "list", Request{JobID: "job", Limit: 1, Cursor: first}, &page)) + require.True(t, page.Complete) var job Job require.NoError(t, client.Call(context.Background(), "ensure", Request{SpecRef: specRef}, &job)) require.Equal(t, "SOURCE_COMPLETE", job.Phase) @@ -55,6 +59,67 @@ func TestPublishedExportRecoveredAndCursorFinalTail(t *testing.T) { require.Error(t, client.Call(context.Background(), "ensure", Request{SpecRef: other}, &job)) } +func TestEmbeddedCloseStopsExportWithoutFailingJob(t *testing.T) { + root := t.TempDir() + marker := filepath.Join(root, "started") + t.Setenv("SNAPSHOT_TEST_MARKER", marker) + binary := filepath.Join(root, "cse-ctl") + require.NoError(t, os.WriteFile(binary, []byte("#!/bin/sh\nprintf started > \"$SNAPSHOT_TEST_MARKER\"\nexec sleep 30\n"), 0o700)) + s := New(root, binary) + spec := protocol.Spec{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, SelectedSpans: []protocol.Span{{TableID: 1, Start: []byte("a"), End: []byte("z")}}} + ref, err := s.Objects.Put("spec", spec) + require.NoError(t, err) + var job Job + require.NoError(t, (LocalClient{Server: s}).Call(context.Background(), "ensure", Request{SpecRef: ref}, &job)) + require.Eventually(t, func() bool { + _, err := os.Stat(marker) + return err == nil + }, 5*time.Second, 10*time.Millisecond) + s.Close() + _, err = s.Objects.Read(key("job"), &job) + require.NoError(t, err) + require.Equal(t, "PLANNING", job.Phase) +} + +func TestLocalExportPausesWhenArtifactDiskIsLow(t *testing.T) { + s := New(t.TempDir(), "unused") + s.MinFreeBytes = 1 << 62 + _, err := s.Objects.Put(key("job"), Job{Phase: "MATERIALIZING"}) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + require.Error(t, s.waitForSpace(ctx, "job")) + var job Job + _, err = s.Objects.Read(key("job"), &job) + require.NoError(t, err) + require.Equal(t, "BLOCKED_SPACE", job.Phase) +} + +func TestRetryBatchUsesFreshAttemptsAndStopsOnCancellation(t *testing.T) { + attempts := 0 + want := protocol.ObjectRef{URI: "candidate.json"} + got, err := retryBatch(context.Background(), func() (protocol.ObjectRef, error) { + attempts++ + if attempts < 3 { + return protocol.ObjectRef{}, protocol.Invalid("temporary CSE failure") + } + return want, nil + }) + require.NoError(t, err) + require.Equal(t, want, got) + require.Equal(t, 3, attempts) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + attempts = 0 + _, err = retryBatch(ctx, func() (protocol.ObjectRef, error) { + attempts++ + return protocol.ObjectRef{}, nil + }) + require.ErrorIs(t, err, context.Canceled) + require.Zero(t, attempts) +} + func TestMaterializeRangesBoundedAndComplete(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index 48a71824e5..707be7a841 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -6,13 +6,73 @@ It uses one TiCDC capture, Kafka open protocol, and a shared local artifact directory. Snapshot rows are mounted with the schema at `B` and enter the same capture-owned Kafka sink as incremental rows. +## Embedded local profile (October 2026) + +The default deployment for the October design runs the export controller inside +TiCDC. No `snapshot-provider` process or Provider HTTP endpoint is needed. +`pkg/snapshot/provider` is the local CSE Runner; the standalone HTTP adapter +below remains for the earlier demo. + +The capture administrator sets these **server** settings, not the changefeed: + +```toml +newarch = true +snapshot-cse-binary = "/opt/ticdc/bin/cse-snapshot-wrapper" +snapshot-artifact-dir = "/var/lib/ticdc/snapshot-artifacts" +snapshot-export-workers = 16 +snapshot-min-free-bytes = 10737418240 +``` + +The binary and artifact paths must be absolute. Place the artifact directory on +a persistent volume accessible after a restart on the same node. The capture +image must include a CSE CLI version matching the packed-backup format; the +capture's object-store identity needs read access to the selected backup. The +server controls the CLI path, so a changefeed cannot execute an arbitrary +program. `snapshot-export-workers` is limited to 1–32; the free-space check +pauses new ranges when the artifact filesystem has less than the configured +available space. Applied chunks are deleted only after their broker-ACK receipt +is durable. Keep enough volume headroom for already running ranges. + +For the large packed backup used in the performance test, the fixed wrapper +execs the pinned `cse-ctl` with `--file-memory-limit-mib 4096`; the CSE +default of 512 MiB failed on one large packed shard. This is an image/server +setting, never a changefeed setting. Size the Pod memory limit for the number +of concurrent CSE processes and observe their actual RSS. In this lab, the +wrapper and capture receive `DFS_S3_KEY_ID` and `DFS_S3_SECRET_KEY` from the +server environment; Cloud should inject scoped credentials from its secret +mechanism rather than embedding them in changefeed configuration. + +A changefeed uses the existing create API/CLI with `[snapshot]` containing +`backup-uri`, `backup-digest`, `apply-workers`, and `inflight-bytes`; an +empty `provider-url` selects the embedded Runner. The selected tables remain +in `[filter]`. This first profile requires one capture and Kafka open protocol. +The plan, range winners, receipts, and final marker remain on the volume and +within the normal changefeed status. An exported range does not release the +incremental barrier: only all durable apply receipts and the final marker do. + +For TiDB Cloud, package the version-matched `cdc` and `cse-ctl` in the capture +image, mount a dedicated persistent volume at the artifact path, grant read +access to the packed backup, and apply the server settings above. The Cloud +control plane then creates one changefeed with the backup URI/digest and table +filter; it does not schedule each range. Pin the active snapshot to the capture +that can access its volume. A lost node/volume is an explicit failed or blocked +snapshot, not an automatic cross-node handoff. Shared S3 artifacts and +distributed task ownership are a later stage. + +Build TiCDC with a real semantic release version in ldflags. A bare `go build` +reports `Version: None` and its CLI rejects changefeed creation. For example: + +```sh +go build -tags=nextgen -ldflags "-X github.com/pingcap/ticdc/pkg/version.ReleaseVersion=v8.5.4 -X github.com/pingcap/ticdc/pkg/version.GitHash=$(git rev-parse HEAD) -X github.com/pingcap/tiflow/pkg/version.ReleaseVersion=v8.5.4" -o bin/cdc ./cmd/cdc +``` + ## Modules | Module | Responsibility | | --- | --- | | CSE `cse-ctl snapshot` | Plan physical ranges and scan the immutable backup into bounded SnapshotKV chunks; no row decoding or sink | | `pkg/snapshot/protocol` | Versioned artifacts, exact coverage checks, chunk decoder, stable row identity | -| `pkg/snapshot/provider`, `cmd/snapshot-provider` | Independent BR controller/Runner; launch CSE, publish one immutable RangeExport winner, reconcile publication gaps, serve cursor discovery | +| `pkg/snapshot/provider` | Embedded local BR controller/Runner; launch CSE, publish one immutable RangeExport winner, reconcile publication gaps, serve cursor discovery; `cmd/snapshot-provider` remains an optional HTTP adapter for the earlier demo | | `pkg/snapshot/store` | Single-host durable file CAS, immutable objects and paged range tasks | | `pkg/snapshot/bootstrap` | Generation, schema freeze, discovery, assignment, receipt and finalization controller | | `coordinator/changefeed` | Persist the optional snapshot child **inside the existing ChangeFeedStatus key**, with status/info revision and owner-epoch checks | @@ -25,7 +85,7 @@ objects are immutable; attempts never overwrite a winner. The final `SNAPSHOT_COMMITTED` phase and global marker are one status CAS transaction. Normal checkpoint, pause and epoch updates preserve the snapshot child. -## Build +## Legacy standalone demo build Use the `codex/snapshot-e2e-demo` worktree in each repository. The CSE worktree is based on packed-reader PR #5709 at `ce471b0d203d3e5d3800355e1324a7ed12aa25de`; @@ -45,7 +105,7 @@ cargo build -p cse-ctl cp "${CARGO_TARGET_DIR:-target}/debug/cse-ctl" "$RUN/bin/cse-ctl" ``` -## Run on 10.2.15.7 +## Legacy standalone installation on 10.2.15.7 The installed run is `/data/nvme0n1/cse-snapshot-demo-20260921`: @@ -76,21 +136,20 @@ python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" curl -s 'http://127.0.0.1:18300/api/v2/changefeeds/native-snapshot-demo?keyspace=snap_demo_0921' ``` -To prepare another fixture, use a **new run directory**, copy/build its binaries, -and stop the old demo processes before reusing the same service ports. Removing -old demo changefeeds or choosing a fresh keyspace avoids feeding fixture resets -into prior validation topics. `--reset-fixture` explicitly drops only the -`snapshot_demo` database. It does not rebuild the cluster. +To prepare another embedded fixture, use a **new run directory**, copy/build its +binaries, and choose a new capture port, cluster ID, feed ID and Kafka topic. +`--reset-fixture` explicitly drops only the chosen database, not the cluster. ```sh -python3 tests/integration_tests/native_snapshot/demo.py stop --root "$OLD_RUN" # A Python environment with boto3 is needed only for prepare; credentials are # read from the existing CSE config and never put in the manifest or sink URI. -python3 tests/integration_tests/native_snapshot/demo.py prepare --root "$RUN" --reset-fixture -python3 tests/integration_tests/native_snapshot/demo.py start --root "$RUN" --cluster-id unique-demo-cluster --provider-workers 1 -python3 tests/integration_tests/native_snapshot/demo.py create --root "$RUN" --name unique-demo-feed --topic unique-demo-topic -python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" --name unique-demo-feed -python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" --name unique-demo-feed --topic unique-demo-topic +export CSE=/opt/ticdc/bin/cse-ctl ARTIFACT=/var/lib/ticdc/snapshot-artifacts +export SERVER=http://127.0.0.1:18395 ADDR=10.2.15.7:18395 +python3 tests/integration_tests/native_snapshot/demo.py prepare --root "$RUN" --artifact-root "$ARTIFACT" --embedded-provider --cse-binary "$CSE" --database unique_demo --reset-fixture +python3 tests/integration_tests/native_snapshot/demo.py start --root "$RUN" --artifact-root "$ARTIFACT" --embedded-provider --cse-binary "$CSE" --cluster-id unique-demo-cluster --provider-workers 1 --server "$SERVER" --advertise-addr "$ADDR" +python3 tests/integration_tests/native_snapshot/demo.py create --root "$RUN" --embedded-provider --name unique-demo-feed --topic unique-demo-topic --server "$SERVER" +python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" --name unique-demo-feed --server "$SERVER" +python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" --name unique-demo-feed --topic unique-demo-topic --server "$SERVER" --database unique_demo ``` Preparation writes 3,000 accounts and an empty table, takes a lightweight backup, diff --git a/tests/integration_tests/native_snapshot/compare.py b/tests/integration_tests/native_snapshot/compare.py index 0576b19107..717487cd91 100644 --- a/tests/integration_tests/native_snapshot/compare.py +++ b/tests/integration_tests/native_snapshot/compare.py @@ -9,9 +9,12 @@ parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", default="4400") parser.add_argument("--user", default="root") +parser.add_argument("--database", default="snapshot_demo") args = parser.parse_args() +if not args.database.replace("_", "").isalnum(): + raise SystemExit("invalid database") result = json.load(open(args.result)) -sql = "SELECT JSON_OBJECT('id',id,'balance',balance,'note',note,'revision',revision) FROM snapshot_demo.accounts ORDER BY id" +sql = "SELECT JSON_OBJECT('id',id,'balance',balance,'note',note,'revision',revision) FROM "+args.database+".accounts ORDER BY id" data = subprocess.check_output(["mysql", "--batch", "--raw", "--skip-column-names", "-h"+args.host, "-P"+args.port, "-u"+args.user, "-e", sql], text=True) expected = {str(row["id"]): row for row in map(json.loads, data.splitlines())} assert result["final_rows"] == expected, "Kafka replay differs from SQL rows" diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py index 039bd628ad..3f669c6ee3 100644 --- a/tests/integration_tests/native_snapshot/demo.py +++ b/tests/integration_tests/native_snapshot/demo.py @@ -17,13 +17,16 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=["prepare", "start", "stop", "create", "wait", "verify"]) parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--artifact-root", type=Path, help="persistent snapshot artifact directory") parser.add_argument("--keyspace", default="snap_demo_0921") + parser.add_argument("--database", default="snapshot_demo") parser.add_argument("--pd", default="http://127.0.0.1:2379") parser.add_argument("--sql-port", default="4400") parser.add_argument("--broker", default="10.2.15.7:9092") parser.add_argument("--server", default="http://127.0.0.1:18300") parser.add_argument("--provider-workers", type=int, default=1) parser.add_argument("--provider", default="http://127.0.0.1:18400") + parser.add_argument("--embedded-provider", action="store_true", help="run the CSE export controller inside TiCDC") parser.add_argument("--worker", default="http://127.0.0.1:39000") parser.add_argument("--name", default="native-snapshot-demo") parser.add_argument("--topic", default="native-snapshot-demo-20260921") @@ -33,7 +36,10 @@ def main(): parser.add_argument("--advertise-addr", default="10.2.15.7:18300") parser.add_argument("--reset-fixture", action="store_true", help="drop only snapshot_demo before seeding") args = parser.parse_args() + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", args.database): + raise SystemExit("database must be a simple SQL identifier") root = args.root.resolve() + artifact_root = args.artifact_root.resolve() if args.artifact_root else root / "artifacts" root.mkdir(parents=True, exist_ok=True) (root / "logs").mkdir(exist_ok=True) @@ -60,11 +66,11 @@ def get(name): if len(args.keyspace) > 20: raise SystemExit("TiCDC keyspace names must be at most 20 characters") if args.reset_fixture: - sql("DROP DATABASE IF EXISTS snapshot_demo") - sql('CREATE DATABASE snapshot_demo; CREATE TABLE snapshot_demo.accounts(id BIGINT PRIMARY KEY,balance BIGINT NOT NULL,note VARCHAR(100)); CREATE TABLE snapshot_demo.empty_table(id INT PRIMARY KEY); SET GLOBAL tidb_gc_life_time="24h";') + sql("DROP DATABASE IF EXISTS " + args.database) + sql('CREATE DATABASE '+args.database+'; CREATE TABLE '+args.database+'.accounts(id BIGINT PRIMARY KEY,balance BIGINT NOT NULL,note VARCHAR(100)); CREATE TABLE '+args.database+'.empty_table(id INT PRIMARY KEY); SET GLOBAL tidb_gc_life_time="24h";') for start in range(1, 3001, 500): values = ",".join("(%d,%d,'snapshot-%d')" % (i, i*10, i) for i in range(start, start+500)) - sql("INSERT INTO snapshot_demo.accounts VALUES " + values) + sql("INSERT INTO "+args.database+".accounts VALUES " + values) backup = http(args.worker+"/api/v1/x/cluster/lightweight_backup", {}) write("backup.json", backup) with (root / "logs/pack.log").open("w") as log: @@ -81,12 +87,16 @@ def get(name): keyspace = http(args.pd+"/pd/api/v2/keyspaces/"+args.keyspace) manifest = {"snapshot_ts": ts, "keyspace_id": keyspace["id"], "backup_uri": "s3://"+path+"?endpoint="+config("s3-endpoint")+"®ion=local", "backup_digest": hashlib.sha256(data).hexdigest()} write("manifest.json", manifest) - sql("USE snapshot_demo; UPDATE accounts SET balance=99999,note='updated-after-B' WHERE id=1; DELETE FROM accounts WHERE id=2; INSERT INTO accounts VALUES(3001,30010,'inserted-after-B'); ALTER TABLE accounts ADD COLUMN revision INT DEFAULT 0; INSERT INTO accounts VALUES(3002,30020,'after-DDL',1);") + sql("USE "+args.database+"; UPDATE accounts SET balance=99999,note='updated-after-B' WHERE id=1; DELETE FROM accounts WHERE id=2; INSERT INTO accounts VALUES(3001,30010,'inserted-after-B'); ALTER TABLE accounts ADD COLUMN revision INT DEFAULT 0; INSERT INTO accounts VALUES(3002,30020,'after-DDL',1);") # An SQL snapshot TSO taken after all fixture commits bounds the wait. target = int(sql("BEGIN; SELECT @@tidb_current_ts; COMMIT;").strip()) write("target.json", {"checkpoint_ts": target}) - config_text = '[filter]\nrules=["snapshot_demo.*"]\n[snapshot]\n' - for k, v in {"backup-uri": manifest["backup_uri"], "backup-digest": manifest["backup_digest"], "provider-url": args.provider, "artifact-dir": str(root/"artifacts")}.items(): + config_text = '[filter]\nrules=['+json.dumps(args.database+".*")+']\n[snapshot]\n' + snapshot_config = {"backup-uri": manifest["backup_uri"], "backup-digest": manifest["backup_digest"]} + if not args.embedded_provider: + snapshot_config["provider-url"] = args.provider + snapshot_config["artifact-dir"] = str(artifact_root) + for k, v in snapshot_config.items(): config_text += k+"="+json.dumps(v)+"\n" (root / "changefeed.toml").write_text(config_text) print(json.dumps({"snapshot_ts": ts, "keyspace_id": keyspace["id"], "target_ts": target})) @@ -97,15 +107,18 @@ def get(name): env.update(DFS_S3_KEY_ID=config("s3-key-id"), DFS_S3_SECRET_KEY=config("s3-secret-key")) from urllib.parse import urlsplit commands = { - "provider": [str(root/"bin/snapshot-provider"), "-root", str(root/"artifacts"), "-cse-binary", args.cse_binary, "-listen", urlsplit(args.provider).netloc, "-workers", str(args.provider_workers)], + "provider": [str(root/"bin/snapshot-provider"), "-root", str(artifact_root), "-cse-binary", args.cse_binary, "-listen", urlsplit(args.provider).netloc, "-workers", str(args.provider_workers)], "cdc": [str(root/"bin/cdc"), "server", "--pd="+args.pd, "--addr=0.0.0.0:"+str(urlsplit(args.server).port), "--advertise-addr="+args.advertise_addr, "--cluster-id="+args.cluster_id, "--data-dir="+str(root/"cdc-data"), "--log-file="+str(root/"logs/cdc.log"), "--config="+str(root/"cdc.toml")], } + if args.embedded_provider: + commands.pop("provider") + commands["cdc"].extend(["--snapshot-cse-binary="+args.cse_binary, "--snapshot-artifact-dir="+str(artifact_root), "--snapshot-export-workers="+str(args.provider_workers)]) for name, command in commands.items(): pidfile = root/(name+".pid") if pidfile.exists() and Path("/proc/"+pidfile.read_text()+"/cmdline").exists(): raise SystemExit(name+" PID still exists; stop before starting") with (root/("logs/"+name+"-stdout.log")).open("a") as log: - proc = subprocess.Popen(command, env=env if name=="provider" else None, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) pidfile.write_text(str(proc.pid)) print(name, proc.pid) for _ in range(300): @@ -167,7 +180,7 @@ def get(name): elif args.action == "verify": output = root/(args.name+"-verification.json") subprocess.run([str(root/"bin/snapshot-verify"), "-broker", args.broker, "-topic", args.topic, "-output", str(output), "-spec", http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace)["snapshot"]["spec_ref"]["uri"]], check=True) - subprocess.run(["python3", str(Path(__file__).with_name("compare.py")), str(output), "--port", args.sql_port], check=True) + subprocess.run(["python3", str(Path(__file__).with_name("compare.py")), str(output), "--port", args.sql_port, "--database", args.database], check=True) if __name__ == "__main__": From f74c0708e96d04c6f4526c70d8298a3cdd647c8b Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Thu, 29 Oct 2026 09:25:06 +0800 Subject: [PATCH 11/17] snapshot: adapt schema freeze to context-aware APIs --- maintainer/snapshot.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/maintainer/snapshot.go b/maintainer/snapshot.go index 055f6181c6..045ab5c09c 100644 --- a/maintainer/snapshot.go +++ b/maintainer/snapshot.go @@ -9,10 +9,12 @@ import ( "github.com/pingcap/ticdc/logservice/schemastore" appcontext "github.com/pingcap/ticdc/pkg/common/context" "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/filter" "github.com/pingcap/ticdc/pkg/node" "github.com/pingcap/ticdc/pkg/sink/kafka" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/tidb/pkg/tablecodec" ) @@ -63,22 +65,27 @@ func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb. m.handleError(protocol.Invalid("capture snapshot capability unavailable")) return false } + f, err := filter.NewFilter(m.controller.replicaConfig.Filter, "", util.GetOrZero(m.controller.replicaConfig.CaseSensitive), util.GetOrZero(m.controller.replicaConfig.ForceReplicate)) + if err != nil { + m.handleError(err) + return false + } controller := bootstrap.Controller{ID: m.changefeedID, Epoch: m.info.Epoch, TS: m.info.StartTs, Keyspace: m.controller.keyspaceMeta.ID, Config: cfg, ArtifactDir: artifactDir, CSEBinary: serverCfg.SnapshotCSEBinary, ExportWorkers: serverCfg.SnapshotExportWorkers, MinFreeBytes: serverCfg.SnapshotMinFreeBytes, Repository: repo, Capture: capture, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { bundle := bootstrap.SchemaBundle{SnapshotTS: m.info.StartTs} - tables, err := m.controller.loadTables(m.info.StartTs) + schemas := appcontext.GetService[schemastore.SchemaStore](appcontext.SchemaStore) + tables, err := m.controller.loadTables(m.snapshotContext, m.info.StartTs, schemas, f) if err != nil { return bundle, nil, protocol.Wrap(err) } sort.Slice(tables, func(i, j int) bool { return tables[i].TableID < tables[j].TableID }) - schemas := appcontext.GetService[schemastore.SchemaStore](appcontext.SchemaStore) var spans []protocol.Span for _, t := range tables { // Snapshot mounting precedes incremental dispatcher registration. Pin // this version explicitly while copying its frozen schema. - if err := schemas.RegisterTable(m.controller.keyspaceMeta, t.TableID, m.info.StartTs); err != nil { + if err := schemas.RegisterTable(m.snapshotContext, m.controller.keyspaceMeta, t.TableID, m.info.StartTs); err != nil { return bundle, nil, protocol.Wrap(err) } - table, err := schemas.GetTableInfo(m.controller.keyspaceMeta, t.TableID, m.info.StartTs) + table, err := schemas.GetTableInfo(m.snapshotContext, m.controller.keyspaceMeta, t.TableID, m.info.StartTs) unregisterErr := schemas.UnregisterTable(m.controller.keyspaceMeta, t.TableID) if err != nil { return bundle, nil, protocol.Wrap(err) From 9f9d2dbba0f491fab4dcface641986d8074fc97c Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 30 Nov 2026 15:30:15 +0800 Subject: [PATCH 12/17] snapshot: isolate CSE bootstrap and expose stage performance --- api/v2/changefeed.go | 2 +- api/v2/model.go | 3 + cmd/cdc/server/server.go | 4 - cmd/snapshot-provider/main.go | 43 - coordinator/changefeed/snapshot.go | 64 +- coordinator/changefeed/snapshot_test.go | 9 +- coordinator/coordinator.go | 1 - coordinator/snapshot.go | 43 - deployments/snapshot.Dockerfile | 12 + .../dispatchermanager/dispatcher_manager.go | 7 +- .../dispatcherorchestrator/snapshot.go | 51 - downstreamadapter/sink/helper/mq_row_event.go | 16 - .../sink/helper/snapshot_test.go | 33 - maintainer/maintainer.go | 28 +- maintainer/maintainer_event.go | 11 +- maintainer/snapshot.go | 101 +- maintainer/snapshot_test.go | 35 + metrics/grafana/ticdc_new_arch.json | 1023 ++++++++++++++++- .../ticdc_new_arch_next_gen.json | 1023 ++++++++++++++++- .../ticdc_new_arch_with_keyspace_name.json | 1023 ++++++++++++++++- pkg/common/event/dml_event.go | 2 - pkg/common/event/row_change.go | 7 - pkg/config/changefeed.go | 3 + pkg/config/changefeed_test.go | 5 + pkg/config/replica_config.go | 3 + pkg/config/server.go | 26 +- pkg/messaging/message.go | 8 + pkg/messaging/message_snapshot_test.go | 22 + pkg/metrics/init.go | 1 + pkg/metrics/snapshot.go | 104 ++ pkg/sink/codec/open/codec.go | 6 +- pkg/sink/codec/open/snapshot_test.go | 32 - pkg/snapshot/bootstrap/controller.go | 113 +- pkg/snapshot/bootstrap/controller_test.go | 57 + pkg/snapshot/bootstrap/interfaces.go | 6 +- pkg/snapshot/exporter/cleanup.go | 68 ++ pkg/snapshot/exporter/cleanup_test.go | 27 + pkg/snapshot/exporter/diagnostics.go | 62 + pkg/snapshot/exporter/disk.go | 65 ++ pkg/snapshot/exporter/disk_test.go | 67 ++ .../provider.go => exporter/exporter.go} | 262 +++-- .../exporter_test.go} | 38 +- pkg/snapshot/exporter/process_linux.go | 11 + pkg/snapshot/exporter/process_other.go | 8 + pkg/snapshot/placement.go | 35 + pkg/snapshot/placement_test.go | 39 + pkg/snapshot/protocol/chunk.go | 2 + pkg/snapshot/protocol/message.go | 16 + pkg/snapshot/protocol/protocol_test.go | 11 +- pkg/snapshot/protocol/types.go | 105 +- pkg/snapshot/provider/client.go | 61 - pkg/snapshot/schema.go | 76 ++ pkg/snapshot/schema_test.go | 44 + pkg/snapshot/service.go | 362 ++++++ pkg/snapshot/service_mock_test.go | 118 ++ pkg/snapshot/service_test.go | 88 ++ pkg/snapshot/state/repository.go | 94 ++ pkg/snapshot/state/repository_test.go | 68 ++ pkg/snapshot/store/tasks.go | 2 - pkg/snapshot/validate.go | 47 + .../snapshot.go => pkg/snapshot/writer.go | 81 +- .../snapshot/writer_test.go | 78 +- scripts/generate-mock.sh | 1 + server/server.go | 4 + .../native_snapshot/README.md | 346 ++---- .../integration_tests/native_snapshot/demo.py | 17 +- .../native_snapshot/verify/main.go | 23 +- 67 files changed, 5179 insertions(+), 1074 deletions(-) delete mode 100644 cmd/snapshot-provider/main.go delete mode 100644 coordinator/snapshot.go create mode 100644 deployments/snapshot.Dockerfile delete mode 100644 downstreamadapter/dispatcherorchestrator/snapshot.go delete mode 100644 downstreamadapter/sink/helper/snapshot_test.go create mode 100644 maintainer/snapshot_test.go create mode 100644 pkg/messaging/message_snapshot_test.go create mode 100644 pkg/metrics/snapshot.go delete mode 100644 pkg/sink/codec/open/snapshot_test.go create mode 100644 pkg/snapshot/exporter/cleanup.go create mode 100644 pkg/snapshot/exporter/cleanup_test.go create mode 100644 pkg/snapshot/exporter/diagnostics.go create mode 100644 pkg/snapshot/exporter/disk.go create mode 100644 pkg/snapshot/exporter/disk_test.go rename pkg/snapshot/{provider/provider.go => exporter/exporter.go} (68%) rename pkg/snapshot/{provider/provider_test.go => exporter/exporter_test.go} (83%) create mode 100644 pkg/snapshot/exporter/process_linux.go create mode 100644 pkg/snapshot/exporter/process_other.go create mode 100644 pkg/snapshot/placement.go create mode 100644 pkg/snapshot/placement_test.go create mode 100644 pkg/snapshot/protocol/message.go delete mode 100644 pkg/snapshot/provider/client.go create mode 100644 pkg/snapshot/schema.go create mode 100644 pkg/snapshot/schema_test.go create mode 100644 pkg/snapshot/service.go create mode 100644 pkg/snapshot/service_mock_test.go create mode 100644 pkg/snapshot/service_test.go create mode 100644 pkg/snapshot/state/repository.go create mode 100644 pkg/snapshot/state/repository_test.go create mode 100644 pkg/snapshot/validate.go rename downstreamadapter/dispatchermanager/snapshot.go => pkg/snapshot/writer.go (70%) rename downstreamadapter/dispatchermanager/snapshot_test.go => pkg/snapshot/writer_test.go (69%) diff --git a/api/v2/changefeed.go b/api/v2/changefeed.go index d8280b15a7..d9a325590b 100644 --- a/api/v2/changefeed.go +++ b/api/v2/changefeed.go @@ -621,7 +621,7 @@ func CfInfoToAPIModel( apiInfoModel := &ChangeFeedInfo{ Snapshot: status.Snapshot, - BootstrapComplete: info.Config == nil || info.Config.Snapshot == nil || status.Snapshot != nil && status.Snapshot.Marker != nil, + BootstrapComplete: info.Config == nil || info.Config.Snapshot == nil || status.Snapshot != nil && status.Snapshot.Phase == "SNAPSHOT_COMMITTED", UpstreamID: info.UpstreamID, ID: info.ChangefeedID.Name(), Keyspace: info.ChangefeedID.Keyspace(), diff --git a/api/v2/model.go b/api/v2/model.go index 7b1a052c79..bfa88e7e94 100644 --- a/api/v2/model.go +++ b/api/v2/model.go @@ -1542,6 +1542,9 @@ func (c *ReplicaConfig) omitSensitiveData() { // maskSensitiveData masks configured API fields without populating omitted fields. func (c *ReplicaConfig) maskSensitiveData() { + if c != nil && c.Snapshot != nil { + c.Snapshot.BackupURI = util.MaskSensitiveDataInURI(c.Snapshot.BackupURI) + } if c == nil { return } diff --git a/cmd/cdc/server/server.go b/cmd/cdc/server/server.go index a324c9531e..d54343c196 100644 --- a/cmd/cdc/server/server.go +++ b/cmd/cdc/server/server.go @@ -77,8 +77,6 @@ func (o *options) addFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.serverConfig.DataDir, "data-dir", o.serverConfig.DataDir, "the path to the directory used to store TiCDC-generated data") cmd.Flags().StringVar(&o.serverConfig.SnapshotCSEBinary, "snapshot-cse-binary", o.serverConfig.SnapshotCSEBinary, "CSE binary for embedded packed-backup snapshot export") - cmd.Flags().StringVar(&o.serverConfig.SnapshotArtifactDir, "snapshot-artifact-dir", o.serverConfig.SnapshotArtifactDir, "persistent artifact directory for embedded snapshot export") - cmd.Flags().IntVar(&o.serverConfig.SnapshotExportWorkers, "snapshot-export-workers", o.serverConfig.SnapshotExportWorkers, "maximum concurrent local snapshot export processes per changefeed") cmd.Flags().Int64Var(&o.serverConfig.SnapshotMinFreeBytes, "snapshot-min-free-bytes", o.serverConfig.SnapshotMinFreeBytes, "minimum free bytes before starting another snapshot range") cmd.Flags().StringSliceVar(&o.pdEndpoints, "pd", []string{"http://127.0.0.1:2379"}, "Set the PD endpoints to use. Use ',' to separate multiple PDs") @@ -219,9 +217,7 @@ func (o *options) complete(command *cobra.Command) error { case "snapshot-cse-binary": cfg.SnapshotCSEBinary = o.serverConfig.SnapshotCSEBinary case "snapshot-artifact-dir": - cfg.SnapshotArtifactDir = o.serverConfig.SnapshotArtifactDir case "snapshot-export-workers": - cfg.SnapshotExportWorkers = o.serverConfig.SnapshotExportWorkers case "snapshot-min-free-bytes": cfg.SnapshotMinFreeBytes = o.serverConfig.SnapshotMinFreeBytes case "ca": diff --git a/cmd/snapshot-provider/main.go b/cmd/snapshot-provider/main.go deleted file mode 100644 index d67c81d2e0..0000000000 --- a/cmd/snapshot-provider/main.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package main - -import ( - "flag" - "log" - "net/http" - "os" - "path/filepath" - "syscall" - "time" - - "github.com/pingcap/ticdc/pkg/snapshot/provider" -) - -func main() { - root := flag.String("root", "", "shared artifact directory") - binary := flag.String("cse-binary", "", "CSE batch binary") - addr := flag.String("listen", "127.0.0.1:18400", "listen address") - workers := flag.Int("workers", 1, "maximum concurrent local range workers per job (1-32)") - flag.Parse() - if *workers < 1 || *workers > 32 { - log.Fatal("workers must be between 1 and 32") - } - if *root == "" || *binary == "" { - log.Fatal("root and cse-binary required") - } - if e := os.MkdirAll(*root, 0o700); e != nil { - log.Fatal(e) - } - f, e := os.OpenFile(filepath.Join(*root, "provider.lock"), os.O_CREATE|os.O_RDWR, 0o600) - if e != nil { - log.Fatal(e) - } - defer f.Close() - if e = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); e != nil { - log.Fatal("another controller owns this demo store") - } - controller := provider.New(*root, *binary) - controller.Workers = *workers - s := http.Server{Addr: *addr, Handler: controller, ReadHeaderTimeout: 5 * time.Second} - log.Fatal(s.ListenAndServe()) -} diff --git a/coordinator/changefeed/snapshot.go b/coordinator/changefeed/snapshot.go index 60e28d812c..38a87c1203 100644 --- a/coordinator/changefeed/snapshot.go +++ b/coordinator/changefeed/snapshot.go @@ -5,72 +5,14 @@ import ( "context" "github.com/pingcap/ticdc/pkg/common" - "github.com/pingcap/ticdc/pkg/config" - "github.com/pingcap/ticdc/pkg/etcd" "github.com/pingcap/ticdc/pkg/snapshot/protocol" - clientv3 "go.etcd.io/etcd/client/v3" + "github.com/pingcap/ticdc/pkg/snapshot/state" ) func (b *EtcdBackend) LoadSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) (*protocol.State, error) { - info, e := b.etcdClient.GetChangeFeedInfo(ctx, id.DisplayName) - if e != nil { - return nil, protocol.Wrap(e) - } - if info.Epoch != epoch { - return nil, protocol.Invalid("stale snapshot owner") - } - status, _, e := b.etcdClient.GetChangeFeedStatus(ctx, id) - if e != nil { - return nil, protocol.Wrap(e) - } - return status.Snapshot, nil + return (&state.Repository{Client: b.etcdClient}).LoadSnapshot(ctx, id, epoch) } func (b *EtcdBackend) SaveSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, next *protocol.State) error { - infoKey := etcd.GetEtcdKeyChangeFeedInfo(b.etcdClient.GetClusterID(), id.DisplayName) - statusKey := etcd.GetEtcdKeyJob(b.etcdClient.GetClusterID(), id.DisplayName) - for retry := 0; retry < 20; retry++ { - ir, e := b.etcdClient.GetEtcdClient().Get(ctx, infoKey) - if e != nil { - return protocol.Wrap(e) - } - if len(ir.Kvs) != 1 { - return protocol.Invalid("changefeed disappeared") - } - var info config.ChangeFeedInfo - if e = info.Unmarshal(ir.Kvs[0].Value); e != nil { - return e - } - if info.Epoch != epoch || info.ChangefeedID != id || !info.State.IsRunning() { - return protocol.Invalid("snapshot owner no longer active") - } - status, rev, e := b.etcdClient.GetChangeFeedStatus(ctx, id) - if e != nil { - return protocol.Wrap(e) - } - if old := status.Snapshot; old != nil { - if old.Generation != next.Generation || old.SnapshotID != next.SnapshotID || old.SnapshotTS != next.SnapshotTS { - return protocol.Invalid("snapshot identity changed") - } - if old.Marker != nil && (next.Marker == nil || *old.Marker != *next.Marker) { - return protocol.Invalid("cannot roll back snapshot marker") - } - } - if next.Marker != nil && (next.Phase != "SNAPSHOT_COMMITTED" || next.PlanRef.URI == "" || next.Marker.SnapshotID != next.SnapshotID || next.Marker.SnapshotTS != next.SnapshotTS) { - return protocol.Invalid("marker/phase mismatch") - } - status.Snapshot = next - bts, e := status.Marshal() - if e != nil { - return e - } - res, e := b.etcdClient.GetEtcdClient().Txn(ctx, []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision(infoKey), "=", ir.Kvs[0].ModRevision), clientv3.Compare(clientv3.ModRevision(statusKey), "=", rev)}, []clientv3.Op{clientv3.OpPut(statusKey, bts)}, nil) - if e != nil { - return protocol.Wrap(e) - } - if res.Succeeded { - return nil - } - } - return protocol.Invalid("snapshot runtime CAS contention") + return (&state.Repository{Client: b.etcdClient}).SaveSnapshot(ctx, id, epoch, next) } diff --git a/coordinator/changefeed/snapshot_test.go b/coordinator/changefeed/snapshot_test.go index beff6cbe15..fb04c5c93d 100644 --- a/coordinator/changefeed/snapshot_test.go +++ b/coordinator/changefeed/snapshot_test.go @@ -24,20 +24,19 @@ func TestCheckpointPreservesSnapshotAcrossConflict(t *testing.T) { backend := NewEtcdBackend(cdc) id := common.NewChangeFeedIDWithName("demo", common.DefaultKeyspaceName) first := &config.ChangeFeedStatus{CheckpointTs: 42, Snapshot: &protocol.State{Generation: "g", Phase: "APPLYING"}} - marker := &protocol.Marker{SnapshotTS: 42, SnapshotID: "s"} - second := &config.ChangeFeedStatus{CheckpointTs: 42, Progress: config.ProgressStopping, Snapshot: &protocol.State{Generation: "g", Phase: "SNAPSHOT_COMMITTED", Marker: marker}} + second := &config.ChangeFeedStatus{CheckpointTs: 42, Progress: config.ProgressStopping, Snapshot: &protocol.State{Generation: "g", Phase: "SNAPSHOT_COMMITTED"}} gomock.InOrder(cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(first, int64(1), nil), raw.EXPECT().Txn(gomock.Any(), gomock.Len(1), gomock.Any(), gomock.Any()).Return(&clientv3.TxnResponse{}, nil), cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(second, int64(2), nil), raw.EXPECT().Txn(gomock.Any(), gomock.Len(1), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ []clientv3.Cmp, ops []clientv3.Op, _ []clientv3.Op) (*clientv3.TxnResponse, error) { var s config.ChangeFeedStatus require.NoError(t, s.Unmarshal(ops[0].ValueBytes())) require.Equal(t, uint64(100), s.CheckpointTs) require.Equal(t, config.ProgressStopping, s.Progress) - require.Equal(t, marker, s.Snapshot.Marker) + require.Equal(t, "SNAPSHOT_COMMITTED", s.Snapshot.Phase) return &clientv3.TxnResponse{Succeeded: true}, nil })) require.NoError(t, backend.UpdateChangefeedCheckpointTs(context.Background(), map[common.ChangeFeedID]uint64{id: 100})) } -func TestSnapshotRejectsOldOwnerAndMarkerRollback(t *testing.T) { +func TestSnapshotRejectsOldOwnerAndPhaseRollback(t *testing.T) { ctrl := gomock.NewController(t) cdc := etcd.NewMockCDCEtcdClient(ctrl) raw := etcd.NewMockClient(ctrl) @@ -50,7 +49,7 @@ func TestSnapshotRejectsOldOwnerAndMarkerRollback(t *testing.T) { require.NoError(t, e) raw.EXPECT().Get(gomock.Any(), gomock.Any()).Return(&clientv3.GetResponse{Kvs: []*mvccpb.KeyValue{{Value: []byte(b), ModRevision: 7}}}, nil).Times(2) require.ErrorContains(t, backend.SaveSnapshot(context.Background(), id, 1, &protocol.State{Generation: "g"}), "owner") - old := &protocol.State{Generation: "g", SnapshotID: "s", SnapshotTS: 42, Phase: "SNAPSHOT_COMMITTED", Marker: &protocol.Marker{SnapshotTS: 42}} + old := &protocol.State{Generation: "g", SnapshotID: "s", SnapshotTS: 42, Phase: "SNAPSHOT_COMMITTED"} cdc.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(&config.ChangeFeedStatus{Snapshot: old}, int64(9), nil) require.ErrorContains(t, backend.SaveSnapshot(context.Background(), id, 2, &protocol.State{Generation: "g", SnapshotID: "s", SnapshotTS: 42}), "roll back") } diff --git a/coordinator/coordinator.go b/coordinator/coordinator.go index 5ff7c9931b..7392218b4e 100644 --- a/coordinator/coordinator.go +++ b/coordinator/coordinator.go @@ -124,7 +124,6 @@ func New(node *node.Info, changefeedChangeCh: make(chan []*changefeedChange, 1024), backend: backend, } - appcontext.SetService(bootstrap.RepositoryService, bootstrap.Repository(c)) // handle messages from message center mc.RegisterHandler(messaging.CoordinatorTopic, c.recvMessages) c.controller = NewController( diff --git a/coordinator/snapshot.go b/coordinator/snapshot.go deleted file mode 100644 index a800c00b4d..0000000000 --- a/coordinator/snapshot.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package coordinator - -import ( - "context" - - "github.com/pingcap/ticdc/pkg/common" - "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" - "github.com/pingcap/ticdc/pkg/snapshot/protocol" -) - -func (c *coordinator) snapshotOwner(id common.ChangeFeedID, epoch uint64) error { - if c.closed.Load() { - return protocol.Invalid("coordinator stopped") - } - cf := c.controller.getChangefeed(id) - if cf == nil || cf.GetNodeID() != c.nodeInfo.ID || cf.GetInfo().Epoch != epoch { - return protocol.Invalid("demo snapshot requires local current maintainer") - } - return nil -} - -func (c *coordinator) LoadSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) (*protocol.State, error) { - if e := c.snapshotOwner(id, epoch); e != nil { - return nil, e - } - b, ok := c.backend.(bootstrap.Repository) - if !ok { - return nil, protocol.Invalid("backend does not support snapshots") - } - return b.LoadSnapshot(ctx, id, epoch) -} - -func (c *coordinator) SaveSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, s *protocol.State) error { - if e := c.snapshotOwner(id, epoch); e != nil { - return e - } - b, ok := c.backend.(bootstrap.Repository) - if !ok { - return protocol.Invalid("backend does not support snapshots") - } - return b.SaveSnapshot(ctx, id, epoch, s) -} diff --git a/deployments/snapshot.Dockerfile b/deployments/snapshot.Dockerfile new file mode 100644 index 0000000000..1df896412c --- /dev/null +++ b/deployments/snapshot.Dockerfile @@ -0,0 +1,12 @@ +# Build CDC and the matching CSE exporter for the target architecture first. +# Both artifacts must be supplied in bin/; this image never downloads an exporter. +FROM rockylinux:9.3 +RUN dnf install -y ca-certificates tzdata libstdc++ libgcc openssl-libs \ + && dnf clean all +COPY bin/cdc /cdc +COPY bin/cse-ctl /usr/local/bin/cse-ctl +# Fail the image build when the supplied exporter cannot load its runtime libraries. +RUN /usr/local/bin/cse-ctl snapshot --help >/dev/null +EXPOSE 8300 +ENTRYPOINT ["/cdc"] +CMD ["server"] diff --git a/downstreamadapter/dispatchermanager/dispatcher_manager.go b/downstreamadapter/dispatchermanager/dispatcher_manager.go index 71c665f6ae..1c594fc3c2 100644 --- a/downstreamadapter/dispatchermanager/dispatcher_manager.go +++ b/downstreamadapter/dispatchermanager/dispatcher_manager.go @@ -148,10 +148,7 @@ type DispatcherManager struct { // writeSink is the capture-write-gated view passed to dispatchers. // sink remains the concrete implementation used for lifecycle and // sink-specific recovery operations. - writeSink sink.Sink - sinkStopped chan struct{} - snapshotMu sync.Mutex - snapshotRuntime *snapshotRuntime + writeSink sink.Sink // redo related // redoEnabled is immutable and set to true if enabled. @@ -239,7 +236,6 @@ func NewDispatcherManager( } manager = &DispatcherManager{ - sinkStopped: make(chan struct{}), ctx: ctx, dispatcherMap: newDispatcherMap[*dispatcher.EventDispatcher](), currentOperatorMap: sync.Map{}, @@ -397,7 +393,6 @@ func NewDispatcherManager( go func() { defer manager.wg.Done() err := manager.sink.Run(ctx) - close(manager.sinkStopped) manager.handleError(ctx, err) }() diff --git a/downstreamadapter/dispatcherorchestrator/snapshot.go b/downstreamadapter/dispatcherorchestrator/snapshot.go deleted file mode 100644 index af49e6be1e..0000000000 --- a/downstreamadapter/dispatcherorchestrator/snapshot.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package dispatcherorchestrator - -import ( - "context" - "time" - - "github.com/pingcap/ticdc/downstreamadapter/dispatchermanager" - "github.com/pingcap/ticdc/pkg/common" - "github.com/pingcap/ticdc/pkg/snapshot/protocol" -) - -func (m *DispatcherOrchestrator) snapshotManager(id common.ChangeFeedID) (*dispatchermanager.DispatcherManager, error) { - m.mutex.Lock() - defer m.mutex.Unlock() - e := m.dispatcherManagers[id] - if e == nil || m.fenced.Load() || m.closed.Load() { - return nil, protocol.Invalid("capture is unavailable") - } - return e, nil -} - -func (m *DispatcherOrchestrator) ApplySnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { - e, err := m.snapshotManager(id) - if err != nil { - return 0, err - } - return e.ApplySnapshot(ctx, epoch, spec, ref, ex) -} - -func (m *DispatcherOrchestrator) DrainSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) error { - e, err := m.snapshotManager(id) - if err != nil { - return err - } - return e.DrainSnapshot(ctx, epoch) -} - -// Abort waits for closure before releasing the single-host writer lock. -func (m *DispatcherOrchestrator) AbortSnapshot(id common.ChangeFeedID) { - m.mutex.Lock() - e := m.dispatcherManagers[id] - m.mutex.Unlock() - if e == nil { - return - } - e.LocalFence() - for !e.TryClose(false) { - time.Sleep(50 * time.Millisecond) - } -} diff --git a/downstreamadapter/sink/helper/mq_row_event.go b/downstreamadapter/sink/helper/mq_row_event.go index 1901953b3c..bbd8de207c 100644 --- a/downstreamadapter/sink/helper/mq_row_event.go +++ b/downstreamadapter/sink/helper/mq_row_event.go @@ -17,7 +17,6 @@ import ( "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" "github.com/pingcap/ticdc/downstreamadapter/sink/eventrouter/partition" commonEvent "github.com/pingcap/ticdc/pkg/common/event" - "github.com/pingcap/ticdc/pkg/snapshot/protocol" ) func NewMQRowEvents( @@ -54,7 +53,6 @@ func NewMQRowEvents( TotalPartition: partitionNum, }, RowEvent: commonEvent.RowEvent{ - Snapshot: snapshotRow(event, row), PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, StartTs: event.StartTs, @@ -87,7 +85,6 @@ func NewRowEvents( } events = append(events, &commonEvent.RowEvent{ - Snapshot: snapshotRow(event, row), PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, StartTs: event.StartTs, @@ -100,16 +97,3 @@ func NewRowEvents( } return events } - -// A mounted snapshot batch shares generation metadata, but every row has its -// own identity. Never copy a batch-level record ID to all rows in the batch. -func snapshotRow(event *commonEvent.DMLEvent, row commonEvent.RowChange) *commonEvent.SnapshotRow { - if event.Snapshot == nil { - return nil - } - return &commonEvent.SnapshotRow{ - ID: protocol.RecordID(event.Snapshot.SnapshotID, event.PhysicalTableID, row.RowKey), - SnapshotID: event.Snapshot.SnapshotID, - Timestamp: event.Snapshot.Timestamp, - } -} diff --git a/downstreamadapter/sink/helper/snapshot_test.go b/downstreamadapter/sink/helper/snapshot_test.go deleted file mode 100644 index 3074c90c29..0000000000 --- a/downstreamadapter/sink/helper/snapshot_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package helper - -import ( - "testing" - - commonEvent "github.com/pingcap/ticdc/pkg/common/event" - "github.com/pingcap/ticdc/pkg/snapshot/protocol" - "github.com/stretchr/testify/require" -) - -func TestSnapshotBatchPreservesPerRowIdentity(t *testing.T) { - helper := commonEvent.NewEventTestHelper(t) - defer helper.Close() - helper.DDL2Job("create table test.snap_ids (id int primary key, v int)") - ev := helper.DML2Event("test", "snap_ids", "insert into test.snap_ids values(1,10)", "insert into test.snap_ids values(2,20)") - ev.Snapshot = &commonEvent.SnapshotRow{SnapshotID: "generation", Timestamp: 42} - flushed := 0 - ev.AddPostFlushFunc(func() { flushed++ }) - rows := NewRowEvents(ev, nil, NewPostFlushRowCallback(ev, uint64(ev.Len()))) - require.Len(t, rows, 2) - require.NotEqual(t, rows[0].Snapshot.ID, rows[1].Snapshot.ID) - for i, row := range rows { - require.Equal(t, protocol.RecordID("generation", ev.PhysicalTableID, ev.RowKeys[i]), row.Snapshot.ID) - require.Equal(t, uint64(42), row.Snapshot.Timestamp) - } - rows[1].Callback() - require.Zero(t, flushed) - rows[0].Callback() - require.Equal(t, 1, flushed) - ev.Snapshot = nil - require.Nil(t, snapshotRow(ev, rows[0].Event)) -} diff --git a/maintainer/maintainer.go b/maintainer/maintainer.go index 2facca073a..a283890e33 100644 --- a/maintainer/maintainer.go +++ b/maintainer/maintainer.go @@ -66,7 +66,6 @@ const ( type Maintainer struct { snapshotRunning bool snapshotDone bool - snapshotContext context.Context changefeedID common.ChangeFeedID info *config.ChangeFeedInfo selfNode *node.Info @@ -272,7 +271,6 @@ func NewMaintainer(cfID common.ChangeFeedID, ctx, cancel := context.WithCancel(context.Background()) m.ctx = ctx m.cancel = cancel - m.snapshotContext = ctx go m.runHandleEvents(ctx) go m.calCheckpointTs(ctx) @@ -371,7 +369,9 @@ func (m *Maintainer) HandleEvent(event *Event) bool { m.handleError(event.snapshotError) } else { m.snapshotDone = true - m.onBootstrapResponses(event.snapshotResponses) + if err := m.initialize(); err != nil { + m.handleError(err) + } } } return false @@ -460,6 +460,9 @@ func (m *Maintainer) SetDispatcherDrainTarget(target node.ID, epoch uint64) { } func (m *Maintainer) initialize() error { + if !m.snapshotBeforeBootstrap() { + return nil + } start := time.Now() log.Info("start to initialize changefeed maintainer", zap.Stringer("changefeedID", m.changefeedID)) @@ -584,6 +587,19 @@ func (m *Maintainer) onMessage(msg *messaging.TargetMessage) { } func (m *Maintainer) onRemoveMaintainer(cascade, changefeedRemoved bool) { + if m.info != nil && m.info.Config != nil && m.info.Config.Snapshot != nil && !m.snapshotDone && !m.initialized.Load() { + // Snapshot has not created dispatcher managers. A handoff can stop this + // maintainer immediately; the CDC-owned executor is adopted by its successor. + m.removing.Store(true) + m.cascadeRemoving.Store(cascade) + m.changefeedRemoved.Store(changefeedRemoved) + m.markRemoved() + m.scheduleState.Store(int32(heartbeatpb.ComponentState_Stopped)) + m.markStatusChanged() + m.cancel() + return + } + if !m.initialized.Load() && !cascade && !changefeedRemoved { // A non-cascade remove can arrive before bootstrap finishes in move/restart scenarios. // If we mark the maintainer as removing here, later bootstrap responses may be dropped, @@ -638,6 +654,9 @@ func (m *Maintainer) onRedoPersisted(req *heartbeatpb.RedoResolvedTsProgressMess } func (m *Maintainer) onNodeChanged() { + if m.info.Config.Snapshot != nil && !m.snapshotDone { + return + } addedNodes, removedNodes, requests, responses := m.bootstrapper.HandleNodesChange(m.nodeManager.GetAliveNodes()) log.Info("maintainer node changed", zap.Stringer("changefeedID", m.changefeedID), zap.Int("addedCount", len(addedNodes)), @@ -1168,9 +1187,6 @@ func (m *Maintainer) onBootstrapResponses(responses map[node.ID]*heartbeatpb.Mai if responses == nil || m.removing.Load() { return } - if !m.snapshotBeforeBootstrap(responses) { - return - } isMySQLSinkCompatible, err := isMysqlCompatible(m.info.SinkURI) if err != nil { m.handleError(err) diff --git a/maintainer/maintainer_event.go b/maintainer/maintainer_event.go index 3852ab614b..6f17a80cd4 100644 --- a/maintainer/maintainer_event.go +++ b/maintainer/maintainer_event.go @@ -14,10 +14,8 @@ package maintainer import ( - "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/messaging" - "github.com/pingcap/ticdc/pkg/node" ) const ( @@ -32,11 +30,10 @@ const ( // Event identify the Event that maintainer will handle in event-driven loop type Event struct { - snapshotError error - snapshotResponses map[node.ID]*heartbeatpb.MaintainerBootstrapResponse - changefeedID common.ChangeFeedID - eventType int - message *messaging.TargetMessage + snapshotError error + changefeedID common.ChangeFeedID + eventType int + message *messaging.TargetMessage // blockStatusReleaseKeys tracks the block-status keys reserved when the // event entered the maintainer queue. They are released after HandleEvent // returns so duplicate resends stay suppressed while the event is pending. diff --git a/maintainer/snapshot.go b/maintainer/snapshot.go index 045ab5c09c..6f7eab9635 100644 --- a/maintainer/snapshot.go +++ b/maintainer/snapshot.go @@ -2,116 +2,29 @@ package maintainer import ( - "net/url" - "sort" - - "github.com/pingcap/ticdc/heartbeatpb" - "github.com/pingcap/ticdc/logservice/schemastore" appcontext "github.com/pingcap/ticdc/pkg/common/context" - "github.com/pingcap/ticdc/pkg/config" - "github.com/pingcap/ticdc/pkg/filter" - "github.com/pingcap/ticdc/pkg/node" - "github.com/pingcap/ticdc/pkg/sink/kafka" - "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot" "github.com/pingcap/ticdc/pkg/snapshot/protocol" - "github.com/pingcap/ticdc/pkg/util" - "github.com/pingcap/tidb/pkg/tablecodec" ) -// The first native deployment keeps a single capture. The local Capture -// interface is the seam for later MessageCenter assignment transport. -func (m *Maintainer) snapshotBeforeBootstrap(responses map[node.ID]*heartbeatpb.MaintainerBootstrapResponse) bool { +func (m *Maintainer) snapshotBeforeBootstrap() bool { if m.info.Config.Snapshot == nil || m.snapshotDone { return true } if m.snapshotRunning { return false } - cfg := m.info.Config.Snapshot - serverCfg := config.GetGlobalServerConfig() - artifactDir := cfg.ArtifactDir - if cfg.ProviderURL == "" { - artifactDir = serverCfg.SnapshotArtifactDir - } - if err := cfg.ValidateRuntime(); err != nil { - m.handleError(err) - return false - } - uri, err := url.Parse(m.info.SinkURI) - if err != nil { - m.handleError(protocol.Wrap(err)) - return false - } - if len(responses) != 1 || responses[m.selfNode.ID] == nil || uri.Scheme != "kafka" || uri.Query().Get("protocol") != "open-protocol" || artifactDir == "" || (cfg.ProviderURL == "" && serverCfg.SnapshotCSEBinary == "") || cfg.BackupURI == "" || len(cfg.BackupDigest) != 64 || m.enableRedo || len(m.info.Config.Filter.EventFilters) > 0 { - m.handleError(protocol.Invalid("snapshot requires one capture, kafka open-protocol, frozen backup digest, artifact directory, CSE binary, and no redo/event filters")) - return false - } - options := kafka.NewOptions() - if err := options.Apply(m.changefeedID, uri, m.info.Config.Sink); err != nil { - m.handleError(err) - return false - } - if options.RequiredAcks == kafka.NoResponse { - m.handleError(protocol.Invalid("snapshot receipts require Kafka broker acknowledgements")) - return false - } - repo, ok := appcontext.TryGetService[bootstrap.Repository](bootstrap.RepositoryService) - if !ok { - m.handleError(protocol.Invalid("local coordinator snapshot service unavailable")) - return false - } - capture, ok := appcontext.TryGetService[bootstrap.Capture](appcontext.DispatcherOrchestrator) + service, ok := appcontext.TryGetService[*snapshot.Service](snapshot.ServiceName) if !ok { - m.handleError(protocol.Invalid("capture snapshot capability unavailable")) + m.handleError(protocol.Invalid("snapshot service unavailable")) return false } - f, err := filter.NewFilter(m.controller.replicaConfig.Filter, "", util.GetOrZero(m.controller.replicaConfig.CaseSensitive), util.GetOrZero(m.controller.replicaConfig.ForceReplicate)) - if err != nil { - m.handleError(err) - return false - } - controller := bootstrap.Controller{ID: m.changefeedID, Epoch: m.info.Epoch, TS: m.info.StartTs, Keyspace: m.controller.keyspaceMeta.ID, Config: cfg, ArtifactDir: artifactDir, CSEBinary: serverCfg.SnapshotCSEBinary, ExportWorkers: serverCfg.SnapshotExportWorkers, MinFreeBytes: serverCfg.SnapshotMinFreeBytes, Repository: repo, Capture: capture, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { - bundle := bootstrap.SchemaBundle{SnapshotTS: m.info.StartTs} - schemas := appcontext.GetService[schemastore.SchemaStore](appcontext.SchemaStore) - tables, err := m.controller.loadTables(m.snapshotContext, m.info.StartTs, schemas, f) - if err != nil { - return bundle, nil, protocol.Wrap(err) - } - sort.Slice(tables, func(i, j int) bool { return tables[i].TableID < tables[j].TableID }) - var spans []protocol.Span - for _, t := range tables { - // Snapshot mounting precedes incremental dispatcher registration. Pin - // this version explicitly while copying its frozen schema. - if err := schemas.RegisterTable(m.snapshotContext, m.controller.keyspaceMeta, t.TableID, m.info.StartTs); err != nil { - return bundle, nil, protocol.Wrap(err) - } - table, err := schemas.GetTableInfo(m.snapshotContext, m.controller.keyspaceMeta, t.TableID, m.info.StartTs) - unregisterErr := schemas.UnregisterTable(m.controller.keyspaceMeta, t.TableID) - if err != nil { - return bundle, nil, protocol.Wrap(err) - } - if unregisterErr != nil { - return bundle, nil, protocol.Wrap(unregisterErr) - } - b, err := table.Marshal() - if err != nil { - return bundle, nil, protocol.Wrap(err) - } - bundle.Tables = append(bundle.Tables, bootstrap.Schema{TableID: t.TableID, Data: b}) - start := tablecodec.GenTableRecordPrefix(t.TableID) - end := append([]byte(nil), start...) - end[len(end)-1]++ - spans = append(spans, protocol.Span{TableID: t.TableID, Start: start, End: end}) - } - return bundle, spans, nil - }} m.snapshotRunning = true go func() { - err := controller.Run(m.snapshotContext) + err := service.Bootstrap(m.ctx, m.info.ToChangefeedConfig(), m.controller.keyspaceMeta.ID) select { - case <-m.snapshotContext.Done(): - return - case m.eventCh.In() <- &Event{changefeedID: m.changefeedID, eventType: EventSnapshotDone, snapshotError: err, snapshotResponses: responses}: + case <-m.ctx.Done(): + case m.eventCh.In() <- &Event{changefeedID: m.changefeedID, eventType: EventSnapshotDone, snapshotError: err}: } }() return false diff --git a/maintainer/snapshot_test.go b/maintainer/snapshot_test.go new file mode 100644 index 0000000000..e6a445fac7 --- /dev/null +++ b/maintainer/snapshot_test.go @@ -0,0 +1,35 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package maintainer + +import ( + "context" + "fmt" + "testing" + + "github.com/pingcap/ticdc/heartbeatpb" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/metrics" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" + "go.uber.org/atomic" +) + +func TestSnapshotMaintainerCanStopBeforeDispatcherBootstrap(t *testing.T) { + for _, cascade := range []bool{false, true} { + t.Run(fmt.Sprint(cascade), func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cfg := config.GetDefaultReplicaConfig() + cfg.Snapshot = &protocol.Config{} + m := &Maintainer{removed: atomic.NewBool(false), ctx: ctx, cancel: cancel, changefeedID: common.NewChangeFeedIDWithName("snapshot-stop", common.DefaultKeyspaceName), info: &config.ChangeFeedInfo{Config: cfg}, snapshotRunning: true} + metrics.MaintainerGauge.WithLabelValues(m.changefeedID.Keyspace(), m.changefeedID.Name()).Inc() + defer metrics.MaintainerGauge.DeleteLabelValues(m.changefeedID.Keyspace(), m.changefeedID.Name()) + m.onRemoveMaintainer(cascade, false) + require.True(t, m.removed.Load()) + require.True(t, m.removing.Load()) + require.Equal(t, int32(heartbeatpb.ComponentState_Stopped), m.scheduleState.Load()) + require.ErrorIs(t, ctx.Err(), context.Canceled) + }) + } +} diff --git a/metrics/grafana/ticdc_new_arch.json b/metrics/grafana/ticdc_new_arch.json index d1ab6b44fc..a2e5d7dd62 100644 --- a/metrics/grafana/ticdc_new_arch.json +++ b/metrics/grafana/ticdc_new_arch.json @@ -29316,6 +29316,1021 @@ ], "title": "Kafka Sink V2", "type": "row" + }, + { + "collapsed": true, + "datasource": { + "type": "datasource", + "uid": "grafana" + }, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 28 + }, + "id": 62200, + "panels": [ + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Export counts validated published chunks; apply counts downstream PostFlush acknowledgments, including replay. Both use logical KV key+value bytes, not SST or sink wire bytes.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 29 + }, + "hiddenSeries": false, + "id": 62201, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(rate(ticdc_snapshot_bytes_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}[$__rate_interval])) by (namespace, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot KV throughput", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "Bps", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Rows published by export or acknowledged by the sink. Replayed writes count again.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 29 + }, + "hiddenSeries": false, + "id": 62202, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(rate(ticdc_snapshot_rows_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}[$__rate_interval])) by (namespace, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot rows", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ops", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Active CSE commands and active range apply workers, including time waiting for their sink acknowledgments.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 36 + }, + "hiddenSeries": false, + "id": 62203, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_active_workers{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}) by (namespace, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot active workers", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Committed ranges have durable sink acknowledgments. Ready ranges include ranges currently being applied.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 36 + }, + "hiddenSeries": false, + "id": 62204, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",kind=~\"total_ranges|committed_ranges|ready_ranges\"}) by (namespace, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot range progress", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Shared budget covers mounted rows awaiting sink ACKs. Input chunks and sink internal buffers are additional memory; this is not process RSS.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 43 + }, + "hiddenSeries": false, + "id": 62205, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",kind=~\"inflight_bytes|write_memory_quota_bytes\"}) by (namespace, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot write memory", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Sampled artifact usage during CSE commands, including partial attempts. The last sample remains after commands stop; this is not a filesystem hard quota.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 43 + }, + "hiddenSeries": false, + "id": 62206, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",kind=~\"artifact_disk_bytes|disk_quota_bytes\"}) by (namespace, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot artifact disk", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Batch enqueue to PostFlush acknowledgment, including queueing, encoding, transmission and confirmation.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 50 + }, + "hiddenSeries": false, + "id": 62207, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "histogram_quantile(0.99,sum(rate(ticdc_snapshot_operation_duration_seconds_bucket{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"sink_ack\"}[$__rate_interval])) by (le,namespace,changefeed))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-p99", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot sink acknowledgment latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "CSE command duration and shared write-budget acquisition duration.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 50 + }, + "hiddenSeries": false, + "id": 62208, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "histogram_quantile(0.99,sum(rate(ticdc_snapshot_operation_duration_seconds_bucket{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=~\"plan|materialize-range|write_budget_wait\"}[$__rate_interval])) by (le,namespace,changefeed,stage))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{stage}}-p99", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot export and write wait latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Cumulative failed CSE commands, failed or canceled executions, and CSE command retries started.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 57 + }, + "hiddenSeries": false, + "id": 62209, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_errors_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}) by (namespace,changefeed,stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{stage}}-errors", + "refId": "A" + }, + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_retries_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}) by (namespace,changefeed,stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-{{stage}}-retries", + "refId": "B" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot failures and retries", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Latest execution attempt. Export begins after planning, apply begins at the first range, overall includes both. Pipeline stages overlap: do not add their durations.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 57 + }, + "hiddenSeries": false, + "id": 62210, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,namespace,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,namespace,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,namespace,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-export", + "refId": "A" + }, + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,namespace,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,namespace,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,namespace,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-apply", + "refId": "B" + }, + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,namespace,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,namespace,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,namespace,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-overall", + "refId": "C" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot stage wall time", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + } + ], + "title": "Snapshot", + "type": "row" } ], "refresh": "10s", @@ -29396,7 +30411,7 @@ "value": "$__all" }, "datasource": "${DS_TEST-CLUSTER}", - "definition": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, namespace)", + "definition": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, namespace)", "description": null, "error": null, "hide": 0, @@ -29406,7 +30421,7 @@ "name": "namespace", "options": [], "query": { - "query": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, namespace)", + "query": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, namespace)", "refId": "StandardVariableQuery" }, "refresh": 2, @@ -29427,7 +30442,7 @@ "value": "$__all" }, "datasource": "${DS_TEST-CLUSTER}", - "definition": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", + "definition": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", "description": null, "error": null, "hide": 0, @@ -29437,7 +30452,7 @@ "name": "changefeed", "options": [], "query": { - "query": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", + "query": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", "refId": "StandardVariableQuery" }, "refresh": 2, diff --git a/metrics/nextgengrafana/ticdc_new_arch_next_gen.json b/metrics/nextgengrafana/ticdc_new_arch_next_gen.json index c01bfa98e8..895d6a769c 100644 --- a/metrics/nextgengrafana/ticdc_new_arch_next_gen.json +++ b/metrics/nextgengrafana/ticdc_new_arch_next_gen.json @@ -29316,6 +29316,1021 @@ ], "title": "Kafka Sink V2", "type": "row" + }, + { + "collapsed": true, + "datasource": { + "type": "datasource", + "uid": "grafana" + }, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 28 + }, + "id": 62200, + "panels": [ + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Export counts validated published chunks; apply counts downstream PostFlush acknowledgments, including replay. Both use logical KV key+value bytes, not SST or sink wire bytes.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 29 + }, + "hiddenSeries": false, + "id": 62201, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(rate(ticdc_snapshot_bytes_total{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])) by (keyspace_name, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot KV throughput", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "Bps", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Rows published by export or acknowledged by the sink. Replayed writes count again.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 29 + }, + "hiddenSeries": false, + "id": 62202, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(rate(ticdc_snapshot_rows_total{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])) by (keyspace_name, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot rows", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ops", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Active CSE commands and active range apply workers, including time waiting for their sink acknowledgments.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 36 + }, + "hiddenSeries": false, + "id": 62203, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_active_workers{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) by (keyspace_name, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot active workers", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Committed ranges have durable sink acknowledgments. Ready ranges include ranges currently being applied.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 36 + }, + "hiddenSeries": false, + "id": 62204, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",kind=~\"total_ranges|committed_ranges|ready_ranges\"}) by (keyspace_name, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot range progress", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Shared budget covers mounted rows awaiting sink ACKs. Input chunks and sink internal buffers are additional memory; this is not process RSS.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 43 + }, + "hiddenSeries": false, + "id": 62205, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",kind=~\"inflight_bytes|write_memory_quota_bytes\"}) by (keyspace_name, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot write memory", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Sampled artifact usage during CSE commands, including partial attempts. The last sample remains after commands stop; this is not a filesystem hard quota.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 43 + }, + "hiddenSeries": false, + "id": 62206, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",kind=~\"artifact_disk_bytes|disk_quota_bytes\"}) by (keyspace_name, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot artifact disk", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Batch enqueue to PostFlush acknowledgment, including queueing, encoding, transmission and confirmation.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 50 + }, + "hiddenSeries": false, + "id": 62207, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "histogram_quantile(0.99,sum(rate(ticdc_snapshot_operation_duration_seconds_bucket{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"sink_ack\"}[$__rate_interval])) by (le,keyspace_name,changefeed))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-p99", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot sink acknowledgment latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "CSE command duration and shared write-budget acquisition duration.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 50 + }, + "hiddenSeries": false, + "id": 62208, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "histogram_quantile(0.99,sum(rate(ticdc_snapshot_operation_duration_seconds_bucket{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=~\"plan|materialize-range|write_budget_wait\"}[$__rate_interval])) by (le,keyspace_name,changefeed,stage))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}-p99", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot export and write wait latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Cumulative failed CSE commands, failed or canceled executions, and CSE command retries started.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 57 + }, + "hiddenSeries": false, + "id": 62209, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_errors_total{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) by (keyspace_name,changefeed,stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}-errors", + "refId": "A" + }, + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_retries_total{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) by (keyspace_name,changefeed,stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}-retries", + "refId": "B" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot failures and retries", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Latest execution attempt. Export begins after planning, apply begins at the first range, overall includes both. Pipeline stages overlap: do not add their durations.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 57 + }, + "hiddenSeries": false, + "id": 62210, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,keyspace_name,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,keyspace_name,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,keyspace_name,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-export", + "refId": "A" + }, + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,keyspace_name,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,keyspace_name,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,keyspace_name,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-apply", + "refId": "B" + }, + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,keyspace_name,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,keyspace_name,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,keyspace_name,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-overall", + "refId": "C" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot stage wall time", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + } + ], + "title": "Snapshot", + "type": "row" } ], "refresh": "10s", @@ -29396,7 +30411,7 @@ "value": "$__all" }, "datasource": "${DS_TEST-CLUSTER}", - "definition": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, keyspace_name)", + "definition": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, keyspace_name)", "description": null, "error": null, "hide": 0, @@ -29406,7 +30421,7 @@ "name": "keyspace_name", "options": [], "query": { - "query": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, keyspace_name)", + "query": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, keyspace_name)", "refId": "StandardVariableQuery" }, "refresh": 2, @@ -29427,7 +30442,7 @@ "value": "$__all" }, "datasource": "${DS_TEST-CLUSTER}", - "definition": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, changefeed)", + "definition": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, changefeed)", "description": null, "error": null, "hide": 0, @@ -29437,7 +30452,7 @@ "name": "changefeed", "options": [], "query": { - "query": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, changefeed)", + "query": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\"}, changefeed)", "refId": "StandardVariableQuery" }, "refresh": 2, diff --git a/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json b/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json index 05725e3f74..ce5aad7c63 100644 --- a/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json +++ b/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json @@ -12606,6 +12606,1021 @@ ], "title": "Kafka Sink V2", "type": "row" + }, + { + "collapsed": true, + "datasource": { + "type": "datasource", + "uid": "grafana" + }, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 28 + }, + "id": 62200, + "panels": [ + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Export counts validated published chunks; apply counts downstream PostFlush acknowledgments, including replay. Both use logical KV key+value bytes, not SST or sink wire bytes.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 29 + }, + "hiddenSeries": false, + "id": 62201, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(rate(ticdc_snapshot_bytes_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])) by (keyspace_name, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot KV throughput", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "Bps", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Rows published by export or acknowledged by the sink. Replayed writes count again.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 29 + }, + "hiddenSeries": false, + "id": 62202, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(rate(ticdc_snapshot_rows_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])) by (keyspace_name, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot rows", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ops", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Active CSE commands and active range apply workers, including time waiting for their sink acknowledgments.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 36 + }, + "hiddenSeries": false, + "id": 62203, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_active_workers{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) by (keyspace_name, changefeed, stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot active workers", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Committed ranges have durable sink acknowledgments. Ready ranges include ranges currently being applied.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 36 + }, + "hiddenSeries": false, + "id": 62204, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",kind=~\"total_ranges|committed_ranges|ready_ranges\"}) by (keyspace_name, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot range progress", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Shared budget covers mounted rows awaiting sink ACKs. Input chunks and sink internal buffers are additional memory; this is not process RSS.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 43 + }, + "hiddenSeries": false, + "id": 62205, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",kind=~\"inflight_bytes|write_memory_quota_bytes\"}) by (keyspace_name, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot write memory", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Sampled artifact usage during CSE commands, including partial attempts. The last sample remains after commands stop; this is not a filesystem hard quota.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 43 + }, + "hiddenSeries": false, + "id": 62206, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max(ticdc_snapshot_resource{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",kind=~\"artifact_disk_bytes|disk_quota_bytes\"}) by (keyspace_name, changefeed, kind)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{kind}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot artifact disk", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Batch enqueue to PostFlush acknowledgment, including queueing, encoding, transmission and confirmation.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 50 + }, + "hiddenSeries": false, + "id": 62207, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "histogram_quantile(0.99,sum(rate(ticdc_snapshot_operation_duration_seconds_bucket{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"sink_ack\"}[$__rate_interval])) by (le,keyspace_name,changefeed))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-p99", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot sink acknowledgment latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "CSE command duration and shared write-budget acquisition duration.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 50 + }, + "hiddenSeries": false, + "id": 62208, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "histogram_quantile(0.99,sum(rate(ticdc_snapshot_operation_duration_seconds_bucket{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=~\"plan|materialize-range|write_budget_wait\"}[$__rate_interval])) by (le,keyspace_name,changefeed,stage))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}-p99", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot export and write wait latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Cumulative failed CSE commands, failed or canceled executions, and CSE command retries started.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 57 + }, + "hiddenSeries": false, + "id": 62209, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_errors_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) by (keyspace_name,changefeed,stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}-errors", + "refId": "A" + }, + { + "exemplar": true, + "expr": "sum(ticdc_snapshot_retries_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) by (keyspace_name,changefeed,stage)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-{{stage}}-retries", + "refId": "B" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot failures and retries", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Latest execution attempt. Export begins after planning, apply begins at the first range, overall includes both. Pipeline stages overlap: do not add their durations.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 57 + }, + "hiddenSeries": false, + "id": 62210, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,keyspace_name,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,keyspace_name,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"export\"}) by (instance,keyspace_name,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-export", + "refId": "A" + }, + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,keyspace_name,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,keyspace_name,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"apply\"}) by (instance,keyspace_name,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-apply", + "refId": "B" + }, + { + "exemplar": true, + "expr": "((max(ticdc_snapshot_stage_finished_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,keyspace_name,changefeed) > 0) or (0 * max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,keyspace_name,changefeed) + time())) - max(ticdc_snapshot_stage_started_timestamp_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\",stage=\"overall\"}) by (instance,keyspace_name,changefeed)", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-overall", + "refId": "C" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot stage wall time", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + } + ], + "title": "Snapshot", + "type": "row" } ], "refresh": "10s", @@ -12686,7 +13701,7 @@ "value": "$__all" }, "datasource": "${DS_TEST-CLUSTER}", - "definition": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, keyspace_name)", + "definition": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, keyspace_name)", "description": null, "error": null, "hide": 0, @@ -12696,7 +13711,7 @@ "name": "keyspace_name", "options": [], "query": { - "query": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, keyspace_name)", + "query": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, keyspace_name)", "refId": "StandardVariableQuery" }, "refresh": 2, @@ -12717,7 +13732,7 @@ "value": "$__all" }, "datasource": "${DS_TEST-CLUSTER}", - "definition": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", + "definition": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", "description": null, "error": null, "hide": 0, @@ -12727,7 +13742,7 @@ "name": "changefeed", "options": [], "query": { - "query": "label_values(ticdc_owner_checkpoint_ts_lag{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", + "query": "label_values({__name__=~\"ticdc_owner_checkpoint_ts_lag|ticdc_snapshot_rows_total\", k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\"}, changefeed)", "refId": "StandardVariableQuery" }, "refresh": 2, diff --git a/pkg/common/event/dml_event.go b/pkg/common/event/dml_event.go index cbbd09ea9c..18b2cd3615 100644 --- a/pkg/common/event/dml_event.go +++ b/pkg/common/event/dml_event.go @@ -377,8 +377,6 @@ func (b *BatchDMLEvent) DMLCount() int { // DMLEvent represent a batch of DMLs of a whole or partial of a transaction. type DMLEvent struct { - // Snapshot is local capture metadata; never transported through EventStore. - Snapshot *SnapshotRow `json:"-"` // Version is the version of the DMLEvent struct. Version int `json:"version"` DispatcherID common.DispatcherID `json:"dispatcher_id"` diff --git a/pkg/common/event/row_change.go b/pkg/common/event/row_change.go index da85a8db95..1d16eb358a 100644 --- a/pkg/common/event/row_change.go +++ b/pkg/common/event/row_change.go @@ -88,14 +88,7 @@ type TopicPartitionKey struct { TotalPartition int32 } -type SnapshotRow struct { - ID string - SnapshotID string - Timestamp uint64 -} - type RowEvent struct { - Snapshot *SnapshotRow PhysicalTableID int64 TableInfo *common.TableInfo StartTs uint64 diff --git a/pkg/config/changefeed.go b/pkg/config/changefeed.go index 262fd0c329..f99248b017 100644 --- a/pkg/config/changefeed.go +++ b/pkg/config/changefeed.go @@ -242,6 +242,9 @@ func (cfg *ChangefeedConfig) String() string { return "" } cloned.SinkURI = util.MaskSensitiveDataInURI(cloned.SinkURI) + if cloned.Snapshot != nil { + cloned.Snapshot.BackupURI = util.MaskSensitiveDataInURI(cloned.Snapshot.BackupURI) + } if cloned.SinkConfig != nil { cloned.SinkConfig.MaskSensitiveData() } diff --git a/pkg/config/changefeed_test.go b/pkg/config/changefeed_test.go index e82f0e36be..5b40c68a41 100644 --- a/pkg/config/changefeed_test.go +++ b/pkg/config/changefeed_test.go @@ -19,6 +19,7 @@ import ( "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/util" "github.com/stretchr/testify/require" ) @@ -215,6 +216,7 @@ func TestChangeFeedInfoToChangefeedConfigIntegrity(t *testing.T) { func TestChangeFeedInfoStringMasksSensitiveData(t *testing.T) { cfg := GetDefaultReplicaConfig() + cfg.Snapshot = &protocol.Config{BackupURI: "s3://bucket/backup?secret-key=snapshot-secret-sentinel"} cfg.Sink.SchemaRegistry = util.AddressOf("https://registry.example.com?access-key=registry-secret-sentinel") cfg.Sink.PulsarConfig = &PulsarConfig{ OAuth2: &OAuth2{OAuth2IssuerURL: "https://user:pulsar-issuer-secret-sentinel@oauth.example.com"}, @@ -244,6 +246,7 @@ func TestChangeFeedInfoStringMasksSensitiveData(t *testing.T) { "sink-password-sentinel", "uri-secret-sentinel", "registry-secret-sentinel", + "snapshot-secret-sentinel", "plain-password-sentinel", "gssapi-password-sentinel", "oauth-secret-sentinel", @@ -270,6 +273,7 @@ func TestChangefeedConfigStringMasksSensitiveData(t *testing.T) { SASLPassword: new("plain-password-sentinel"), } changefeedConfig := &ChangefeedConfig{ + Snapshot: &protocol.Config{BackupURI: "s3://bucket/backup?secret-key=snapshot-secret-sentinel"}, SinkURI: "mysql://user:sink-password-sentinel@127.0.0.1:3306/?secret=uri-secret-sentinel", SinkConfig: cfg.Sink, } @@ -281,6 +285,7 @@ func TestChangefeedConfigStringMasksSensitiveData(t *testing.T) { "sink-password-sentinel", "uri-secret-sentinel", "plain-password-sentinel", + "snapshot-secret-sentinel", } { require.NotContains(t, output, secret) } diff --git a/pkg/config/replica_config.go b/pkg/config/replica_config.go index 8c5f34ed7c..88c8210a59 100644 --- a/pkg/config/replica_config.go +++ b/pkg/config/replica_config.go @@ -460,6 +460,9 @@ func (c *ReplicaConfig) FixMemoryQuota() { // MaskSensitiveData masks sensitive data in ReplicaConfig func (c *ReplicaConfig) MaskSensitiveData() { + if c.Snapshot != nil { + c.Snapshot.BackupURI = util.MaskSensitiveDataInURI(c.Snapshot.BackupURI) + } if c.Sink != nil { c.Sink.MaskSensitiveData() } diff --git a/pkg/config/server.go b/pkg/config/server.go index 34a319958b..e68ca90e2f 100644 --- a/pkg/config/server.go +++ b/pkg/config/server.go @@ -103,11 +103,11 @@ var defaultServerConfig = &ServerConfig{ }, InternalErrOutput: "stderr", }, - DataDir: "", - SnapshotExportWorkers: 1, - SnapshotMinFreeBytes: 10 << 30, - GcTTL: 24 * 60 * 60, // 24H - TZ: "System", + DataDir: "", + SnapshotMinFreeBytes: 10 << 30, + SnapshotCSEBinary: "/usr/local/bin/cse-ctl", + GcTTL: 24 * 60 * 60, // 24H + TZ: "System", // Disabled by default. When enabled in next-gen mode, TiCDC uses // service safepoint v2 instead of GC barriers. EnableLegacySafePoint: false, @@ -154,10 +154,8 @@ type ServerConfig struct { // SnapshotCSEBinary enables the embedded local CSE packed-backup exporter. // It is a server setting, never a changefeed-provided executable path. - SnapshotCSEBinary string `toml:"snapshot-cse-binary" json:"snapshot-cse-binary"` - SnapshotArtifactDir string `toml:"snapshot-artifact-dir" json:"snapshot-artifact-dir"` - SnapshotExportWorkers int `toml:"snapshot-export-workers" json:"snapshot-export-workers"` - SnapshotMinFreeBytes int64 `toml:"snapshot-min-free-bytes" json:"snapshot-min-free-bytes"` + SnapshotCSEBinary string `toml:"snapshot-cse-binary" json:"snapshot-cse-binary"` + SnapshotMinFreeBytes int64 `toml:"snapshot-min-free-bytes" json:"snapshot-min-free-bytes"` GcTTL int64 `toml:"gc-ttl" json:"gc-ttl"` TZ string `toml:"tz" json:"tz"` @@ -266,17 +264,11 @@ func (c *ServerConfig) Clone() *ServerConfig { // ValidateAndAdjust validates and adjusts the server configuration func (c *ServerConfig) ValidateAndAdjust() error { - if c.SnapshotExportWorkers == 0 { - c.SnapshotExportWorkers = 1 - } - if c.SnapshotExportWorkers < 1 || c.SnapshotExportWorkers > 32 { - return cerror.ErrInvalidServerOption.GenWithStack("snapshot-export-workers must be between 1 and 32") - } if c.SnapshotMinFreeBytes < 0 { return cerror.ErrInvalidServerOption.GenWithStack("snapshot-min-free-bytes cannot be negative") } - if c.SnapshotCSEBinary != "" && (!filepath.IsAbs(c.SnapshotCSEBinary) || !filepath.IsAbs(c.SnapshotArtifactDir)) { - return cerror.ErrInvalidServerOption.GenWithStack("embedded snapshot requires absolute snapshot-cse-binary and snapshot-artifact-dir paths") + if c.SnapshotCSEBinary != "" && !filepath.IsAbs(c.SnapshotCSEBinary) { + return cerror.ErrInvalidServerOption.GenWithStack("snapshot-cse-binary must be an absolute path") } if !isValidClusterID(c.ClusterID) { return cerror.ErrInvalidServerOption.GenWithStack(fmt.Sprintf("bad cluster-id"+ diff --git a/pkg/messaging/message.go b/pkg/messaging/message.go index f159580fec..b389460835 100644 --- a/pkg/messaging/message.go +++ b/pkg/messaging/message.go @@ -28,6 +28,7 @@ import ( "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/integrity" "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/util" "go.uber.org/zap" ) @@ -110,6 +111,7 @@ const ( TypeSetNodeLivenessResponse IOType = 44 TypeSetDispatcherDrainTargetRequest IOType = 45 TypeNodeHeartbeatResponse IOType = 46 + TypeSnapshot IOType = 50 TypeEventBrokerDispatcherCount IOType = 47 TypeEventBrokerDispatcherCountRequest IOType = 48 TypeEventBrokerDispatcherCountResponse IOType = 49 @@ -117,6 +119,8 @@ const ( func (t IOType) String() string { switch t { + case TypeSnapshot: + return "Snapshot" case TypeEventBrokerDispatcherCount: return "EventBrokerDispatcherCount" case TypeEventBrokerDispatcherCountRequest: @@ -325,6 +329,8 @@ type IOTypeT interface { func decodeIOType(ioType IOType, value []byte) (IOTypeT, error) { var m IOTypeT switch ioType { + case TypeSnapshot: + m = &protocol.Message{} case TypeBatchDMLEvent: m = &commonEvent.BatchDMLEvent{} case TypeDDLEvent: @@ -455,6 +461,8 @@ type TargetMessage struct { func NewSingleTargetMessage(To node.ID, Topic string, Message IOTypeT, Group ...uint64) *TargetMessage { var ioType IOType switch Message.(type) { + case *protocol.Message: + ioType = TypeSnapshot case *commonEvent.BatchDMLEvent: ioType = TypeBatchDMLEvent case *commonEvent.DDLEvent: diff --git a/pkg/messaging/message_snapshot_test.go b/pkg/messaging/message_snapshot_test.go new file mode 100644 index 0000000000..c384f72db1 --- /dev/null +++ b/pkg/messaging/message_snapshot_test.go @@ -0,0 +1,22 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package messaging + +import ( + "fmt" + "testing" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestSnapshotControlMessageRoundTripAndSafeDisplay(t *testing.T) { + original := &protocol.Message{RequestID: "request", Payload: []byte("test-only-credential")} + msg := NewSingleTargetMessage("node", "snapshot", original) + require.Equal(t, TypeSnapshot, msg.Type) + encoded, err := original.Marshal() + require.NoError(t, err) + decoded, err := decodeIOType(msg.Type, encoded) + require.NoError(t, err) + require.Equal(t, original, decoded) + require.NotContains(t, fmt.Sprint(msg), "test-only-credential") +} diff --git a/pkg/metrics/init.go b/pkg/metrics/init.go index 79e5cedc68..66c7e2a10e 100644 --- a/pkg/metrics/init.go +++ b/pkg/metrics/init.go @@ -46,6 +46,7 @@ func InitMetrics(registry *prometheus.Registry) { metrics.InitCloudStorageMetrics(registry) initRedoMetrics(registry) initDDLMetrics(registry) + initSnapshotMetrics(registry) } // GetKeyspaceLabel returns the keyspace label name used by TiCDC metrics. diff --git a/pkg/metrics/snapshot.go b/pkg/metrics/snapshot.go new file mode 100644 index 0000000000..118390f8fa --- /dev/null +++ b/pkg/metrics/snapshot.go @@ -0,0 +1,104 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package metrics + +import ( + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +var snapshotLabels = []string{GetKeyspaceLabel(), "changefeed", "stage"} + +var ( + snapshotRetries = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "retries_total", Help: "CSE command retries started after a failed attempt."}, snapshotLabels) + snapshotBytes = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "bytes_total", Help: "Logical KV bytes published by export or acknowledged by the sink, including replayed writes."}, snapshotLabels) + snapshotRows = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "rows_total", Help: "KV rows published by export or acknowledged by the sink, including replayed writes."}, snapshotLabels) + snapshotStarted = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "stage_started_timestamp_seconds", Help: "Start of the latest execution attempt's stage. Export and apply overlap."}, snapshotLabels) + snapshotFinished = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "stage_finished_timestamp_seconds", Help: "Successful finish of the latest execution attempt's stage; zero while unfinished."}, snapshotLabels) + snapshotWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "active_workers", Help: "Active CSE commands or range apply workers."}, snapshotLabels) + snapshotDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "operation_duration_seconds", Help: "CSE command, shared write-budget acquisition, and batch enqueue-to-ACK duration.", Buckets: prometheus.ExponentialBuckets(0.001, 4, 11)}, snapshotLabels) + snapshotErrors = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "errors_total", Help: "Failed CSE commands or snapshot executions. Canceled executions are included."}, snapshotLabels) + snapshotCPU = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "cse_cpu_seconds_total", Help: "Completed CSE commands' user and system CPU seconds."}, []string{GetKeyspaceLabel(), "changefeed"}) + snapshotValues = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "resource", Help: "Snapshot resource/progress values; kind identifies bytes, configured limits, or range counts."}, []string{GetKeyspaceLabel(), "changefeed", "kind"}) +) + +func initSnapshotMetrics(r *prometheus.Registry) { + r.MustRegister(snapshotBytes, snapshotRows, snapshotStarted, snapshotFinished, snapshotWorkers, snapshotDuration, snapshotErrors, snapshotRetries, snapshotCPU, snapshotValues) +} + +// SnapshotStatistics is shared by one executor's exporter, controller and sink. +// Nil statistics allow package-local users to run without instrumentation. +type SnapshotStatistics struct{ keyspace, changefeed string } + +func NewSnapshotStatistics(keyspace, changefeed string) *SnapshotStatistics { + return &SnapshotStatistics{keyspace: keyspace, changefeed: changefeed} +} + +func (s *SnapshotStatistics) Start(stage string) { + if s == nil { + return + } + snapshotStarted.WithLabelValues(s.keyspace, s.changefeed, stage).SetToCurrentTime() + snapshotFinished.WithLabelValues(s.keyspace, s.changefeed, stage).Set(0) + snapshotBytes.WithLabelValues(s.keyspace, s.changefeed, stage).Add(0) + snapshotRows.WithLabelValues(s.keyspace, s.changefeed, stage).Add(0) +} + +func (s *SnapshotStatistics) Finish(stage string) { + if s != nil { + snapshotFinished.WithLabelValues(s.keyspace, s.changefeed, stage).SetToCurrentTime() + } +} + +func (s *SnapshotStatistics) Output(stage string, bytes, rows uint64) { + if s == nil { + return + } + snapshotBytes.WithLabelValues(s.keyspace, s.changefeed, stage).Add(float64(bytes)) + snapshotRows.WithLabelValues(s.keyspace, s.changefeed, stage).Add(float64(rows)) +} + +func (s *SnapshotStatistics) Worker(stage string, delta float64) { + if s != nil { + snapshotWorkers.WithLabelValues(s.keyspace, s.changefeed, stage).Add(delta) + } +} + +func (s *SnapshotStatistics) Observe(operation string, elapsed time.Duration) { + if s != nil { + snapshotDuration.WithLabelValues(s.keyspace, s.changefeed, operation).Observe(elapsed.Seconds()) + } +} + +func (s *SnapshotStatistics) Error(stage string) { + if s != nil { + snapshotErrors.WithLabelValues(s.keyspace, s.changefeed, stage).Inc() + } +} + +func (s *SnapshotStatistics) Set(kind string, value float64) { + if s != nil { + snapshotValues.WithLabelValues(s.keyspace, s.changefeed, kind).Set(value) + } +} + +func (s *SnapshotStatistics) Add(kind string, delta float64) { + if s != nil { + snapshotValues.WithLabelValues(s.keyspace, s.changefeed, kind).Add(delta) + } +} + +func (s *SnapshotStatistics) Process(cpu float64, peakRSS int64) { + if s == nil { + return + } + snapshotCPU.WithLabelValues(s.keyspace, s.changefeed).Add(cpu) + // Per-command peak, rather than a sum of non-concurrent high-water marks. + s.Set("last_cse_peak_rss_bytes", float64(peakRSS)) +} + +func (s *SnapshotStatistics) Retry(operation string) { + if s != nil { + snapshotRetries.WithLabelValues(s.keyspace, s.changefeed, operation).Inc() + } +} diff --git a/pkg/sink/codec/open/codec.go b/pkg/sink/codec/open/codec.go index 0331572919..64277de123 100644 --- a/pkg/sink/codec/open/codec.go +++ b/pkg/sink/codec/open/codec.go @@ -45,11 +45,7 @@ func encodeRowChangedEvent( keyWriter.WriteObject(func() { keyWriter.WriteUint64Field("ts", e.CommitTs) - if e.Snapshot != nil { - keyWriter.WriteStringField("snapshot_record_id", e.Snapshot.ID) - keyWriter.WriteStringField("snapshot_id", e.Snapshot.SnapshotID) - keyWriter.WriteUint64Field("snapshot_ts", e.Snapshot.Timestamp) - } + keyWriter.WriteStringField("scm", e.TableInfo.GetTargetSchemaName()) keyWriter.WriteStringField("tbl", e.TableInfo.GetTargetTableName()) keyWriter.WriteIntField("t", int(common.MessageTypeRow)) diff --git a/pkg/sink/codec/open/snapshot_test.go b/pkg/sink/codec/open/snapshot_test.go deleted file mode 100644 index 63ed043cdc..0000000000 --- a/pkg/sink/codec/open/snapshot_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package open - -import ( - "testing" - - "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" - commonEvent "github.com/pingcap/ticdc/pkg/common/event" - "github.com/pingcap/ticdc/pkg/config" - "github.com/pingcap/ticdc/pkg/sink/codec/common" - "github.com/stretchr/testify/require" -) - -func TestSnapshotEnvelopeKeepsIdentityWithoutInlineSchema(t *testing.T) { - helper := commonEvent.NewEventTestHelper(t) - defer helper.Close() - helper.DDL2Job("create table test.snap (id int primary key, v int)") - event := helper.DML2Event("test", "snap", "insert into test.snap values(1,10)") - row, ok := event.GetNextRow() - require.True(t, ok) - e := &commonEvent.RowEvent{PhysicalTableID: event.PhysicalTableID, TableInfo: event.TableInfo, Event: row, CommitTs: 42, ColumnSelector: columnselector.NewDefaultColumnSelector(), Snapshot: &commonEvent.SnapshotRow{ID: "stable", SnapshotID: "generation", Timestamp: 42}} - key, _, _, err := encodeRowChangedEvent(e, initColumnFlags(e.TableInfo), common.NewConfig(config.ProtocolOpen), false, "") - require.NoError(t, err) - require.Contains(t, string(key), `"snapshot_record_id":"stable"`) - require.NotContains(t, string(key), "snapshot_schema") - require.Contains(t, string(key), `"snapshot_id":"generation"`) - require.Contains(t, string(key), `"snapshot_ts":42`) - e.Snapshot = nil - key, _, _, err = encodeRowChangedEvent(e, initColumnFlags(e.TableInfo), common.NewConfig(config.ProtocolOpen), false, "") - require.NoError(t, err) - require.NotContains(t, string(key), "snapshot_record_id") -} diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go index d04f99f7ba..ae89eaeed4 100644 --- a/pkg/snapshot/bootstrap/controller.go +++ b/pkg/snapshot/bootstrap/controller.go @@ -3,6 +3,7 @@ package bootstrap import ( "context" + "encoding/json" "os" "path/filepath" "sync" @@ -11,25 +12,27 @@ import ( "github.com/google/uuid" "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/metrics" + "github.com/pingcap/ticdc/pkg/snapshot/exporter" "github.com/pingcap/ticdc/pkg/snapshot/protocol" - "github.com/pingcap/ticdc/pkg/snapshot/provider" "github.com/pingcap/ticdc/pkg/snapshot/store" "golang.org/x/sync/errgroup" ) type Controller struct { - ID common.ChangeFeedID - Epoch uint64 - TS uint64 - Keyspace uint32 - Config *protocol.Config - ArtifactDir string - CSEBinary string - ExportWorkers int - MinFreeBytes int64 - Repository Repository - Capture Capture - Freeze func() (SchemaBundle, []protocol.Span, error) + Statistics *metrics.SnapshotStatistics + DestinationDigest string + ID common.ChangeFeedID + Epoch uint64 + TS uint64 + Keyspace uint32 + Config *protocol.Config + ArtifactDir string + CSEBinary string + MinFreeBytes int64 + Repository Repository + Capture Capture + Freeze func() (SchemaBundle, []protocol.Span, error) } func (c Controller) Run(ctx context.Context) (result error) { @@ -37,9 +40,6 @@ func (c Controller) Run(ctx context.Context) (result error) { return err } artifactDir := c.ArtifactDir - if artifactDir == "" { - artifactDir = c.Config.ArtifactDir - } objects := store.Local{Root: artifactDir} dir := filepath.Join(objects.Root, "cdc", c.ID.ID().String()) if err := os.MkdirAll(dir, 0o700); err != nil { @@ -65,7 +65,7 @@ func (c Controller) Run(ctx context.Context) (result error) { if err != nil { return err } - if state != nil && state.Marker != nil { + if state != nil && state.Phase == "SNAPSHOT_COMMITTED" { return nil } if state == nil { @@ -76,11 +76,26 @@ func (c Controller) Run(ctx context.Context) (result error) { } } save := func() error { return c.Repository.SaveSnapshot(ctx, c.ID, c.Epoch, state) } + bundle, spans, err := c.Freeze() + if err != nil { + return err + } + input, err := json.Marshal(struct { + BackupURI, BackupDigest string + DestinationDigest string + Keyspace uint32 + Bundle SchemaBundle + Spans []protocol.Span + }{c.Config.BackupURI, c.Config.BackupDigest, c.DestinationDigest, c.Keyspace, bundle, spans}) + if err != nil { + return protocol.Wrap(err) + } + digest := protocol.Digest(input) + if state.InputDigest != "" && state.InputDigest != digest { + return protocol.Invalid("frozen snapshot input changed") + } + state.InputDigest = digest if state.SpecRef.URI == "" { - bundle, spans, err := c.Freeze() - if err != nil { - return err - } schema, err := objects.Put("cdc/"+state.Generation+"/schema.json", bundle) if err != nil { return err @@ -99,19 +114,18 @@ func (c Controller) Run(ctx context.Context) (result error) { if err = protocol.Read(state.SpecRef, &spec); err != nil { return err } - var client provider.Caller = provider.Client{URL: c.Config.ProviderURL} - if c.Config.ProviderURL == "" { - if c.CSEBinary == "" { - return protocol.Invalid("embedded snapshot export requires a configured CSE binary") - } - local := provider.New(artifactDir, c.CSEBinary) - local.Workers = c.ExportWorkers - local.MinFreeBytes = c.MinFreeBytes - defer local.Close() - client = provider.LocalClient{Server: local} + if c.CSEBinary == "" { + return protocol.Invalid("snapshot export requires a configured CSE binary") } - var job provider.Job - if err = client.Call(ctx, "ensure", provider.Request{SpecRef: state.SpecRef}, &job); err != nil { + local := exporter.New(artifactDir, c.CSEBinary) + local.Statistics = c.Statistics + local.Workers = c.Config.ExportConcurrency() + local.MinFreeBytes = c.MinFreeBytes + local.ReadMemoryQuota = c.Config.ReadLimit() + local.DiskQuota = c.Config.DiskLimit() + defer local.Close() + job, err := local.Ensure(state.SpecRef) + if err != nil { return err } wait := func() error { @@ -129,7 +143,7 @@ func (c Controller) Run(ctx context.Context) (result error) { if err = wait(); err != nil { return err } - if err = client.Call(ctx, "status", provider.Request{JobID: spec.JobID}, &job); err != nil { + if job, err = local.Status(spec.JobID); err != nil { return err } } @@ -145,7 +159,8 @@ func (c Controller) Run(ctx context.Context) (result error) { } state.PlanRef = job.PlanRef state.Total = len(plan.Ranges) - state.Barrier = true + c.Statistics.Set("total_ranges", float64(state.Total)) + c.Statistics.Set("committed_ranges", float64(state.Applied)) state.Phase = "APPLYING" if err = save(); err != nil { return err @@ -154,7 +169,7 @@ func (c Controller) Run(ctx context.Context) (result error) { if err = tasks.Init(); err != nil { return err } - if c.Config.ProviderURL == "" { + { if err = cleanupAppliedChunks(artifactDir, spec.JobID, tasks); err != nil { return err } @@ -174,19 +189,22 @@ func (c Controller) Run(ctx context.Context) (result error) { ready = append(ready, task) } } + c.Statistics.Set("ready_ranges", float64(len(ready))) + c.Statistics.Set("committed_ranges", float64(applied)) if err = c.applyReady(ctx, tasks, spec, state.PlanRef, ready); err != nil { return err } applied += len(ready) state.Applied = applied + c.Statistics.Set("committed_ranges", float64(applied)) if err = save(); err != nil { return err } if complete && applied == len(plan.Ranges) { break } - var page provider.Page - if err = client.Call(ctx, "list", provider.Request{JobID: spec.JobID, Cursor: state.Cursor, Limit: 64}, &page); err != nil { + page, err := local.List(spec.JobID, state.Cursor, 64) + if err != nil { return err } for _, ref := range page.Exports { @@ -205,7 +223,7 @@ func (c Controller) Run(ctx context.Context) (result error) { } } if !found { - return protocol.Invalid("provider returned unknown range") + return protocol.Invalid("exporter returned unknown range") } if err = tasks.Ready(ex.Range.RangeID, ref); err != nil { return err @@ -218,7 +236,7 @@ func (c Controller) Run(ctx context.Context) (result error) { return err } if len(page.Exports) == 0 { - if err = client.Call(ctx, "status", provider.Request{JobID: spec.JobID}, &job); err != nil { + if job, err = local.Status(spec.JobID); err != nil { return err } if job.Phase == "FAILED" || job.Phase == "CANCELED" { @@ -233,6 +251,7 @@ func (c Controller) Run(ctx context.Context) (result error) { if err = save(); err != nil { return err } + local.Close() // Join export workers before closing the sink and committing. if err = c.Capture.DrainSnapshot(ctx, c.ID, c.Epoch); err != nil { return err } @@ -245,7 +264,6 @@ func (c Controller) Run(ctx context.Context) (result error) { return protocol.Invalid("incomplete exact range receipts") } } - state.Marker = &protocol.Marker{SnapshotTS: spec.SnapshotTS, SnapshotID: spec.SnapshotID, OutputFence: "single-capture-all-broker-acks"} state.Phase = "SNAPSHOT_COMMITTED" return save() } @@ -298,11 +316,15 @@ func (c Controller) applyReady(ctx context.Context, tasks store.Tasks, spec prot } taskMu.Lock() err = tasks.Commit(task.Range.RangeID, assigned.Lease, rows) + if err == nil { + c.Statistics.Add("committed_ranges", 1) + c.Statistics.Add("ready_ranges", -1) + } taskMu.Unlock() if err != nil { return err } - if c.Config.ProviderURL == "" { + { if err = removeExportChunks(c.artifactDir(), spec.JobID, ex); err != nil { return err } @@ -314,9 +336,4 @@ func (c Controller) applyReady(ctx context.Context, tasks store.Tasks, spec prot return group.Wait() } -func (c Controller) artifactDir() string { - if c.ArtifactDir != "" { - return c.ArtifactDir - } - return c.Config.ArtifactDir -} +func (c Controller) artifactDir() string { return c.ArtifactDir } diff --git a/pkg/snapshot/bootstrap/controller_test.go b/pkg/snapshot/bootstrap/controller_test.go index 7b0203ff5a..f5a8bd2b50 100644 --- a/pkg/snapshot/bootstrap/controller_test.go +++ b/pkg/snapshot/bootstrap/controller_test.go @@ -4,6 +4,8 @@ package bootstrap import ( "context" "fmt" + "os" + "path/filepath" "sync/atomic" "testing" "time" @@ -103,3 +105,58 @@ func TestApplyReadyBoundedReceiptsAndCancellation(t *testing.T) { }) } } + +func TestControllerRecoversCommitFailureWithoutReexport(t *testing.T) { + root := t.TempDir() + binary := filepath.Join(root, "cse") + script := `#!/usr/bin/env python3 +import sys,json,pathlib +p=pathlib.Path(sys.argv[sys.argv.index('--task-spec')+1]);t=json.loads(p.read_text());s=t['spec'] +if sys.argv[2]!='plan': raise RuntimeError('must not materialize empty plan') +plan={k:s[k] for k in ('protocol_version','job_id','snapshot_id','snapshot_ts')};plan['ranges']=[] +(pathlib.Path(t['output_dir'])/'plan.json').write_text(json.dumps(plan)) +` + require.NoError(t, os.WriteFile(binary, []byte(script), 0o700)) + ctrl := gomock.NewController(t) + repo := NewMockRepository(ctrl) + capture := NewMockCapture(ctrl) + id := common.NewChangeFeedIDWithName("empty", common.DefaultKeyspaceName) + var saved *protocol.State + repo.EXPECT().LoadSnapshot(gomock.Any(), id, uint64(1)).DoAndReturn(func(context.Context, common.ChangeFeedID, uint64) (*protocol.State, error) { + if saved == nil { + return nil, nil + } + s := *saved + return &s, nil + }).AnyTimes() + failCommit := true + drained := false + repo.EXPECT().SaveSnapshot(gomock.Any(), id, uint64(1), gomock.Any()).DoAndReturn(func(_ context.Context, _ common.ChangeFeedID, _ uint64, s *protocol.State) error { + if s.Phase == "SNAPSHOT_COMMITTED" { + require.True(t, drained) + require.Equal(t, s.Total, s.Applied) + if failCommit { + failCommit = false + return protocol.Invalid("commit interrupted") + } + } + copy := *s + saved = © + return nil + }).AnyTimes() + capture.EXPECT().DrainSnapshot(gomock.Any(), id, uint64(1)).DoAndReturn(func(context.Context, common.ChangeFeedID, uint64) error { drained = true; return nil }).Times(2) + capture.EXPECT().AbortSnapshot(id).Times(1) + c := Controller{ID: id, Epoch: 1, TS: 42, Config: &protocol.Config{BackupURI: "existing-backup"}, ArtifactDir: root, CSEBinary: binary, Repository: repo, Capture: capture, Freeze: func() (SchemaBundle, []protocol.Span, error) { return SchemaBundle{SnapshotTS: 42}, nil, nil }} + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + require.ErrorContains(t, c.Run(ctx), "commit interrupted") + require.Equal(t, "DRAINING", saved.Phase) + require.NoError(t, c.Run(ctx)) + require.Equal(t, "SNAPSHOT_COMMITTED", saved.Phase) + // A committed snapshot skips CSE, freeze and sink entirely. + c.Freeze = func() (SchemaBundle, []protocol.Span, error) { + t.Fatal("committed snapshot refrozen") + return SchemaBundle{}, nil, nil + } + require.NoError(t, c.Run(ctx)) +} diff --git a/pkg/snapshot/bootstrap/interfaces.go b/pkg/snapshot/bootstrap/interfaces.go index 2190b1834f..ad878cb808 100644 --- a/pkg/snapshot/bootstrap/interfaces.go +++ b/pkg/snapshot/bootstrap/interfaces.go @@ -8,10 +8,8 @@ import ( "github.com/pingcap/ticdc/pkg/snapshot/protocol" ) -const RepositoryService = "SnapshotRuntimeRepository" - -// Repository is implemented by Coordinator, using the existing changefeed -// runtime status key and ownership epoch. Mutate preserves concurrent fields. +// Repository persists into the existing changefeed runtime status and fences +// every mutation by its ownership epoch. It preserves concurrent status fields. type Repository interface { LoadSnapshot(context.Context, common.ChangeFeedID, uint64) (*protocol.State, error) SaveSnapshot(context.Context, common.ChangeFeedID, uint64, *protocol.State) error diff --git a/pkg/snapshot/exporter/cleanup.go b/pkg/snapshot/exporter/cleanup.go new file mode 100644 index 0000000000..dafa7cc168 --- /dev/null +++ b/pkg/snapshot/exporter/cleanup.go @@ -0,0 +1,68 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import ( + "os" + "path/filepath" + "strings" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +// The controller's writer lock and joined subprocesses make startup the safe +// point to remove interrupted attempts. Published winners may precede their +// journal entry, so inspect every durable winner rather than only Job.Exports. +func (s *Runner) cleanupAttempts(id string, j Job) error { + root := filepath.Join(s.Objects.Root, "br", id, "attempts") + keep := make(map[string]bool) + preserve := func(uri string) { + if uri == "" { + return + } + rel, err := filepath.Rel(root, uri) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return + } + parts := strings.Split(rel, string(os.PathSeparator)) + if len(parts) > 1 { + keep[parts[0]] = true + } + } + preserve(j.PlanRef.URI) + winners, err := os.ReadDir(filepath.Join(s.Objects.Root, "br", id, "range-exports")) + if err != nil && !os.IsNotExist(err) { + return protocol.Wrap(err) + } + for _, entry := range winners { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") { + continue + } + path := filepath.Join(s.Objects.Root, "br", id, "range-exports", entry.Name()) + ref, err := protocol.Ref(path) + if err != nil { + return err + } + var ex protocol.Export + if err = protocol.Read(ref, &ex); err != nil { + return err + } + for _, chunk := range ex.Chunks { + preserve(chunk.URI) + } + } + attempts, err := os.ReadDir(root) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return protocol.Wrap(err) + } + for _, entry := range attempts { + if !keep[entry.Name()] { + if err = os.RemoveAll(filepath.Join(root, entry.Name())); err != nil { + return protocol.Wrap(err) + } + } + } + return nil +} diff --git a/pkg/snapshot/exporter/cleanup_test.go b/pkg/snapshot/exporter/cleanup_test.go new file mode 100644 index 0000000000..3a887be6ca --- /dev/null +++ b/pkg/snapshot/exporter/cleanup_test.go @@ -0,0 +1,27 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import ( + "os" + "path/filepath" + "testing" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestCleanupPreservesUnjournaledWinnerAndAcceptedPlan(t *testing.T) { + s := New(t.TempDir(), "unused") + root := filepath.Join(s.Objects.Root, "br", "job", "attempts") + for _, name := range []string{"plan", "published", "interrupted"} { + require.NoError(t, os.MkdirAll(filepath.Join(root, name), 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(root, name, "file"), []byte("data"), 0o600)) + } + _, err := s.Objects.Put("br/job/range-exports/range.json", protocol.Export{Chunks: []protocol.Chunk{{ObjectRef: protocol.ObjectRef{URI: filepath.Join(root, "published", "file")}}}}) + require.NoError(t, err) + // Simulate death after winner publication but before append to Job.Exports. + require.NoError(t, s.cleanupAttempts("job", Job{PlanRef: protocol.ObjectRef{URI: filepath.Join(root, "plan", "file")}})) + require.FileExists(t, filepath.Join(root, "published", "file")) + require.FileExists(t, filepath.Join(root, "plan", "file")) + require.NoDirExists(t, filepath.Join(root, "interrupted")) +} diff --git a/pkg/snapshot/exporter/diagnostics.go b/pkg/snapshot/exporter/diagnostics.go new file mode 100644 index 0000000000..811ffb4f95 --- /dev/null +++ b/pkg/snapshot/exporter/diagnostics.go @@ -0,0 +1,62 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import ( + "bytes" + "net/url" + "os" + "strings" + + "github.com/pingcap/ticdc/pkg/util" +) + +// Child output is untrusted third-party diagnostics. Keep it bounded in memory, +// redact before writing any log, and omit incomplete lines at the buffer limit. +type diagnostics struct { + bytes.Buffer + backupURI string +} + +func (d *diagnostics) Write(p []byte) (int, error) { + n := len(p) + if remain := (64 << 10) - d.Len(); remain > 0 { + d.Buffer.Write(p[:min(len(p), remain)]) + } + return n, nil +} + +func (d *diagnostics) safe() []byte { + b := d.Bytes() + end := bytes.LastIndexByte(b, '\n') + if end < 0 { + return nil + } + text := string(b[:end+1]) + text = strings.ReplaceAll(text, d.backupURI, util.MaskSensitiveDataInURI(d.backupURI)) + var secrets []string + if uri, err := url.Parse(d.backupURI); err == nil { + if uri.User != nil { + if p, ok := uri.User.Password(); ok { + secrets = append(secrets, p) + } + } + for key, values := range uri.Query() { + for _, s := range []string{"password", "secret", "key", "token", "access", "signature", "credential"} { + if strings.Contains(strings.ToLower(key), s) { + secrets = append(secrets, values...) + break + } + } + } + } + for _, key := range []string{"DFS_S3_KEY_ID", "DFS_S3_SECRET_KEY", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"} { + secrets = append(secrets, os.Getenv(key)) + } + for _, secret := range secrets { + if secret != "" { + text = strings.ReplaceAll(text, secret, "[REDACTED]") + text = strings.ReplaceAll(text, url.QueryEscape(secret), "[REDACTED]") + } + } + return []byte(text) +} diff --git a/pkg/snapshot/exporter/disk.go b/pkg/snapshot/exporter/disk.go new file mode 100644 index 0000000000..9bdd648a93 --- /dev/null +++ b/pkg/snapshot/exporter/disk.go @@ -0,0 +1,65 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "time" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +func directoryUsage(root string) (int64, error) { + var bytes int64 + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if d.IsDir() { + return nil + } + info, err := d.Info() + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + bytes += info.Size() + return nil + }) + return bytes, protocol.Wrap(err) +} + +// Check during export as a range can exceed the admission reservation. Stop +// and discard its partial attempt instead of exhausting the shared CDC disk. +func (s *Runner) monitorDisk(ctx context.Context, cancel context.CancelCauseFunc) { + if s.DiskQuota == 0 { + <-ctx.Done() + return + } + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + used, err := directoryUsage(s.Objects.Root) + if err != nil { + cancel(err) + return + } + s.Statistics.Set("artifact_disk_bytes", float64(used)) + if used > s.DiskQuota { + cancel(protocol.Invalid("snapshot disk-quota exceeded; increase it to fit an exported range")) + return + } + } + } +} diff --git a/pkg/snapshot/exporter/disk_test.go b/pkg/snapshot/exporter/disk_test.go new file mode 100644 index 0000000000..59b9c683dd --- /dev/null +++ b/pkg/snapshot/exporter/disk_test.go @@ -0,0 +1,67 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" +) + +func TestDiskQuotaCountsTemporaryAttemptsAndCancels(t *testing.T) { + root := t.TempDir() + s := New(root, "unused") + s.DiskQuota = 1024 + require.NoError(t, os.MkdirAll(filepath.Join(root, "br", "job", "attempts", "partial"), 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(root, "br", "job", "attempts", "partial", "chunk.skv"), make([]byte, 2048), 0o600)) + used, err := directoryUsage(root) + require.NoError(t, err) + require.EqualValues(t, 2048, used) + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + done := make(chan struct{}) + go func() { s.monitorDisk(ctx, cancel); close(done) }() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("quota violation did not stop exporter") + } + require.ErrorContains(t, context.Cause(ctx), "disk-quota exceeded") +} + +func TestEnsureCanRecoverFailedJob(t *testing.T) { + s := New(t.TempDir(), "unused") + defer s.Close() + spec := protocol.Spec{ProtocolVersion: 1, JobID: "retry", SnapshotID: "s", SnapshotTS: 42} + ref, err := s.Objects.Put("spec", spec) + require.NoError(t, err) + planRef, err := s.Objects.Put("plan", protocol.Plan{ProtocolVersion: 1, JobID: "retry", SnapshotID: "s", SnapshotTS: 42}) + require.NoError(t, err) + _, err = s.Objects.Put(key("retry"), Job{Spec: spec, SpecRef: ref, PlanRef: planRef, Phase: "FAILED", Error: "old attempt failed"}) + require.NoError(t, err) + j, err := s.Ensure(ref) + require.NoError(t, err) + require.NotEqual(t, "FAILED", j.Phase) + require.Empty(t, j.Error) + require.Eventually(t, func() bool { + var got Job + _, err := s.Objects.Read(key("retry"), &got) + return err == nil && got.Phase == "SOURCE_COMPLETE" + }, 3*time.Second, 10*time.Millisecond) +} + +func TestChildDiagnosticsMaskSecretsAndBoundOutput(t *testing.T) { + t.Setenv("DFS_S3_SECRET_KEY", "test-only-env-secret") + d := &diagnostics{backupURI: "s3://bucket/path?secret-key=test-only-uri-secret"} + _, err := d.Write([]byte("failure test-only-env-secret s3://bucket/path?secret-key=test-only-uri-secret\n")) + require.NoError(t, err) + require.NotContains(t, string(d.safe()), "test-only-env-secret") + require.NotContains(t, string(d.safe()), "test-only-uri-secret") + _, err = d.Write(make([]byte, 128<<10)) + require.NoError(t, err) + require.LessOrEqual(t, d.Len(), 64<<10) +} diff --git a/pkg/snapshot/provider/provider.go b/pkg/snapshot/exporter/exporter.go similarity index 68% rename from pkg/snapshot/provider/provider.go rename to pkg/snapshot/exporter/exporter.go index 182d6dd1de..7081fea317 100644 --- a/pkg/snapshot/provider/provider.go +++ b/pkg/snapshot/exporter/exporter.go @@ -1,14 +1,13 @@ // Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -// Package provider implements BR's export controller. It never decodes rows or +// Package exporter manages embedded CSE export subprocesses. It never decodes rows or // opens a sink. The local Runner is confined to this package/process. -package provider +package exporter import ( "context" "encoding/base64" "encoding/json" "fmt" - "net/http" "os" "os/exec" "path/filepath" @@ -19,6 +18,7 @@ import ( "syscall" "time" + "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" "golang.org/x/sync/errgroup" @@ -37,28 +37,25 @@ type Page struct { Cursor string `json:"next_cursor"` Complete bool `json:"source_complete"` } -type Request struct { - JobID string `json:"job_id"` - SpecRef protocol.ObjectRef `json:"spec_ref"` - Cursor string `json:"cursor"` - Limit int `json:"limit"` -} -type Server struct { - Objects store.Local - Binary string +type Runner struct { + Statistics *metrics.SnapshotStatistics + Objects store.Local + Binary string // MinFreeBytes pauses new ranges while the artifact filesystem is low on space. MinFreeBytes int64 // Workers bounds concurrent local materialize-range processes per job. // Configure before serving requests; values below one retain serial execution. - Workers int - mu sync.Mutex - running map[string]context.CancelFunc - closed bool - workers sync.WaitGroup + ReadMemoryQuota int64 + DiskQuota int64 + Workers int + mu sync.Mutex + running map[string]context.CancelFunc + closed bool + workers sync.WaitGroup } -func New(root, binary string) *Server { - return &Server{Objects: store.Local{Root: root}, Binary: binary, running: map[string]context.CancelFunc{}} +func New(root, binary string) *Runner { + return &Runner{Objects: store.Local{Root: root}, Binary: binary, running: map[string]context.CancelFunc{}} } func key(id string) string { return "br/" + id + "/control.json" } func validID(id string) bool { @@ -73,7 +70,7 @@ func validID(id string) bool { return true } -func (s *Server) update(id string, fn func(*Job) error) error { +func (s *Runner) update(id string, fn func(*Job) error) error { for retry := 0; retry < 30; retry++ { var j Job v, e := s.Objects.Read(key(id), &j) @@ -97,7 +94,7 @@ func (s *Server) update(id string, fn func(*Job) error) error { return protocol.Invalid("job CAS contention") } -func (s *Server) Ensure(ref protocol.ObjectRef) (Job, error) { +func (s *Runner) Ensure(ref protocol.ObjectRef) (Job, error) { var spec protocol.Spec if e := protocol.Read(ref, &spec); e != nil { return Job{}, e @@ -117,13 +114,24 @@ func (s *Server) Ensure(ref protocol.ObjectRef) (Job, error) { if j.SpecRef != ref { return j, protocol.Invalid("Ensure identity conflict") } - if j.Phase != "SOURCE_COMPLETE" && j.Phase != "FAILED" && j.Phase != "CANCELED" { + if j.Phase == "FAILED" || j.Phase == "CANCELED" { + if err := s.update(spec.JobID, func(j *Job) error { j.Phase = "ACCEPTED"; j.Error = ""; return nil }); err != nil { + return j, err + } + j.Phase = "ACCEPTED" + j.Error = "" + } + if j.Phase == "SOURCE_COMPLETE" { + if err := s.cleanupAttempts(spec.JobID, j); err != nil { + return j, err + } + } else { s.start(spec.JobID) } return j, nil } -func (s *Server) start(id string) { +func (s *Runner) start(id string) { s.mu.Lock() defer s.mu.Unlock() if s.closed { @@ -156,7 +164,7 @@ func (s *Server) start(id string) { } // Close stops all local export processes and waits for their work to finish. -func (s *Server) Close() { +func (s *Runner) Close() { s.mu.Lock() s.closed = true for _, cancel := range s.running { @@ -166,7 +174,7 @@ func (s *Server) Close() { s.workers.Wait() } -func (s *Server) batch(ctx context.Context, id, command string, task map[string]any) (protocol.ObjectRef, error) { +func (s *Runner) batch(ctx context.Context, id, command string, task map[string]any) (protocol.ObjectRef, error) { parent := filepath.Join(s.Objects.Root, "br", id, "attempts") if e := os.MkdirAll(parent, 0o700); e != nil { return protocol.ObjectRef{}, protocol.Wrap(e) @@ -187,16 +195,36 @@ func (s *Server) batch(ctx context.Context, id, command string, task map[string] if e = os.WriteFile(taskFile, b, 0o600); e != nil { return protocol.ObjectRef{}, protocol.Wrap(e) } - log, e := os.Create(filepath.Join(dir, "worker.log")) - if e != nil { - return protocol.ObjectRef{}, protocol.Wrap(e) - } - defer log.Close() - cmd := exec.CommandContext(ctx, s.Binary, "snapshot", command, "--task-spec", taskFile) - cmd.Stdout = log - cmd.Stderr = log + output := &diagnostics{} + if spec, ok := task["spec"].(protocol.Spec); ok { + output.backupURI = spec.BackupURI + } + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + monitorDone := make(chan struct{}) + go func() { defer close(monitorDone); s.monitorDisk(ctx, cancel) }() + args := []string{"snapshot", command, "--task-spec", taskFile} + if s.ReadMemoryQuota > 0 { + args = append(args, "--file-memory-limit-mib", strconv.FormatInt(s.ReadMemoryQuota>>20, 10)) + } + cmd := exec.CommandContext(ctx, s.Binary, args...) + configureProcess(cmd) + cmd.Stdout = output + cmd.Stderr = output started := time.Now() + s.Statistics.Worker("export", 1) e = cmd.Run() + s.Statistics.Worker("export", -1) + s.Statistics.Observe(command, time.Since(started)) + if e != nil { + s.Statistics.Error(command) + } + _ = os.WriteFile(filepath.Join(dir, "worker.log"), output.safe(), 0o600) + cancel(nil) + <-monitorDone + if cause := context.Cause(ctx); cause != context.Canceled && cause != nil { + e = cause + } // Observability only: worker resource accounting is not part of the export // protocol and must never turn a completed export into a failed attempt. if state := cmd.ProcessState; state != nil { @@ -207,12 +235,20 @@ func (s *Server) batch(ctx context.Context, id, command string, task map[string] peakRSS *= 1024 } stats["peak_rss_bytes"] = peakRSS + s.Statistics.Process(state.UserTime().Seconds()+state.SystemTime().Seconds(), peakRSS) } if data, err := json.Marshal(stats); err == nil { _ = os.WriteFile(filepath.Join(dir, "worker-stats.json"), data, 0o600) } } if e != nil { + // Failed attempts never own published receipts, so their partial output is disposable. + entries, _ := os.ReadDir(dir) + for _, entry := range entries { + if entry.Name() != "worker.log" && entry.Name() != "worker-stats.json" { + _ = os.RemoveAll(filepath.Join(dir, entry.Name())) + } + } return protocol.ObjectRef{}, protocol.Wrap(e) } name := "candidate.json" @@ -222,11 +258,14 @@ func (s *Server) batch(ctx context.Context, id, command string, task map[string] return protocol.Ref(filepath.Join(dir, name)) } -func (s *Server) run(ctx context.Context, id string) error { +func (s *Runner) run(ctx context.Context, id string) error { var j Job if _, e := s.Objects.Read(key(id), &j); e != nil { return e } + if err := s.cleanupAttempts(id, j); err != nil { + return err + } if j.PlanRef.URI == "" { if e := s.update(id, func(j *Job) error { @@ -240,7 +279,7 @@ func (s *Server) run(ctx context.Context, id string) error { } ref, e := retryBatch(ctx, func() (protocol.ObjectRef, error) { return s.batch(ctx, id, "plan", map[string]any{"spec": j.Spec}) - }) + }, func() { s.Statistics.Retry("plan") }) if e != nil { return e } @@ -278,11 +317,13 @@ func (s *Server) run(ctx context.Context, id string) error { if workers < 1 { workers = 1 } + s.Statistics.Start("export") if e := materializeRanges(ctx, workers, plan.Ranges, func(ctx context.Context, r protocol.Span) error { return s.materialize(ctx, id, j, r) }); e != nil { return e } + s.Statistics.Finish("export") return s.update(id, func(j *Job) error { if e := activeJob(j); e != nil { return e @@ -333,7 +374,7 @@ func materializeRanges(ctx context.Context, workers int, ranges []protocol.Span, return group.Wait() } -func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.Span) error { +func (s *Runner) materialize(ctx context.Context, id string, j Job, r protocol.Span) error { // A deterministic URI is the completion authority. Recover a published // winner before launching work, then reconcile the append-only journal. exportKey := "br/" + id + "/range-exports/" + r.RangeID + ".json" @@ -348,7 +389,7 @@ func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.S } ref, e := retryBatch(ctx, func() (protocol.ObjectRef, error) { return s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 64 << 20}) - }) + }, func() { s.Statistics.Retry("materialize-range") }) if e != nil { return e } @@ -383,7 +424,9 @@ func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.S if e != nil { return e } + published := false if e = s.update(id, func(j *Job) error { + published = false if e := activeJob(j); e != nil { return e } @@ -396,21 +439,34 @@ func (s *Server) materialize(ctx context.Context, id string, j Job, r protocol.S } } j.Exports = append(j.Exports, ref) + published = true return nil }); e != nil { return e } + if published { + var bytes uint64 + for _, chunk := range ex.Chunks { + bytes += chunk.LogicalBytes + } + s.Statistics.Output("export", bytes, ex.KVCount) + } return nil } // A failed CSE process gets a fresh attempt directory. Published range winners // are never retried; callers validate each successful candidate before publish. -func retryBatch(ctx context.Context, run func() (protocol.ObjectRef, error)) (protocol.ObjectRef, error) { +func retryBatch(ctx context.Context, run func() (protocol.ObjectRef, error), onRetry ...func()) (protocol.ObjectRef, error) { var err error for attempt := 0; attempt < 3; attempt++ { if e := ctx.Err(); e != nil { return protocol.ObjectRef{}, protocol.Wrap(e) } + if attempt > 0 { + for _, notify := range onRetry { + notify() + } + } var ref protocol.ObjectRef ref, err = run() if err == nil { @@ -430,8 +486,8 @@ func retryBatch(ctx context.Context, run func() (protocol.ObjectRef, error)) (pr return protocol.ObjectRef{}, err } -func (s *Server) waitForSpace(ctx context.Context, id string) error { - if s.MinFreeBytes == 0 { +func (s *Runner) waitForSpace(ctx context.Context, id string) error { + if s.MinFreeBytes == 0 && s.DiskQuota == 0 { return nil } blocked := false @@ -443,7 +499,12 @@ func (s *Server) waitForSpace(ctx context.Context, id string) error { if err := syscall.Statfs(s.Objects.Root, &stat); err != nil { return protocol.Wrap(err) } - if int64(stat.Bavail)*int64(stat.Bsize) >= s.MinFreeBytes { + used, err := directoryUsage(s.Objects.Root) + if err != nil { + return err + } + reserve := int64(max(1, s.Workers)) * (64 << 20) + if int64(stat.Bavail)*int64(stat.Bsize) >= s.MinFreeBytes && (s.DiskQuota == 0 || used+reserve < s.DiskQuota) { if blocked { return s.update(id, func(j *Job) error { if err := activeJob(j); err != nil { @@ -475,90 +536,49 @@ func (s *Server) waitForSpace(ctx context.Context, id string) error { } } -func (s *Server) invoke(method string, req Request) (any, error) { - var out any - var err error - if method == "ensure" { - out, err = s.Ensure(req.SpecRef) - } else if !validID(req.JobID) { - err = protocol.Invalid("invalid job ID") - } else { - var j Job - var v string - v, err = s.Objects.Read(key(req.JobID), &j) - if err == nil && v == "" { - err = protocol.Invalid("unknown job") - } - if err == nil { - // A Provider can restart between CDC polls without losing an HTTP - // request. Reconcile durable work even when Ensure is not repeated. - if (method == "status" || method == "list") && j.Phase != "SOURCE_COMPLETE" && j.Phase != "FAILED" && j.Phase != "CANCELED" { - s.start(req.JobID) - } - switch method { - case "status": - out = j - case "list": - var offset int - if req.Cursor != "" { - b, e := base64.RawURLEncoding.DecodeString(req.Cursor) - if e != nil { - err = protocol.Wrap(e) - break - } - parts := strings.Split(string(b), ":") - if len(parts) != 3 || parts[0] != req.JobID || parts[1] != j.PlanRef.Digest { - err = protocol.Invalid("cursor identity mismatch") - break - } - offset, e = strconv.Atoi(parts[2]) - if e != nil { - err = protocol.Wrap(e) - break - } - } - if offset < 0 || offset > len(j.Exports) { - err = protocol.Invalid("cursor outside journal") - break - } - limit := req.Limit - if limit < 1 || limit > 256 { - limit = 64 - } - end := min(offset+limit, len(j.Exports)) - cursor := base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s:%d", req.JobID, j.PlanRef.Digest, end))) - out = Page{j.Exports[offset:end], cursor, j.Phase == "SOURCE_COMPLETE" && end == len(j.Exports)} - case "cancel": - err = s.update(req.JobID, func(j *Job) error { j.Phase = "CANCELED"; return nil }) - s.mu.Lock() - if cancel := s.running[req.JobID]; cancel != nil { - cancel() - } - s.mu.Unlock() - out = map[string]bool{"canceled": true} - default: - err = protocol.Invalid("unknown provider method") - } - } +// Status observes one durable export job; Ensure is the only restart entry point. +func (s *Runner) Status(id string) (Job, error) { + var j Job + if !validID(id) { + return j, protocol.Invalid("invalid export job ID") } - return out, err + digest, err := s.Objects.Read(key(id), &j) + if err != nil { + return j, err + } + if digest == "" { + return j, protocol.Invalid("unknown export job") + } + return j, nil } -func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - if r.Method != "POST" { - http.Error(w, "POST required", 405) - return +func (s *Runner) List(id, cursor string, limit int) (Page, error) { + j, err := s.Status(id) + if err != nil { + return Page{}, err } - var req Request - if e := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); e != nil { - http.Error(w, "invalid request", 400) - return + offset := 0 + if cursor != "" { + b, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return Page{}, protocol.Wrap(err) + } + parts := strings.Split(string(b), ":") + if len(parts) != 3 || parts[0] != id || parts[1] != j.PlanRef.Digest { + return Page{}, protocol.Invalid("cursor identity mismatch") + } + offset, err = strconv.Atoi(parts[2]) + if err != nil { + return Page{}, protocol.Wrap(err) + } } - out, err := s.invoke(strings.TrimPrefix(r.URL.Path, "/"), req) - if err != nil { - http.Error(w, err.Error(), 400) - return + if offset < 0 || offset > len(j.Exports) { + return Page{}, protocol.Invalid("cursor outside journal") + } + if limit < 1 || limit > 256 { + limit = 64 } - _ = json.NewEncoder(w).Encode(out) + end := min(offset+limit, len(j.Exports)) + next := base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s:%d", id, j.PlanRef.Digest, end))) + return Page{Exports: j.Exports[offset:end], Cursor: next, Complete: j.Phase == "SOURCE_COMPLETE" && end == len(j.Exports)}, nil } diff --git a/pkg/snapshot/provider/provider_test.go b/pkg/snapshot/exporter/exporter_test.go similarity index 83% rename from pkg/snapshot/provider/provider_test.go rename to pkg/snapshot/exporter/exporter_test.go index 16ebe4b312..bac0a95a6f 100644 --- a/pkg/snapshot/provider/provider_test.go +++ b/pkg/snapshot/exporter/exporter_test.go @@ -1,9 +1,8 @@ // Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package provider +package exporter import ( "context" - "net/http/httptest" "os" "path/filepath" "sync" @@ -30,33 +29,34 @@ func TestPublishedExportRecoveredAndCursorFinalTail(t *testing.T) { _, e = s.Objects.Put("br/job/range-exports/"+r.RangeID+".json", protocol.Export{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, PlanDigest: ref.Digest, Range: r, AttemptID: "a"}) require.NoError(t, e) } - server := httptest.NewServer(s) - defer server.Close() - client := Client{URL: server.URL} - // Simulate Provider restart after export publication but before journal - // update. A status poll must restart reconciliation without another Ensure. + _, err := s.Ensure(specRef) + require.NoError(t, err) var recovered Job require.Eventually(t, func() bool { - err := client.Call(context.Background(), "status", Request{JobID: "job"}, &recovered) + var err error + recovered, err = s.Status("job") return err == nil && recovered.Phase == "SOURCE_COMPLETE" - }, time.Second, 10*time.Millisecond) - var page Page - require.NoError(t, client.Call(context.Background(), "list", Request{JobID: "job", Limit: 1}, &page)) + }, 3*time.Second, 10*time.Millisecond) + page, err := s.List("job", "", 1) + require.NoError(t, err) require.Len(t, page.Exports, 1) require.False(t, page.Complete) first := page.Cursor - require.NoError(t, client.Call(context.Background(), "list", Request{JobID: "job", Limit: 1, Cursor: first}, &page)) + page, err = s.List("job", first, 1) + require.NoError(t, err) require.True(t, page.Complete) require.Len(t, page.Exports, 1) - require.NoError(t, (LocalClient{Server: s}).Call(context.Background(), "list", Request{JobID: "job", Limit: 1, Cursor: first}, &page)) + page, err = s.List("job", first, 1) + require.NoError(t, err) require.True(t, page.Complete) - var job Job - require.NoError(t, client.Call(context.Background(), "ensure", Request{SpecRef: specRef}, &job)) + job, err := s.Ensure(specRef) + require.NoError(t, err) require.Equal(t, "SOURCE_COMPLETE", job.Phase) spec.BackupDigest = "different" other, e := s.Objects.Put("other-spec", spec) require.NoError(t, e) - require.Error(t, client.Call(context.Background(), "ensure", Request{SpecRef: other}, &job)) + _, err = s.Ensure(other) + require.Error(t, err) } func TestEmbeddedCloseStopsExportWithoutFailingJob(t *testing.T) { @@ -69,12 +69,12 @@ func TestEmbeddedCloseStopsExportWithoutFailingJob(t *testing.T) { spec := protocol.Spec{ProtocolVersion: 1, JobID: "job", SnapshotID: "s", SnapshotTS: 42, SelectedSpans: []protocol.Span{{TableID: 1, Start: []byte("a"), End: []byte("z")}}} ref, err := s.Objects.Put("spec", spec) require.NoError(t, err) - var job Job - require.NoError(t, (LocalClient{Server: s}).Call(context.Background(), "ensure", Request{SpecRef: ref}, &job)) + job, err := s.Ensure(ref) + require.NoError(t, err) require.Eventually(t, func() bool { _, err := os.Stat(marker) return err == nil - }, 5*time.Second, 10*time.Millisecond) + }, 20*time.Second, 10*time.Millisecond) s.Close() _, err = s.Objects.Read(key("job"), &job) require.NoError(t, err) diff --git a/pkg/snapshot/exporter/process_linux.go b/pkg/snapshot/exporter/process_linux.go new file mode 100644 index 0000000000..9d007e7734 --- /dev/null +++ b/pkg/snapshot/exporter/process_linux.go @@ -0,0 +1,11 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import ( + "os/exec" + "syscall" +) + +func configureProcess(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL} +} diff --git a/pkg/snapshot/exporter/process_other.go b/pkg/snapshot/exporter/process_other.go new file mode 100644 index 0000000000..c72e1dee79 --- /dev/null +++ b/pkg/snapshot/exporter/process_other.go @@ -0,0 +1,8 @@ +//go:build !linux + +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package exporter + +import "os/exec" + +func configureProcess(cmd *exec.Cmd) {} diff --git a/pkg/snapshot/placement.go b/pkg/snapshot/placement.go new file mode 100644 index 0000000000..0524adeeda --- /dev/null +++ b/pkg/snapshot/placement.go @@ -0,0 +1,35 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "time" + + "github.com/pingcap/ticdc/pkg/node" +) + +const executorUnavailableTimeout = 60 * time.Second + +// Placement uses stable advertised addresses so a restarted process can adopt +// its own local files even though its capture ID changed. It belongs to one +// maintainer attempt; a fresh maintainer waits a full grace period again. +type Placement struct{ unavailableSince time.Time } + +func (p *Placement) Select(now time.Time, bound string, self *node.Info, alive map[node.ID]*node.Info) (*node.Info, bool) { + if bound == "" { + p.unavailableSince = time.Time{} + return self, true + } + for _, n := range alive { + if n.AdvertiseAddr == bound { + p.unavailableSince = time.Time{} + return n, false + } + } + if p.unavailableSince.IsZero() { + p.unavailableSince = now + } + if now.Sub(p.unavailableSince) < executorUnavailableTimeout { + return nil, false + } + return self, true +} diff --git a/pkg/snapshot/placement_test.go b/pkg/snapshot/placement_test.go new file mode 100644 index 0000000000..21c2f01050 --- /dev/null +++ b/pkg/snapshot/placement_test.go @@ -0,0 +1,39 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "testing" + "time" + + "github.com/pingcap/ticdc/pkg/node" + "github.com/stretchr/testify/require" +) + +func TestPlacementWaitsAndPrefersOriginalAddress(t *testing.T) { + self := &node.Info{ID: "new", AdvertiseAddr: "new:8300"} + old := &node.Info{ID: "old", AdvertiseAddr: "old:8300"} + now := time.Unix(100, 0) + var p Placement + n, bind := p.Select(now, "", self, nil) + require.Same(t, self, n) + require.True(t, bind) + n, bind = p.Select(now, old.AdvertiseAddr, self, map[node.ID]*node.Info{old.ID: old}) + require.Same(t, old, n) + require.False(t, bind) + n, _ = p.Select(now, old.AdvertiseAddr, self, nil) + require.Nil(t, n) + n, _ = p.Select(now.Add(59*time.Second), old.AdvertiseAddr, self, nil) + require.Nil(t, n) + restarted := &node.Info{ID: "restarted", AdvertiseAddr: old.AdvertiseAddr} + n, bind = p.Select(now.Add(59*time.Second), old.AdvertiseAddr, self, map[node.ID]*node.Info{restarted.ID: restarted}) + require.Same(t, restarted, n) + require.False(t, bind) + // Recovery resets the absence timer rather than carrying over an old outage. + n, _ = p.Select(now.Add(60*time.Second), old.AdvertiseAddr, self, nil) + require.Nil(t, n) + n, _ = p.Select(now.Add(119*time.Second), old.AdvertiseAddr, self, nil) + require.Nil(t, n) + n, bind = p.Select(now.Add(120*time.Second), old.AdvertiseAddr, self, nil) + require.Same(t, self, n) + require.True(t, bind) +} diff --git a/pkg/snapshot/protocol/chunk.go b/pkg/snapshot/protocol/chunk.go index 276afae988..f650a4dea7 100644 --- a/pkg/snapshot/protocol/chunk.go +++ b/pkg/snapshot/protocol/chunk.go @@ -56,6 +56,7 @@ func (r *bufferReader) Read(p []byte) (int, error) { r.data = r.data[n:] return n, nil } + func (r *bufferReader) take(n uint32) ([]byte, error) { if uint64(n) > uint64(len(r.data)) { return nil, Wrap(io.ErrUnexpectedEOF) @@ -64,6 +65,7 @@ func (r *bufferReader) take(n uint32) ([]byte, error) { r.data = r.data[n:] return b, nil } + func readN(r io.Reader, n uint32, max uint32) ([]byte, error) { if n > max { return nil, Invalid("frame exceeds limit") diff --git a/pkg/snapshot/protocol/message.go b/pkg/snapshot/protocol/message.go new file mode 100644 index 0000000000..544b61503d --- /dev/null +++ b/pkg/snapshot/protocol/message.go @@ -0,0 +1,16 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package protocol + +import "encoding/json" + +// Message carries control/status only. Payloads may contain configuration secrets; +// String deliberately never includes them, including in generic messaging logs. +type Message struct { + RequestID string + Response bool + Payload []byte +} + +func (m *Message) Marshal() ([]byte, error) { b, e := json.Marshal(m); return b, Wrap(e) } +func (m *Message) Unmarshal(b []byte) error { return Wrap(json.Unmarshal(b, m)) } +func (m *Message) String() string { return "snapshot control message" } diff --git a/pkg/snapshot/protocol/protocol_test.go b/pkg/snapshot/protocol/protocol_test.go index d7485a7fcd..3a3e4112da 100644 --- a/pkg/snapshot/protocol/protocol_test.go +++ b/pkg/snapshot/protocol/protocol_test.go @@ -22,9 +22,6 @@ func TestCoverageAndStableIdentity(t *testing.T) { p.Ranges[1] = r require.Error(t, ValidatePlan(spec, p)) } - require.Equal(t, RecordID("s", 1, []byte("a")), RecordID("s", 1, []byte("a"))) - require.NotEqual(t, RecordID("s", 1, []byte("a")), RecordID("s", 2, []byte("a"))) - require.NotEqual(t, RecordID("ab", 1, []byte("c")), RecordID("a", 1, []byte("bc"))) } func TestRustGoldenAndCorruption(t *testing.T) { @@ -76,7 +73,7 @@ func TestRustGoldenAndCorruption(t *testing.T) { } func TestStateRoundTrip(t *testing.T) { - state := State{Generation: "g", Phase: "SNAPSHOT_COMMITTED", Marker: &Marker{SnapshotTS: 42}} + state := State{Generation: "g", Phase: "SNAPSHOT_COMMITTED"} b, e := json.Marshal(state) require.NoError(t, e) var out State @@ -108,9 +105,9 @@ func TestRuntimeLimits(t *testing.T) { var defaults *Config require.NoError(t, defaults.ValidateRuntime()) require.Equal(t, 4, defaults.ApplyConcurrency()) - require.EqualValues(t, 64<<20, defaults.InflightLimit()) - for _, c := range []Config{{ApplyWorkers: -1}, {ApplyWorkers: 33}, {InflightBytes: 1}, {InflightBytes: (1 << 30) + 1}} { + require.EqualValues(t, 256<<20, defaults.InflightLimit()) + for _, c := range []Config{{ApplyWorkers: -1}, {ApplyWorkers: 33}, {WriteMemoryQuota: 1}, {WriteMemoryQuota: (1 << 30) + 1}} { require.Error(t, c.ValidateRuntime()) } - require.NoError(t, (&Config{ApplyWorkers: 16, InflightBytes: 32 << 20}).ValidateRuntime()) + require.NoError(t, (&Config{ApplyWorkers: 16, WriteMemoryQuota: 32 << 20}).ValidateRuntime()) } diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go index 95ed21e531..451521ae75 100644 --- a/pkg/snapshot/protocol/types.go +++ b/pkg/snapshot/protocol/types.go @@ -4,7 +4,6 @@ package protocol import ( "bytes" "crypto/sha256" - "encoding/binary" "encoding/hex" "encoding/json" "fmt" @@ -95,37 +94,36 @@ type Footer struct { // State is the optional snapshot child of ChangeFeedStatus, never a second job key. type State struct { - Generation string `json:"generation"` - SnapshotID string `json:"snapshot_id"` - SnapshotTS uint64 `json:"snapshot_ts"` - Phase string `json:"phase"` - SpecRef ObjectRef `json:"spec_ref"` - PlanRef ObjectRef `json:"plan_ref"` - Cursor string `json:"ready_cursor"` - Barrier bool `json:"sink_bootstrap_barrier"` - Applied int `json:"applied"` - Total int `json:"total"` - Marker *Marker `json:"global_marker,omitempty"` -} -type Marker struct { - SnapshotTS uint64 `json:"snapshot_ts"` - SnapshotID string `json:"snapshot_id"` - OutputFence string `json:"output_fence"` + Generation string `json:"generation"` + SnapshotID string `json:"snapshot_id"` + SnapshotTS uint64 `json:"snapshot_ts"` + Phase string `json:"phase"` + SpecRef ObjectRef `json:"spec_ref"` + PlanRef ObjectRef `json:"plan_ref"` + Cursor string `json:"ready_cursor"` + Applied int `json:"applied"` + Total int `json:"total"` + Executor string `json:"executor,omitempty"` + InputDigest string `json:"input_digest,omitempty"` } -// Config is opt-in. An empty ProviderURL selects the embedded local runner; -// ArtifactDir and ProviderURL remain for the standalone demo adapter. +// Config controls the independent snapshot pipeline. Quotas are in bytes. type Config struct { - ApplyWorkers int `toml:"apply-workers" json:"apply-workers,omitempty"` - InflightBytes int64 `toml:"inflight-bytes" json:"inflight-bytes,omitempty"` - BackupURI string `toml:"backup-uri" json:"backup-uri"` - BackupDigest string `toml:"backup-digest" json:"backup-digest"` - ProviderURL string `toml:"provider-url" json:"provider-url"` - ArtifactDir string `toml:"artifact-dir" json:"artifact-dir"` + ApplyWorkers int `toml:"apply-workers" json:"apply-workers,omitempty"` + // WriteMemoryQuota bounds mounted rows awaiting sink ACKs across all apply + // workers. Default: 256 MiB. Chunk buffers and sink overhead are additional. + WriteMemoryQuota int64 `toml:"write-memory-quota" json:"write-memory-quota,omitempty"` + // ReadMemoryQuotaPerProcess bounds SST file contents cached in memory, not process RSS. + ReadMemoryQuotaPerProcess int64 `toml:"read-memory-quota-per-process" json:"read-memory-quota-per-process,omitempty"` + ExportWorkers int `toml:"export-workers" json:"export-workers,omitempty"` + // DiskQuota covers this changefeed's complete snapshot directory. Default: 200 GB. + DiskQuota int64 `toml:"disk-quota" json:"disk-quota,omitempty"` + BackupURI string `toml:"backup-uri" json:"backup-uri"` + BackupDigest string `toml:"backup-digest" json:"backup-digest"` } // ApplyConcurrency and InflightLimit bound capture-side work independently of -// provider export workers. The byte budget covers mounted data awaiting ACK; +// CSE export workers. The byte budget covers mounted data awaiting ACK; // each worker additionally owns at most one bounded input chunk and batch. func (c *Config) ApplyConcurrency() int { if c == nil || c.ApplyWorkers == 0 { @@ -133,18 +131,50 @@ func (c *Config) ApplyConcurrency() int { } return c.ApplyWorkers } + func (c *Config) InflightLimit() int64 { - if c == nil || c.InflightBytes == 0 { - return 64 << 20 + if c == nil || c.WriteMemoryQuota == 0 { + return 256 << 20 + } + return c.WriteMemoryQuota +} + +func (c *Config) ReadLimit() int64 { + if c == nil || c.ReadMemoryQuotaPerProcess == 0 { + return 512 << 20 + } + return c.ReadMemoryQuotaPerProcess +} + +func (c *Config) DiskLimit() int64 { + if c == nil || c.DiskQuota == 0 { + return 200_000_000_000 } - return c.InflightBytes + return c.DiskQuota } + +func (c *Config) ExportConcurrency() int { + if c == nil || c.ExportWorkers == 0 { + return 1 + } + return c.ExportWorkers +} + func (c *Config) ValidateRuntime() error { + if c.ReadLimit() < 1<<20 || c.ReadLimit()%(1<<20) != 0 { + return Invalid("read-memory-quota-per-process must be a positive whole MiB") + } + if c.DiskLimit() < 128<<20 || c.DiskLimit() <= int64(c.ExportConcurrency())*(64<<20)+(4<<20) { + return Invalid("disk-quota must be at least 128 MiB and allow one 64 MiB chunk per export worker plus metadata") + } + if c.ExportConcurrency() < 1 || c.ExportConcurrency() > 32 { + return Invalid("export-workers must be between 1 and 32") + } if c.ApplyConcurrency() < 1 || c.ApplyConcurrency() > 32 { return Invalid("apply-workers must be between 1 and 32") } if c.InflightLimit() < 32<<20 || c.InflightLimit() > 1<<30 { - return Invalid("inflight-bytes must be between 32 MiB and 1 GiB") + return Invalid("write-memory-quota must be between 32 MiB and 1 GiB") } return nil } @@ -245,18 +275,3 @@ func ValidateExport(spec Spec, plan ObjectRef, r Span, e Export) error { } return nil } - -func RecordID(snapshot string, table int64, key []byte) string { - h := sha256.New() - h.Write([]byte("snapshot-key-v1\x00")) - var b [8]byte - binary.BigEndian.PutUint32(b[:4], uint32(len(snapshot))) - h.Write(b[:4]) - h.Write([]byte(snapshot)) - binary.BigEndian.PutUint64(b[:], uint64(table)) - h.Write(b[:]) - binary.BigEndian.PutUint32(b[:4], uint32(len(key))) - h.Write(b[:4]) - h.Write(key) - return hex.EncodeToString(h.Sum(nil)) -} diff --git a/pkg/snapshot/provider/client.go b/pkg/snapshot/provider/client.go deleted file mode 100644 index 8859b4d8bf..0000000000 --- a/pkg/snapshot/provider/client.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package provider - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - "time" - - "github.com/pingcap/ticdc/pkg/snapshot/protocol" -) - -type Client struct{ URL string } - -// Caller keeps the snapshot bootstrap independent of whether the Provider is -// reached over HTTP or embedded in the TiCDC process. -type Caller interface { - Call(context.Context, string, Request, any) error -} - -type LocalClient struct{ Server *Server } - -func (c LocalClient) Call(ctx context.Context, method string, req Request, out any) error { - if err := ctx.Err(); err != nil { - return protocol.Wrap(err) - } - result, err := c.Server.invoke(method, req) - if err != nil { - return err - } - b, err := json.Marshal(result) - if err != nil { - return protocol.Wrap(err) - } - return protocol.Wrap(json.Unmarshal(b, out)) -} - -func (c Client) Call(ctx context.Context, method string, req Request, out any) error { - b, e := json.Marshal(req) - if e != nil { - return protocol.Wrap(e) - } - r, e := http.NewRequestWithContext(ctx, "POST", c.URL+"/"+method, bytes.NewReader(b)) - if e != nil { - return protocol.Wrap(e) - } - r.Header.Set("Content-Type", "application/json") - client := http.Client{Timeout: 30 * time.Second} - resp, e := client.Do(r) - if e != nil { - return protocol.Wrap(e) - } - defer resp.Body.Close() - if resp.StatusCode != 200 { - b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) - return protocol.Invalid("provider %s: %s", method, b) - } - return protocol.Wrap(json.NewDecoder(io.LimitReader(resp.Body, 4<<20)).Decode(out)) -} diff --git a/pkg/snapshot/schema.go b/pkg/snapshot/schema.go new file mode 100644 index 0000000000..546843d331 --- /dev/null +++ b/pkg/snapshot/schema.go @@ -0,0 +1,76 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "bytes" + "context" + "sort" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/filter" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/tidb/pkg/kv" + "github.com/pingcap/tidb/pkg/meta" + "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/tablecodec" +) + +// FreezeSchema reads metadata at the backup timestamp directly. It never +// registers tables or versions in the incremental SchemaStore. +func FreezeSchema(ctx context.Context, storage kv.Storage, ts uint64, cfg *config.ChangefeedConfig) (bootstrap.SchemaBundle, []protocol.Span, error) { + bundle := bootstrap.SchemaBundle{SnapshotTS: ts} + f, err := filter.NewFilter(cfg.Filter, "", cfg.CaseSensitive, cfg.ForceReplicate) + if err != nil { + return bundle, nil, err + } + reader := meta.NewReader(storage.GetSnapshot(kv.NewVersion(ts))) + dbs, err := reader.ListDatabases() + if err != nil { + return bundle, nil, protocol.Wrap(err) + } + var spans []protocol.Span + for _, db := range dbs { + if filter.IsSysSchema(db.Name.O) || f.ShouldIgnoreSchema(db.Name.O) { + continue + } + err = reader.IterTables(db.ID, func(t *model.TableInfo) error { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + if t.Sequence != nil || t.IsView() || f.ShouldIgnoreTable(db.Name.O, t.Name.O) { + return nil + } + table := common.WrapTableInfo(db.Name.O, t) + if !table.IsEligible(cfg.ForceReplicate) { + return nil + } + data, err := table.Marshal() + if err != nil { + return protocol.Wrap(err) + } + ids := []int64{t.ID} + if p := t.GetPartitionInfo(); p != nil { + ids = nil + for _, d := range p.Definitions { + ids = append(ids, d.ID) + } + } + for _, id := range ids { + start := tablecodec.GenTableRecordPrefix(id) + end := bytes.Clone(start) + end[len(end)-1]++ + bundle.Tables = append(bundle.Tables, bootstrap.Schema{TableID: id, Data: data}) + spans = append(spans, protocol.Span{TableID: id, Start: start, End: end}) + } + return nil + }) + if err != nil { + return bundle, nil, protocol.Wrap(err) + } + } + sort.Slice(bundle.Tables, func(i, j int) bool { return bundle.Tables[i].TableID < bundle.Tables[j].TableID }) + sort.Slice(spans, func(i, j int) bool { return spans[i].TableID < spans[j].TableID }) + return bundle, spans, nil +} diff --git a/pkg/snapshot/schema_test.go b/pkg/snapshot/schema_test.go new file mode 100644 index 0000000000..74c137dd46 --- /dev/null +++ b/pkg/snapshot/schema_test.go @@ -0,0 +1,44 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "context" + "testing" + + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/stretchr/testify/require" + "github.com/tikv/client-go/v2/oracle" +) + +func TestFreezeSchemaPinsTimestampAndPhysicalPartitions(t *testing.T) { + h := commonEvent.NewEventTestHelperWithPrivateStore(t) + defer h.Close() + h.DDL2Job("create table test.frozen(id int primary key, v int)") + h.DDL2Job("create table test.partitioned(id int primary key) partition by range(id)(partition p0 values less than(10),partition p1 values less than(maxvalue))") + h.DDL2Job("create table test.excluded(id int primary key)") + ver, err := h.Storage().CurrentVersion(oracle.GlobalTxnScope) + require.NoError(t, err) + h.DDL2Job("alter table test.frozen add column later int") + cfg := &config.ChangefeedConfig{Filter: &config.FilterConfig{Rules: []string{"test.frozen", "test.partitioned"}}} + bundle, spans, err := FreezeSchema(context.Background(), h.Storage(), ver.Ver, cfg) + require.NoError(t, err) + require.Equal(t, ver.Ver, bundle.SnapshotTS) + require.Len(t, bundle.Tables, 3) + require.Len(t, spans, 3) + partitions := 0 + for i, s := range bundle.Tables { + require.Equal(t, s.TableID, spans[i].TableID) + require.Less(t, string(spans[i].Start), string(spans[i].End)) + info, err := common.UnmarshalJSONToTableInfo(s.Data) + require.NoError(t, err) + if info.GetTableName() == "frozen" { + require.Len(t, info.GetColumns(), 2) + } else { + require.Equal(t, "partitioned", info.GetTableName()) + partitions++ + } + } + require.Equal(t, 2, partitions) +} diff --git a/pkg/snapshot/service.go b/pkg/snapshot/service.go new file mode 100644 index 0000000000..c8d36335dc --- /dev/null +++ b/pkg/snapshot/service.go @@ -0,0 +1,362 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "sync" + "time" + + "github.com/google/uuid" + "github.com/pingcap/ticdc/downstreamadapter/sink" + "github.com/pingcap/ticdc/pkg/common" + appcontext "github.com/pingcap/ticdc/pkg/common/context" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/messaging" + "github.com/pingcap/ticdc/pkg/metrics" + "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/writelease" + "github.com/pingcap/tidb/pkg/kv" +) + +const ( + ServiceName = "snapshot" + controlTopic = "snapshot-control" +) + +type ( + Nodes interface{ GetAliveNodes() map[node.ID]*node.Info } + Repository interface { + bootstrap.Repository + Bind(context.Context, common.ChangeFeedID, uint64, *protocol.State, string) error + } +) + +// StorageGetter borrows server-owned storage; snapshot execution must never close it. +type ( + StorageGetter func(context.Context, string) (kv.Storage, error) + request struct { + Config *config.ChangefeedConfig + Keyspace uint32 + } +) + +type response struct { + Done bool + Error string +} +type execution struct { + epoch uint64 + cancel context.CancelFunc + done chan struct{} + err error + seen time.Time +} + +// Service is CDC-owned: MessageCenter only transports start/status heartbeats. +// Data and task pages stay on the executor; no external management process runs. +type Service struct { + ctx context.Context + self *node.Info + nodes Nodes + repo Repository + mc messaging.MessageCenter + storage StorageGetter + mu sync.Mutex + jobs map[common.ChangeFeedID]*execution + waiters map[string]chan response +} + +func NewService(ctx context.Context, self *node.Info, nodes Nodes, repo Repository, mc messaging.MessageCenter, storage StorageGetter) *Service { + s := &Service{ctx: ctx, self: self, nodes: nodes, repo: repo, mc: mc, storage: storage, jobs: make(map[common.ChangeFeedID]*execution), waiters: make(map[string]chan response)} + mc.RegisterHandler(controlTopic, s.handle) + return s +} +func (s *Service) Name() string { return ServiceName } +func (s *Service) Run(ctx context.Context) error { <-ctx.Done(); return nil } +func (s *Service) Close(context.Context) error { + s.mc.DeRegisterHandler(controlTopic) + s.mu.Lock() + jobs := make([]*execution, 0, len(s.jobs)) + for _, j := range s.jobs { + j.cancel() + jobs = append(jobs, j) + } + s.mu.Unlock() + for _, j := range jobs { + <-j.done + } + return nil +} + +// Run is the only maintainer entry point. It waits for the original executor +// through node-manager's grace period and only then rebinds to this CDC. +func (s *Service) Bootstrap(ctx context.Context, cfg *config.ChangefeedConfig, keyspace uint32) error { + if err := Validate(cfg); err != nil { + return err + } + var placement Placement + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + state, err := s.repo.LoadSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch) + if err != nil { + return err + } + if state != nil && state.Phase == "SNAPSHOT_COMMITTED" { + return nil + } + if state == nil { + id := uuid.NewString() + state = &protocol.State{Generation: id, SnapshotID: id, SnapshotTS: cfg.StartTS, Phase: "PREPARING"} + } + target, bind := placement.Select(time.Now(), state.Executor, s.self, s.nodes.GetAliveNodes()) + if target != nil { + if bind { + old := state.Executor + state.Executor = target.AdvertiseAddr + // Local receipts cannot be read on another node. Re-export the same frozen + // snapshot there, allowing duplicates, with no dependency on the lost disk. + if old != "" && old != state.Executor { + state.SpecRef = protocol.ObjectRef{} + state.PlanRef = protocol.ObjectRef{} + state.Cursor = "" + state.Applied = 0 + state.Total = 0 + state.Phase = "PREPARING" + } + if err = s.repo.Bind(ctx, cfg.ChangefeedID, cfg.Epoch, state, old); err != nil { + return err + } + } + res, err := s.poll(ctx, target.ID, request{cfg, keyspace}) + if err == nil { + if res.Error != "" { + return protocol.Invalid("%s", res.Error) + } + if res.Done { + return nil + } + } + // A transient transport failure doesn't change executor ownership. If the + // node disappears, NodeManager starts the 60-second relocation timer. + } + select { + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + case <-ticker.C: + } + } +} + +func (s *Service) poll(ctx context.Context, target node.ID, req request) (response, error) { + if target == s.self.ID { + return s.status(req), nil + } + id := uuid.NewString() + ch := make(chan response, 1) + s.mu.Lock() + s.waiters[id] = ch + s.mu.Unlock() + defer func() { s.mu.Lock(); delete(s.waiters, id); s.mu.Unlock() }() + payload, err := json.Marshal(req) + if err != nil { + return response{}, protocol.Wrap(err) + } + if err = s.mc.SendCommand(messaging.NewSingleTargetMessage(target, controlTopic, &protocol.Message{RequestID: id, Payload: payload})); err != nil { + return response{}, err + } + timer := time.NewTimer(time.Second) + defer timer.Stop() + select { + case r := <-ch: + return r, nil + case <-ctx.Done(): + return response{}, protocol.Wrap(ctx.Err()) + case <-timer.C: + return response{}, protocol.Invalid("snapshot status timeout") + } +} + +func (s *Service) handle(_ context.Context, msg *messaging.TargetMessage) error { + m := msg.Message[0].(*protocol.Message) + if m.Response { + var r response + if err := json.Unmarshal(m.Payload, &r); err != nil { + return protocol.Wrap(err) + } + s.mu.Lock() + if ch := s.waiters[m.RequestID]; ch != nil { + select { + case ch <- r: + default: + } + } + s.mu.Unlock() + return nil + } + var req request + if err := json.Unmarshal(m.Payload, &req); err != nil { + return protocol.Wrap(err) + } + if req.Config == nil { + return protocol.Invalid("missing snapshot configuration") + } + r := s.status(req) + b, err := json.Marshal(r) + if err != nil { + return protocol.Wrap(err) + } + return s.mc.SendCommand(messaging.NewSingleTargetMessage(msg.From, controlTopic, &protocol.Message{RequestID: m.RequestID, Response: true, Payload: b})) +} + +func (s *Service) status(req request) response { + s.mu.Lock() + defer s.mu.Unlock() + cfg := req.Config + j := s.jobs[cfg.ChangefeedID] + if j != nil && j.epoch != cfg.Epoch { + if j.epoch > cfg.Epoch { + return response{Error: "stale snapshot owner"} + } + j.cancel() + select { + case <-j.done: + delete(s.jobs, cfg.ChangefeedID) + j = nil + default: + return response{} + } + } + if j == nil { + ctx, cancel := context.WithCancel(s.ctx) + j = &execution{epoch: cfg.Epoch, cancel: cancel, done: make(chan struct{}), seen: time.Now()} + s.jobs[cfg.ChangefeedID] = j + go func() { defer close(j.done); j.err = s.execute(ctx, req) }() + go s.watch(ctx, cfg, j) + } + j.seen = time.Now() + select { + case <-j.done: + if j.err != nil { + return response{Error: j.err.Error()} + } + return response{Done: true} + default: + return response{} + } +} + +func (s *Service) watch(ctx context.Context, cfg *config.ChangefeedConfig, j *execution) { + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-j.done: + return + case <-ticker.C: + s.mu.Lock() + expired := time.Since(j.seen) > 15*time.Second + s.mu.Unlock() + state, err := s.repo.LoadSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch) + if expired || err != nil || state == nil || state.Executor != s.self.AdvertiseAddr { + j.cancel() + return + } + } + } +} + +func (s *Service) execute(ctx context.Context, req request) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + cfg := req.Config + if err := Validate(cfg); err != nil { + return err + } + state, err := s.repo.LoadSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch) + if err != nil { + return err + } + if state != nil && state.Phase == "SNAPSHOT_COMMITTED" { + return nil + } + if state == nil || state.Executor != s.self.AdvertiseAddr { + return protocol.Invalid("snapshot executor fenced") + } + server := config.GetGlobalServerConfig() + dir := filepath.Join(server.DataDir, "snapshot", cfg.ChangefeedID.ID().String()) + if err = os.MkdirAll(dir, 0o700); err != nil { + return protocol.Wrap(err) + } + bundle, spans, err := s.freezeSchema(ctx, cfg) + if err != nil { + return err + } + destination, err := json.Marshal(struct { + URI string + Sink *config.SinkConfig + TimeZone string + CaseSensitive bool + }{cfg.SinkURI, cfg.SinkConfig, cfg.TimeZone, cfg.CaseSensitive}) + if err != nil { + return protocol.Wrap(err) + } + sk, err := sink.New(ctx, cfg, cfg.ChangefeedID, req.Keyspace) + if err != nil { + return err + } + if gate, ok := appcontext.TryGetService[*writelease.Gate](appcontext.CaptureWriteGate); ok { + sk.SetWriteGate(gate) + } + statistics := metrics.NewSnapshotStatistics(cfg.ChangefeedID.Keyspace(), cfg.ChangefeedID.Name()) + statistics.Start("overall") + statistics.Set("inflight_bytes", 0) + statistics.Set("write_memory_quota_bytes", float64(cfg.Snapshot.InflightLimit())) + statistics.Set("disk_quota_bytes", float64(cfg.Snapshot.DiskLimit())) + writer := NewWriter(ctx, sk, cfg.Snapshot, cfg.Epoch, statistics) + defer writer.Close() + go func() { + select { + case <-ctx.Done(): + case <-writer.sinkStopped: + if writer.sinkErr != nil { + cancel() + } + } + }() + ctl := bootstrap.Controller{Statistics: statistics, DestinationDigest: protocol.Digest(destination), ID: cfg.ChangefeedID, Epoch: cfg.Epoch, TS: cfg.StartTS, Keyspace: req.Keyspace, Config: cfg.Snapshot, ArtifactDir: dir, CSEBinary: server.SnapshotCSEBinary, MinFreeBytes: server.SnapshotMinFreeBytes, Repository: s.repo, Capture: writer, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { + return bundle, spans, nil + }} + err = ctl.Run(ctx) + if err == nil { + statistics.Finish("apply") + statistics.Finish("overall") + } else { + statistics.Error("overall") + } + select { + case <-writer.sinkStopped: + if writer.sinkErr != nil { + return writer.sinkErr + } + default: + } + return err +} + +func (s *Service) freezeSchema(ctx context.Context, cfg *config.ChangefeedConfig) (bootstrap.SchemaBundle, []protocol.Span, error) { + storage, err := s.storage(ctx, cfg.ChangefeedID.Keyspace()) + if err != nil { + return bootstrap.SchemaBundle{}, nil, err + } + // TiDB's driver caches clients across OpenWithOptions calls. Their lifetime + // belongs to KeyspaceManager, including after this snapshot has completed. + return FreezeSchema(ctx, storage, cfg.StartTS, cfg) +} diff --git a/pkg/snapshot/service_mock_test.go b/pkg/snapshot/service_mock_test.go new file mode 100644 index 0000000000..b97db6fe0c --- /dev/null +++ b/pkg/snapshot/service_mock_test.go @@ -0,0 +1,118 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/pingcap/ticdc/pkg/snapshot (interfaces: Nodes,Repository) + +// Package snapshot is a generated GoMock package. +package snapshot + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + common "github.com/pingcap/ticdc/pkg/common" + node "github.com/pingcap/ticdc/pkg/node" + protocol "github.com/pingcap/ticdc/pkg/snapshot/protocol" +) + +// MockNodes is a mock of Nodes interface. +type MockNodes struct { + ctrl *gomock.Controller + recorder *MockNodesMockRecorder +} + +// MockNodesMockRecorder is the mock recorder for MockNodes. +type MockNodesMockRecorder struct { + mock *MockNodes +} + +// NewMockNodes creates a new mock instance. +func NewMockNodes(ctrl *gomock.Controller) *MockNodes { + mock := &MockNodes{ctrl: ctrl} + mock.recorder = &MockNodesMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNodes) EXPECT() *MockNodesMockRecorder { + return m.recorder +} + +// GetAliveNodes mocks base method. +func (m *MockNodes) GetAliveNodes() map[node.ID]*node.Info { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAliveNodes") + ret0, _ := ret[0].(map[node.ID]*node.Info) + return ret0 +} + +// GetAliveNodes indicates an expected call of GetAliveNodes. +func (mr *MockNodesMockRecorder) GetAliveNodes() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAliveNodes", reflect.TypeOf((*MockNodes)(nil).GetAliveNodes)) +} + +// MockRepository is a mock of Repository interface. +type MockRepository struct { + ctrl *gomock.Controller + recorder *MockRepositoryMockRecorder +} + +// MockRepositoryMockRecorder is the mock recorder for MockRepository. +type MockRepositoryMockRecorder struct { + mock *MockRepository +} + +// NewMockRepository creates a new mock instance. +func NewMockRepository(ctrl *gomock.Controller) *MockRepository { + mock := &MockRepository{ctrl: ctrl} + mock.recorder = &MockRepositoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { + return m.recorder +} + +// Bind mocks base method. +func (m *MockRepository) Bind(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64, arg3 *protocol.State, arg4 string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Bind", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(error) + return ret0 +} + +// Bind indicates an expected call of Bind. +func (mr *MockRepositoryMockRecorder) Bind(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bind", reflect.TypeOf((*MockRepository)(nil).Bind), arg0, arg1, arg2, arg3, arg4) +} + +// LoadSnapshot mocks base method. +func (m *MockRepository) LoadSnapshot(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64) (*protocol.State, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "LoadSnapshot", arg0, arg1, arg2) + ret0, _ := ret[0].(*protocol.State) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// LoadSnapshot indicates an expected call of LoadSnapshot. +func (mr *MockRepositoryMockRecorder) LoadSnapshot(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LoadSnapshot", reflect.TypeOf((*MockRepository)(nil).LoadSnapshot), arg0, arg1, arg2) +} + +// SaveSnapshot mocks base method. +func (m *MockRepository) SaveSnapshot(arg0 context.Context, arg1 common.ChangeFeedID, arg2 uint64, arg3 *protocol.State) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SaveSnapshot", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(error) + return ret0 +} + +// SaveSnapshot indicates an expected call of SaveSnapshot. +func (mr *MockRepositoryMockRecorder) SaveSnapshot(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveSnapshot", reflect.TypeOf((*MockRepository)(nil).SaveSnapshot), arg0, arg1, arg2, arg3) +} diff --git a/pkg/snapshot/service_test.go b/pkg/snapshot/service_test.go new file mode 100644 index 0000000000..6f8f16b606 --- /dev/null +++ b/pkg/snapshot/service_test.go @@ -0,0 +1,88 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/golang/mock/gomock" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/messaging" + messagingmock "github.com/pingcap/ticdc/pkg/messaging/mock" + "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/tidb/pkg/kv" + "github.com/stretchr/testify/require" +) + +func TestRemoteStatusKeepsOriginalExecutorAfterMaintainerMove(t *testing.T) { + for _, failed := range []bool{false, true} { + t.Run(fmt.Sprint(failed), func(t *testing.T) { + ctrl := gomock.NewController(t) + repo := NewMockRepository(ctrl) + nodes := NewMockNodes(ctrl) + a := &node.Info{ID: "executor", AdvertiseAddr: "original:8300"} + b := &node.Info{ID: "maintainer", AdvertiseAddr: "new:8300"} + id := common.NewChangeFeedIDWithName("remote", common.DefaultKeyspaceName) + repo.EXPECT().LoadSnapshot(gomock.Any(), id, uint64(7)).Return(&protocol.State{Executor: a.AdvertiseAddr, Phase: "APPLYING"}, nil) + nodes.EXPECT().GetAliveNodes().Return(map[node.ID]*node.Info{a.ID: a, b.ID: b}) + ma := messagingmock.NewMockMessageCenter(ctrl) + mb := messagingmock.NewMockMessageCenter(ctrl) + for _, mc := range []*messagingmock.MockMessageCenter{ma, mb} { + mc.EXPECT().RegisterHandler(controlTopic, gomock.Any()) + mc.EXPECT().DeRegisterHandler(controlTopic) + } + sa := NewService(context.Background(), a, nodes, repo, ma, nil) + sb := NewService(context.Background(), b, nodes, repo, mb, nil) + defer sa.Close(context.Background()) + defer sb.Close(context.Background()) + done := make(chan struct{}) + close(done) + j := &execution{epoch: 7, cancel: func() {}, done: done} + if failed { + j.err = protocol.Invalid("CSE retries exhausted") + } + sa.jobs[id] = j + mb.EXPECT().SendCommand(gomock.Any()).DoAndReturn(func(m *messaging.TargetMessage) error { + require.Equal(t, a.ID, m.To) + m.From = b.ID + return sa.handle(context.Background(), m) + }) + ma.EXPECT().SendCommand(gomock.Any()).DoAndReturn(func(m *messaging.TargetMessage) error { + require.Equal(t, b.ID, m.To) + m.From = a.ID + return sb.handle(context.Background(), m) + }) + cfg := &config.ChangefeedConfig{ChangefeedID: id, Epoch: 7, StartTS: 42, SinkURI: "file:///unused", Snapshot: &protocol.Config{BackupURI: "existing", BackupDigest: strings.Repeat("0", 64)}} + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + err := sb.Bootstrap(ctx, cfg, 1) + if failed { + require.ErrorContains(t, err, "CSE retries exhausted") + } else { + require.NoError(t, err) + } + }) + } +} + +type borrowedStorage struct { + kv.Storage + closed bool +} + +func (s *borrowedStorage) Close() error { s.closed = true; return nil } +func TestSchemaFreezeDoesNotCloseServerStorage(t *testing.T) { + storage := &borrowedStorage{} + calls := 0 + service := &Service{storage: func(context.Context, string) (kv.Storage, error) { calls++; return storage, nil }} + cfg := &config.ChangefeedConfig{Filter: &config.FilterConfig{Rules: []string{"invalid-filter-pattern"}}} + _, _, err := service.freezeSchema(context.Background(), cfg) + require.Error(t, err) + require.Equal(t, 1, calls) + require.False(t, storage.closed) +} diff --git a/pkg/snapshot/state/repository.go b/pkg/snapshot/state/repository.go new file mode 100644 index 0000000000..3fedf46da6 --- /dev/null +++ b/pkg/snapshot/state/repository.go @@ -0,0 +1,94 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package state + +import ( + "context" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/etcd" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + clientv3 "go.etcd.io/etcd/client/v3" +) + +type Repository struct{ Client etcd.CDCEtcdClient } + +func (b *Repository) LoadSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64) (*protocol.State, error) { + info, e := b.Client.GetChangeFeedInfo(ctx, id.DisplayName) + if e != nil { + return nil, protocol.Wrap(e) + } + if info.Epoch != epoch || info.ChangefeedID != id { + return nil, protocol.Invalid("stale snapshot owner") + } + status, _, e := b.Client.GetChangeFeedStatus(ctx, id) + if e != nil { + return nil, protocol.Wrap(e) + } + return status.Snapshot, nil +} + +func (b *Repository) SaveSnapshot(ctx context.Context, id common.ChangeFeedID, epoch uint64, next *protocol.State) error { + return b.save(ctx, id, epoch, next, nil) +} + +// Bind changes placement with an expected previous binding, under the same status CAS. +func (b *Repository) Bind(ctx context.Context, id common.ChangeFeedID, epoch uint64, next *protocol.State, previous string) error { + return b.save(ctx, id, epoch, next, &previous) +} + +func (b *Repository) save(ctx context.Context, id common.ChangeFeedID, epoch uint64, next *protocol.State, previous *string) error { + infoKey := etcd.GetEtcdKeyChangeFeedInfo(b.Client.GetClusterID(), id.DisplayName) + statusKey := etcd.GetEtcdKeyJob(b.Client.GetClusterID(), id.DisplayName) + for retry := 0; retry < 20; retry++ { + ir, e := b.Client.GetEtcdClient().Get(ctx, infoKey) + if e != nil { + return protocol.Wrap(e) + } + if len(ir.Kvs) != 1 { + return protocol.Invalid("changefeed disappeared") + } + var info config.ChangeFeedInfo + if e = info.Unmarshal(ir.Kvs[0].Value); e != nil { + return e + } + if info.Epoch != epoch || info.ChangefeedID != id || !info.State.IsRunning() { + return protocol.Invalid("snapshot owner no longer active") + } + status, rev, e := b.Client.GetChangeFeedStatus(ctx, id) + if e != nil { + return protocol.Wrap(e) + } + if old := status.Snapshot; old != nil { + if old.Generation != next.Generation || old.SnapshotID != next.SnapshotID || old.SnapshotTS != next.SnapshotTS { + return protocol.Invalid("snapshot identity changed") + } + if old.Phase == "SNAPSHOT_COMMITTED" && *old != *next { + return protocol.Invalid("cannot roll back committed snapshot") + } + if (previous == nil && old.Executor != next.Executor) || (previous != nil && old.Executor != *previous) { + return protocol.Invalid("snapshot executor changed") + } + if old.InputDigest != "" && old.InputDigest != next.InputDigest { + return protocol.Invalid("frozen snapshot input changed") + } + } + if next.Phase == "SNAPSHOT_COMMITTED" && (next.PlanRef.URI == "" || next.Applied != next.Total) { + return protocol.Invalid("incomplete snapshot commit") + } + + status.Snapshot = next + bts, e := status.Marshal() + if e != nil { + return e + } + res, e := b.Client.GetEtcdClient().Txn(ctx, []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision(infoKey), "=", ir.Kvs[0].ModRevision), clientv3.Compare(clientv3.ModRevision(statusKey), "=", rev)}, []clientv3.Op{clientv3.OpPut(statusKey, bts)}, nil) + if e != nil { + return protocol.Wrap(e) + } + if res.Succeeded { + return nil + } + } + return protocol.Invalid("snapshot runtime CAS contention") +} diff --git a/pkg/snapshot/state/repository_test.go b/pkg/snapshot/state/repository_test.go new file mode 100644 index 0000000000..1de738dd2d --- /dev/null +++ b/pkg/snapshot/state/repository_test.go @@ -0,0 +1,68 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package state + +import ( + "context" + "testing" + + "github.com/golang/mock/gomock" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/etcd" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/stretchr/testify/require" + "go.etcd.io/etcd/api/v3/mvccpb" + clientv3 "go.etcd.io/etcd/client/v3" +) + +func TestExecutorBindingFencesLateReceiptsAndPreservesStatus(t *testing.T) { + ctrl := gomock.NewController(t) + client := etcd.NewMockCDCEtcdClient(ctrl) + raw := etcd.NewMockClient(ctrl) + client.EXPECT().GetEtcdClient().Return(raw).AnyTimes() + client.EXPECT().GetClusterID().Return("test").AnyTimes() + repo := &Repository{Client: client} + id := common.NewChangeFeedIDWithName("snapshot", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ChangefeedID: id, Epoch: 2, State: config.StateNormal} + data, err := info.Marshal() + require.NoError(t, err) + raw.EXPECT().Get(gomock.Any(), gomock.Any()).Return(&clientv3.GetResponse{Kvs: []*mvccpb.KeyValue{{Value: []byte(data), ModRevision: 7}}}, nil).AnyTimes() + old := &protocol.State{Generation: "g", SnapshotID: "g", SnapshotTS: 42, Executor: "original", InputDigest: "frozen"} + next := *old + next.Executor = "replacement" + client.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(&config.ChangeFeedStatus{Snapshot: old}, int64(9), nil) + require.ErrorContains(t, repo.SaveSnapshot(context.Background(), id, 2, &next), "executor changed") + client.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(&config.ChangeFeedStatus{Snapshot: old, CheckpointTs: 42, Progress: config.ProgressStopping}, int64(10), nil) + raw.EXPECT().Txn(gomock.Any(), gomock.Len(2), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ []clientv3.Cmp, ops []clientv3.Op, _ []clientv3.Op) (*clientv3.TxnResponse, error) { + var got config.ChangeFeedStatus + require.NoError(t, got.Unmarshal(ops[0].ValueBytes())) + require.Equal(t, uint64(42), got.CheckpointTs) + require.Equal(t, config.ProgressStopping, got.Progress) + require.Equal(t, "replacement", got.Snapshot.Executor) + return &clientv3.TxnResponse{Succeeded: true}, nil + }) + require.NoError(t, repo.Bind(context.Background(), id, 2, &next, "original")) + client.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(&config.ChangeFeedStatus{Snapshot: &next}, int64(11), nil) + require.ErrorContains(t, repo.SaveSnapshot(context.Background(), id, 2, old), "executor changed") +} + +func TestPausedSnapshotRemainsReadableButCannotWrite(t *testing.T) { + ctrl := gomock.NewController(t) + client := etcd.NewMockCDCEtcdClient(ctrl) + raw := etcd.NewMockClient(ctrl) + id := common.NewChangeFeedIDWithName("paused", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ChangefeedID: id, Epoch: 2, State: config.StateStopped} + next := &protocol.State{SnapshotID: "snapshot", SnapshotTS: 42, Phase: "APPLYING"} + client.EXPECT().GetChangeFeedInfo(gomock.Any(), id.DisplayName).Return(info, nil) + client.EXPECT().GetChangeFeedStatus(gomock.Any(), id).Return(&config.ChangeFeedStatus{Snapshot: next}, int64(1), nil) + repo := &Repository{Client: client} + got, err := repo.LoadSnapshot(context.Background(), id, 2) + require.NoError(t, err) + require.Equal(t, next, got) + client.EXPECT().GetClusterID().Return("test").AnyTimes() + client.EXPECT().GetEtcdClient().Return(raw).AnyTimes() + data, err := info.Marshal() + require.NoError(t, err) + raw.EXPECT().Get(gomock.Any(), gomock.Any()).Return(&clientv3.GetResponse{Kvs: []*mvccpb.KeyValue{{Value: []byte(data), ModRevision: 7}}}, nil) + require.ErrorContains(t, repo.SaveSnapshot(context.Background(), id, 2, next), "no longer active") +} diff --git a/pkg/snapshot/store/tasks.go b/pkg/snapshot/store/tasks.go index 25984ea217..d88525b308 100644 --- a/pkg/snapshot/store/tasks.go +++ b/pkg/snapshot/store/tasks.go @@ -15,7 +15,6 @@ type Task struct { Export protocol.ObjectRef `json:"export"` Lease uint64 `json:"lease"` Rows uint64 `json:"rows"` - Ack string `json:"ack,omitempty"` } type Page struct { Job string `json:"job"` @@ -151,7 +150,6 @@ func (t Tasks) Commit(id string, lease, rows uint64) error { } x.State = "APPLIED" x.Rows = rows - x.Ack = "kafka-broker-ack" return nil }, false) } diff --git a/pkg/snapshot/validate.go b/pkg/snapshot/validate.go new file mode 100644 index 0000000000..6db148e269 --- /dev/null +++ b/pkg/snapshot/validate.go @@ -0,0 +1,47 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "net/url" + + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/sink/kafka" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/util" +) + +func Validate(cfg *config.ChangefeedConfig) error { + if cfg.Snapshot == nil { + return protocol.Invalid("missing snapshot configuration") + } + if err := cfg.Snapshot.ValidateRuntime(); err != nil { + return err + } + if cfg.Snapshot.BackupURI == "" || len(cfg.Snapshot.BackupDigest) != 64 { + return protocol.Invalid("snapshot requires an existing backup and SHA256 digest") + } + uri, err := url.Parse(cfg.SinkURI) + if err != nil { + return protocol.Wrap(util.MaskSensitiveDataInURLError(err)) + } + switch uri.Scheme { + case config.KafkaScheme, config.KafkaSSLScheme: + options := kafka.NewOptions() + if err = options.Apply(cfg.ChangefeedID, uri, cfg.SinkConfig); err != nil { + return err + } + if options.RequiredAcks == kafka.NoResponse { + return protocol.Invalid("snapshot requires Kafka acknowledgements") + } + case config.S3Scheme, config.FileScheme, config.GCSScheme, config.GSScheme, config.AzblobScheme, config.AzureScheme: + default: + return protocol.Invalid("snapshot supports Kafka and cloud storage sinks") + } + if cfg.Consistent != nil && util.GetOrZero(cfg.Consistent.Level) != "none" && util.GetOrZero(cfg.Consistent.Level) != "" { + return protocol.Invalid("snapshot does not support redo") + } + if cfg.Filter != nil && len(cfg.Filter.EventFilters) > 0 { + return protocol.Invalid("snapshot does not support event filters") + } + return nil +} diff --git a/downstreamadapter/dispatchermanager/snapshot.go b/pkg/snapshot/writer.go similarity index 70% rename from downstreamadapter/dispatchermanager/snapshot.go rename to pkg/snapshot/writer.go index 90e44b7bb0..dfc7ea4e36 100644 --- a/downstreamadapter/dispatchermanager/snapshot.go +++ b/pkg/snapshot/writer.go @@ -1,5 +1,5 @@ // Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package dispatchermanager +package snapshot import ( "bytes" @@ -8,9 +8,11 @@ import ( "sync/atomic" "time" + "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/pkg/common" commonEvent "github.com/pingcap/ticdc/pkg/common/event" "github.com/pingcap/ticdc/pkg/integrity" + "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/tidb/pkg/util/chunk" @@ -34,7 +36,7 @@ type snapshotRuntime struct { // The immutable schema bundle is shared by all range workers of this capture. // Its digest and snapshot identity prevent using live or another generation's // TableInfo while decoding the frozen backup. -func (e *DispatcherManager) getSnapshotRuntime(spec protocol.Spec) (*snapshotRuntime, error) { +func (e *Writer) getSnapshotRuntime(spec protocol.Spec) (*snapshotRuntime, error) { e.snapshotMu.Lock() defer e.snapshotMu.Unlock() if r := e.snapshotRuntime; r != nil { @@ -45,7 +47,7 @@ func (e *DispatcherManager) getSnapshotRuntime(spec protocol.Spec) (*snapshotRun } var cfg *protocol.Config if e.config != nil { - cfg = e.config.Snapshot + cfg = e.config } if err := cfg.ValidateRuntime(); err != nil { return nil, err @@ -111,10 +113,10 @@ func (a *snapshotAcks) wait(ctx context.Context) error { return nil } -// ApplySnapshot mounts bounded batches into the existing capture-owned sink. +// ApplySnapshot mounts bounded batches into this execution attempt's independent sink. // Workers share a byte budget released by broker ACKs. Only range completion // drains all its callbacks; ordinary submission keeps the sink pipeline fed. -func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { +func (e *Writer) ApplySnapshot(ctx context.Context, _ common.ChangeFeedID, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() if e.sinkStopped != nil { @@ -137,7 +139,7 @@ func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spe if err := ctx.Err(); err != nil { return protocol.Wrap(err) } - if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { + if e.epoch != epoch || e.writePathClosed.Load() { return protocol.Invalid("snapshot writer fenced") } return nil @@ -145,6 +147,9 @@ func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spe if err := authorized(); err != nil { return 0, err } + e.applyStarted.Do(func() { e.statistics.Start("apply") }) + e.statistics.Worker("apply", 1) + defer e.statistics.Worker("apply", -1) runtime, err := e.getSnapshotRuntime(spec) if err != nil { return 0, err @@ -166,14 +171,24 @@ func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spe if charge > runtime.limit { return protocol.Invalid("snapshot batch exceeds in-flight byte budget") } + waitStarted := time.Now() if err := runtime.budget.Acquire(ctx, charge); err != nil { return protocol.Wrap(err) } + e.statistics.Observe("write_budget_wait", time.Since(waitStarted)) if err := authorized(); err != nil { runtime.budget.Release(charge) return err } - batch.AddPostFlushFunc(acks.add(func() { runtime.budget.Release(charge) })) + batchBytes, batchRows := uint64(batch.ApproximateSize), uint64(batch.Length) + submittedAt := time.Now() + e.statistics.Add("inflight_bytes", float64(charge)) + batch.AddPostFlushFunc(acks.add(func() { + runtime.budget.Release(charge) + e.statistics.Add("inflight_bytes", -float64(charge)) + e.statistics.Output("apply", batchBytes, batchRows) + e.statistics.Observe("sink_ack", time.Since(submittedAt)) + })) e.writeSink.AddDMLEvent(batch) batch = nil return nil @@ -186,10 +201,10 @@ func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spe } if batch == nil { batch = commonEvent.NewDMLEvent(dispatcherID, ex.Range.TableID, 0, spec.SnapshotTS, table) + batch.TableInfoVersion = spec.SnapshotTS batch.Rows = chunk.NewChunkWithCapacity(table.GetFieldSlice(), snapshotBatchRows) batch.RowTypes = make([]common.RowType, 0, snapshotBatchRows) batch.RowKeys = make([][]byte, 0, snapshotBatchRows) - batch.Snapshot = &commonEvent.SnapshotRow{SnapshotID: spec.SnapshotID, Timestamp: spec.SnapshotTS} } raw := &common.RawKVEntry{Key: key, Value: value, CRTs: spec.SnapshotTS} n, checksum, err := mounter.DecodeToChunk(raw, table, batch.Rows) @@ -230,12 +245,58 @@ func (e *DispatcherManager) ApplySnapshot(ctx context.Context, epoch uint64, spe return rows, nil } -func (e *DispatcherManager) DrainSnapshot(ctx context.Context, epoch uint64) error { +func (e *Writer) DrainSnapshot(ctx context.Context, _ common.ChangeFeedID, epoch uint64) error { if err := ctx.Err(); err != nil { return protocol.Wrap(err) } - if e.GetMaintainerEpoch() != epoch || e.writePathClosed.Load() { + if e.epoch != epoch || e.writePathClosed.Load() { return protocol.Invalid("snapshot drain fenced") } + select { + case <-e.sinkStopped: + return protocol.Invalid("snapshot sink stopped before drain") + default: + } + e.Close() return nil } + +// Writer owns exactly one snapshot sink. All workers share its write budget. +type Writer struct { + ctx context.Context + cancel context.CancelFunc + writeSink sink.Sink + sinkStopped chan struct{} + sinkErr error + epoch uint64 + config *protocol.Config + snapshotMu sync.Mutex + snapshotRuntime *snapshotRuntime + writePathClosed atomic.Bool + closeOnce sync.Once + applyStarted sync.Once + statistics *metrics.SnapshotStatistics +} + +func NewWriter(ctx context.Context, sk sink.Sink, cfg *protocol.Config, epoch uint64, statistics ...*metrics.SnapshotStatistics) *Writer { + ctx, cancel := context.WithCancel(ctx) + w := &Writer{ctx: ctx, cancel: cancel, writeSink: sk, config: cfg, epoch: epoch, sinkStopped: make(chan struct{})} + if len(statistics) > 0 { + w.statistics = statistics[0] + } + go func() { + w.sinkErr = sk.Run(ctx) + if ctx.Err() != nil { + w.sinkErr = nil + } else if w.sinkErr == nil { + w.sinkErr = protocol.Invalid("snapshot sink stopped unexpectedly") + } + close(w.sinkStopped) + }() + return w +} + +func (w *Writer) Close() { + w.closeOnce.Do(func() { w.writePathClosed.Store(true); w.cancel(); <-w.sinkStopped; w.writeSink.Close() }) +} +func (w *Writer) AbortSnapshot(common.ChangeFeedID) { w.Close() } diff --git a/downstreamadapter/dispatchermanager/snapshot_test.go b/pkg/snapshot/writer_test.go similarity index 69% rename from downstreamadapter/dispatchermanager/snapshot_test.go rename to pkg/snapshot/writer_test.go index 096e66d883..32469326e3 100644 --- a/downstreamadapter/dispatchermanager/snapshot_test.go +++ b/pkg/snapshot/writer_test.go @@ -1,11 +1,12 @@ // Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. -package dispatchermanager +package snapshot import ( "bytes" "context" "encoding/binary" "encoding/json" + "fmt" "os" "path/filepath" "testing" @@ -13,10 +14,13 @@ import ( "github.com/golang/mock/gomock" "github.com/pingcap/ticdc/downstreamadapter/sink/mock" + "github.com/pingcap/ticdc/pkg/common" commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" ) @@ -67,12 +71,13 @@ func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { sk := mock.NewMockSink(gomock.NewController(t)) submitted := make(chan *commonEvent.DMLEvent, 4) sk.EXPECT().AddDMLEvent(gomock.Any()).Do(func(ev *commonEvent.DMLEvent) { submitted <- ev }).AnyTimes() - manager := &DispatcherManager{ctx: context.Background(), writeSink: sk, sinkStopped: make(chan struct{})} - manager.meta.maintainerEpoch = 7 + metricFeed := fmt.Sprintf("snapshot-ack-%d", time.Now().UnixNano()) + statistics := metrics.NewSnapshotStatistics("test", metricFeed) + manager := &Writer{statistics: statistics, epoch: 7, ctx: context.Background(), writeSink: sk, sinkStopped: make(chan struct{})} run := func(ctx context.Context) <-chan error { done := make(chan error, 1) go func() { - n, err := manager.ApplySnapshot(ctx, 7, spec, plan, ex) + n, err := manager.ApplySnapshot(ctx, common.ChangeFeedID{}, 7, spec, plan, ex) if err == nil && n != 3 { done <- protocol.Invalid("unexpected count") return @@ -89,6 +94,7 @@ func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { t.Fatal("no batch") } require.EqualValues(t, 3, ev.Length) + require.Equal(t, spec.SnapshotTS, ev.TableInfoVersion) require.Equal(t, 3, ev.Rows.NumRows()) require.Equal(t, "first", ev.Rows.GetRow(0).GetString(1)) require.Equal(t, "third", ev.Rows.GetRow(2).GetString(1)) @@ -99,9 +105,13 @@ func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { t.Fatal("range completed before ACK") default: } + // Metrics must count downstream confirmation, never enqueue. + require.Equal(t, float64(0), snapshotMetricValue(t, "rows_total", metricFeed, "apply")) ev.PostFlush() ev.PostFlush() // duplicate callback must not release budget twice require.NoError(t, <-done) + require.Equal(t, float64(3), snapshotMetricValue(t, "rows_total", metricFeed, "apply")) + require.Equal(t, float64(size), snapshotMetricValue(t, "bytes_total", metricFeed, "apply")) runtime, err := manager.getSnapshotRuntime(spec) require.NoError(t, err) require.True(t, runtime.budget.TryAcquire(runtime.limit)) @@ -160,3 +170,63 @@ func TestSnapshotAcksCancellation(t *testing.T) { require.NoError(t, acks.wait(context.Background())) require.Equal(t, 2, released) } + +func TestWriterOwnsSinkLifetimeAndClosesOnce(t *testing.T) { + for _, fail := range []bool{false, true} { + t.Run(fmt.Sprint(fail), func(t *testing.T) { + sk := mock.NewMockSink(gomock.NewController(t)) + started := make(chan struct{}) + failure := protocol.Invalid("sink failed") + sk.EXPECT().Run(gomock.Any()).DoAndReturn(func(ctx context.Context) error { + close(started) + if fail { + return failure + } + <-ctx.Done() + return ctx.Err() + }) + sk.EXPECT().Close().Times(1) + w := NewWriter(context.Background(), sk, nil, 7) + <-started + if fail { + <-w.sinkStopped + require.ErrorIs(t, w.sinkErr, failure) + } else { + require.NoError(t, w.DrainSnapshot(context.Background(), common.ChangeFeedID{}, 7)) + } + w.Close() + w.Close() + if !fail { + require.NoError(t, w.sinkErr) + } + }) + } +} + +func snapshotMetricValue(t *testing.T, name, changefeed, stage string) float64 { + t.Helper() + registry := prometheus.NewRegistry() + metrics.InitMetrics(registry) + families, err := registry.Gather() + require.NoError(t, err) + for _, family := range families { + if family.GetName() != "ticdc_snapshot_"+name { + continue + } + for _, metric := range family.Metric { + matchFeed, matchStage := false, false + for _, label := range metric.Label { + if label.GetName() == "changefeed" && label.GetValue() == changefeed { + matchFeed = true + } + if label.GetName() == "stage" && label.GetValue() == stage { + matchStage = true + } + } + if matchFeed && matchStage { + return metric.GetCounter().GetValue() + } + } + } + return 0 +} diff --git a/scripts/generate-mock.sh b/scripts/generate-mock.sh index ef89afae77..960d7c496c 100755 --- a/scripts/generate-mock.sh +++ b/scripts/generate-mock.sh @@ -69,6 +69,7 @@ run_mockgen -source pkg/txnutil/gc/gc_client.go -destination pkg/txnutil/gc/gc_c run_mockgen -source pkg/redo/writer/writer.go -destination pkg/redo/writer/writer_mock.go -package writer run_mockgen -source downstreamadapter/sink/sink.go -destination downstreamadapter/sink/mock/sink_mock.go -package mock run_mockgen -destination pkg/messaging/mock/message_center_mock.go -package mock github.com/pingcap/ticdc/pkg/messaging MessageCenter +run_mockgen -destination pkg/snapshot/service_mock_test.go -package snapshot github.com/pingcap/ticdc/pkg/snapshot Nodes,Repository run_mockgen -source pkg/snapshot/bootstrap/interfaces.go -destination pkg/snapshot/bootstrap/interfaces_mock_test.go -package bootstrap wait_for_batch diff --git a/server/server.go b/server/server.go index 20802f79b2..2ac3436efc 100644 --- a/server/server.go +++ b/server/server.go @@ -45,6 +45,8 @@ import ( "github.com/pingcap/ticdc/pkg/pdutil" "github.com/pingcap/ticdc/pkg/security" tiserver "github.com/pingcap/ticdc/pkg/server" + "github.com/pingcap/ticdc/pkg/snapshot" + snapshotstate "github.com/pingcap/ticdc/pkg/snapshot/state" "github.com/pingcap/ticdc/pkg/tcpserver" "github.com/pingcap/ticdc/pkg/upstream" "github.com/pingcap/ticdc/pkg/writelease" @@ -239,7 +241,9 @@ func (c *server) initialize(ctx context.Context) error { NewElector(c, conf.Debug.Scheduler), } + snapshotService := snapshot.NewService(ctx, c.info, nodeManager, &snapshotstate.Repository{Client: c.EtcdClient}, appctx.GetService[messaging.MessageCenter](appctx.MessageCenter), appctx.GetService[keyspace.Manager](appctx.KeyspaceManager).GetStorage) c.subModules = []common.SubModule{ + snapshotService, subscriptionClient, schemaStore, eventStore, diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index 707be7a841..feacf88fa7 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -1,294 +1,84 @@ -# Native CSE snapshot demo +# Native snapshot bootstrap -This demo runs a normal TiCDC changefeed from a frozen CSE packed backup and then -continues consuming TiKV incremental events strictly after the backup TSO `B`. -It uses one TiCDC capture, Kafka open protocol, and a shared local artifact -directory. Snapshot rows are mounted with the schema at `B` and enter the same -capture-owned Kafka sink as incremental rows. +Snapshot execution lives in `pkg/snapshot`. The maintainer waits for snapshot +completion before bootstrapping incremental dispatcher managers. The executor +owns a separate instance of the existing sink; no standalone provider runs. +Schema is frozen directly from upstream metadata at the backup timestamp. -## Embedded local profile (October 2026) +The first version supports Kafka and cloud storage, without initial schema events. +Snapshot rows use the ordinary insert envelope. Delivery is at least once: +recovery can repeat rows. Completion requires every range's sink flush callbacks, +followed by closing the snapshot sink and persisting `SNAPSHOT_COMMITTED`. -The default deployment for the October design runs the export controller inside -TiCDC. No `snapshot-provider` process or Provider HTTP endpoint is needed. -`pkg/snapshot/provider` is the local CSE Runner; the standalone HTTP adapter -below remains for the earlier demo. +## Existing backup and configuration -The capture administrator sets these **server** settings, not the changefeed: +Cloud must create the backup beforehand. Its timestamp must match the +changefeed's `start-ts`. Supply the packed backup manifest URI and SHA256 digest. +The exporter needs the corresponding object storage credentials in its environment. +Do not embed credentials in URLs used in examples or operational output. ```toml -newarch = true -snapshot-cse-binary = "/opt/ticdc/bin/cse-snapshot-wrapper" -snapshot-artifact-dir = "/var/lib/ticdc/snapshot-artifacts" -snapshot-export-workers = 16 -snapshot-min-free-bytes = 10737418240 +[snapshot] +backup-uri = "s3://bucket/path/backup.meta?endpoint=http://object-storage:9000®ion=local" +backup-digest = "" +export-workers = 1 +# Per CSE subprocess: SST file contents cached in memory, not total process RSS. +read-memory-quota-per-process = 536870912 +apply-workers = 4 +# Mounted rows awaiting sink ACKs; shared by all apply workers (default 256 MiB). +# Input chunks and the sink's internal buffers are additional memory. +write-memory-quota = 268435456 +# Entire per-changefeed snapshot directory, including partial export attempts. +# Default is decimal 200 GB. Export admission pauses near the quota; a range +# exceeding it is interrupted and must be retried with a sufficient quota. +disk-quota = 200000000000 ``` -The binary and artifact paths must be absolute. Place the artifact directory on -a persistent volume accessible after a restart on the same node. The capture -image must include a CSE CLI version matching the packed-backup format; the -capture's object-store identity needs read access to the selected backup. The -server controls the CLI path, so a changefeed cannot execute an arbitrary -program. `snapshot-export-workers` is limited to 1–32; the free-space check -pauses new ranges when the artifact filesystem has less than the configured -available space. Applied chunks are deleted only after their broker-ACK receipt -is durable. Keep enough volume headroom for already running ranges. +Disk usage checks are sampled and may briefly overshoot the quota; this is not +a filesystem hard quota. -For the large packed backup used in the performance test, the fixed wrapper -execs the pinned `cse-ctl` with `--file-memory-limit-mib 4096`; the CSE -default of 512 MiB failed on one large packed shard. This is an image/server -setting, never a changefeed setting. Size the Pod memory limit for the number -of concurrent CSE processes and observe their actual RSS. In this lab, the -wrapper and capture receive `DFS_S3_KEY_ID` and `DFS_S3_SECRET_KEY` from the -server environment; Cloud should inject scoped credentials from its secret -mechanism rather than embedding them in changefeed configuration. +All byte quotas are integers. Snapshot files live under +`/snapshot//`, alongside the sorter's parent directory. +Install the matching `cse-ctl` at `/usr/local/bin/cse-ctl`, or set the absolute +server option `--snapshot-cse-binary`. `deployments/snapshot.Dockerfile` accepts +prebuilt `bin/cdc` and `bin/cse-ctl` for a runtime containing both binaries. -A changefeed uses the existing create API/CLI with `[snapshot]` containing -`backup-uri`, `backup-digest`, `apply-workers`, and `inflight-bytes`; an -empty `provider-url` selects the embedded Runner. The selected tables remain -in `[filter]`. This first profile requires one capture and Kafka open protocol. -The plan, range winners, receipts, and final marker remain on the volume and -within the normal changefeed status. An exported range does not release the -incremental barrier: only all durable apply receipts and the final marker do. +## Recovery and multiple CDC nodes -For TiDB Cloud, package the version-matched `cdc` and `cse-ctl` in the capture -image, mount a dedicated persistent volume at the artifact path, grant read -access to the packed backup, and apply the server settings above. The Cloud -control plane then creates one changefeed with the backup URI/digest and table -filter; it does not schedule each range. Pin the active snapshot to the capture -that can access its volume. A lost node/volume is an explicit failed or blocked -snapshot, not an automatic cross-node handoff. Shared S3 artifacts and -distributed task ownership are a later stage. +The first executor is the initial maintainer node. Its advertised address is +persisted, so maintainer migration does not move export work. NodeManager's +alive-node view controls relocation: the address must remain unavailable for +60 seconds. A new process at the original address reuses local files. A new +executor re-exports the same immutable snapshot; duplicate inserts are allowed. +Task leases and `APPLYING` reduce unnecessary retries; durable `APPLIED` receipts +permit chunk deletion. Failed CSE subprocesses get three local attempts, then +report an error through normal changefeed backoff and list/query output. -Build TiCDC with a real semantic release version in ldflags. A bare `go build` -reports `Version: None` and its CLI rejects changefeed creation. For example: +## Validation ```sh -go build -tags=nextgen -ldflags "-X github.com/pingcap/ticdc/pkg/version.ReleaseVersion=v8.5.4 -X github.com/pingcap/ticdc/pkg/version.GitHash=$(git rev-parse HEAD) -X github.com/pingcap/tiflow/pkg/version.ReleaseVersion=v8.5.4" -o bin/cdc ./cmd/cdc +go test -race -tags=intest ./pkg/snapshot/... +NEXT_GEN=1 make cdc ``` -## Modules - -| Module | Responsibility | -| --- | --- | -| CSE `cse-ctl snapshot` | Plan physical ranges and scan the immutable backup into bounded SnapshotKV chunks; no row decoding or sink | -| `pkg/snapshot/protocol` | Versioned artifacts, exact coverage checks, chunk decoder, stable row identity | -| `pkg/snapshot/provider` | Embedded local BR controller/Runner; launch CSE, publish one immutable RangeExport winner, reconcile publication gaps, serve cursor discovery; `cmd/snapshot-provider` remains an optional HTTP adapter for the earlier demo | -| `pkg/snapshot/store` | Single-host durable file CAS, immutable objects and paged range tasks | -| `pkg/snapshot/bootstrap` | Generation, schema freeze, discovery, assignment, receipt and finalization controller | -| `coordinator/changefeed` | Persist the optional snapshot child **inside the existing ChangeFeedStatus key**, with status/info revision and owner-epoch checks | -| `maintainer/snapshot.go` | Gate normal dispatcher bootstrap until final marker is durable | -| `downstreamadapter/{dispatcherorchestrator,dispatchermanager}/snapshot.go` | Local capture assignment interface, mounting, broker acknowledgements, writer drain/fencing | - -No separate CDC global job key is introduced. Task pages contain only range -state. BR owns its source control state separately. Schema/spec/plan/export/chunk -objects are immutable; attempts never overwrite a winner. The final -`SNAPSHOT_COMMITTED` phase and global marker are one status CAS transaction. -Normal checkpoint, pause and epoch updates preserve the snapshot child. - -## Legacy standalone demo build - -Use the `codex/snapshot-e2e-demo` worktree in each repository. The CSE worktree -is based on packed-reader PR #5709 at `ce471b0d203d3e5d3800355e1324a7ed12aa25de`; -the TiCDC worktree is based on `6a1cb553c`. CSE planning uses the current -`sample_range` coverage validation and materialization consumes its lazy -`scan_range` batch stream, retaining the reader's resource ownership. Build on Linux for the development host: - -```sh -# TiCDC repository; VERSION is a demo build label, not a released artifact. -mkdir -p "$RUN/bin" -go build -tags=nextgen -ldflags "-X github.com/pingcap/ticdc/pkg/version.ReleaseVersion=v9.0.0 -X github.com/pingcap/ticdc/pkg/version.GitHash=$(git rev-parse HEAD) -X github.com/pingcap/ticdc/pkg/version.GitBranch=codex/snapshot-e2e-demo" -o "$RUN/bin/cdc" ./cmd/cdc -go build -o "$RUN/bin/snapshot-provider" ./cmd/snapshot-provider -go build -o "$RUN/bin/snapshot-verify" ./tests/integration_tests/native_snapshot/verify - -# CSE repository, pinned nightly toolchain from rust-toolchain.toml. -cargo build -p cse-ctl -cp "${CARGO_TARGET_DIR:-target}/debug/cse-ctl" "$RUN/bin/cse-ctl" -``` - -## Legacy standalone installation on 10.2.15.7 - -The installed run is `/data/nvme0n1/cse-snapshot-demo-20260921`: - -| Component | Address | -| --- | --- | -| Dedicated SQL / keyspace | `127.0.0.1:4400`, `snap_demo_0921` (102), root without password | -| Upstream PD / CSE TiKV | `127.0.0.1:2379`, `10.2.15.7:20160` | -| Native capture API | `http://10.2.15.7:18300` | -| BR Provider | `http://127.0.0.1:18400` | -| CSE lightweight backup worker | `http://127.0.0.1:39000` | -| Kafka | `10.2.15.7:9092` | -| Lab MinIO | `127.0.0.1:19000` | - -The upstream TiKV needs `[cdc] enable=true`. PD 8.5.5 requires the capture's -`enable-legacy-safepoint=true`; API v2 requires a `nextgen` capture build. -Keep TiDB GC retention long enough to cover preparation and incremental catchup. -The helper sets the dedicated SQL keyspace retention to 24 hours; standard CDC -GC protection applies after changefeed creation. Existing SQL port 4000 was -stopped because the old TiDB build's DDL-owner etcd namespace is shared between -keyspaces. Other downstream/Kafka services are unchanged. - -To inspect the existing result (run in the TiCDC checkout on the host): - -```sh -export RUN=/data/nvme0n1/cse-snapshot-demo-20260921 -python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" -python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" -curl -s 'http://127.0.0.1:18300/api/v2/changefeeds/native-snapshot-demo?keyspace=snap_demo_0921' -``` - -To prepare another embedded fixture, use a **new run directory**, copy/build its -binaries, and choose a new capture port, cluster ID, feed ID and Kafka topic. -`--reset-fixture` explicitly drops only the chosen database, not the cluster. - -```sh -# A Python environment with boto3 is needed only for prepare; credentials are -# read from the existing CSE config and never put in the manifest or sink URI. -export CSE=/opt/ticdc/bin/cse-ctl ARTIFACT=/var/lib/ticdc/snapshot-artifacts -export SERVER=http://127.0.0.1:18395 ADDR=10.2.15.7:18395 -python3 tests/integration_tests/native_snapshot/demo.py prepare --root "$RUN" --artifact-root "$ARTIFACT" --embedded-provider --cse-binary "$CSE" --database unique_demo --reset-fixture -python3 tests/integration_tests/native_snapshot/demo.py start --root "$RUN" --artifact-root "$ARTIFACT" --embedded-provider --cse-binary "$CSE" --cluster-id unique-demo-cluster --provider-workers 1 --server "$SERVER" --advertise-addr "$ADDR" -python3 tests/integration_tests/native_snapshot/demo.py create --root "$RUN" --embedded-provider --name unique-demo-feed --topic unique-demo-topic --server "$SERVER" -python3 tests/integration_tests/native_snapshot/demo.py wait --root "$RUN" --name unique-demo-feed --server "$SERVER" -python3 tests/integration_tests/native_snapshot/demo.py verify --root "$RUN" --name unique-demo-feed --topic unique-demo-topic --server "$SERVER" --database unique_demo -``` - -Preparation writes 3,000 accounts and an empty table, takes a lightweight backup, -packs it, hashes the exact manifest, and records `B`. It then executes one update, -one delete, two inserts and `ADD COLUMN revision DEFAULT 0`. `wait` requires both -the durable snapshot marker and a checkpoint beyond those commits. `verify` -checks all original snapshot values and recomputes the stable record ID, rejects -snapshot output after incremental activation, replays DML/DDL, and compares every -final row and all four columns against SQL. It captures topic end offsets at -startup, so run it only after `wait` and without concurrent fixture writes. - -## Continuous incremental validation - -After `demo.py wait`, run the live workload against a fresh fixture: - -```sh -python3 tests/integration_tests/native_snapshot/live.py \ - --root "$RUN" --name unique-demo-feed --topic unique-demo-topic --duration 60 -``` - -The workload repeatedly commits an update, an insert and a delete in one SQL -optimistic transaction (the older lab CSE does not support TiDB's pessimistic -lock-conflict option). While writes are active, it samples Kafka end offsets and replays -the topic, requiring multiple advancing values of the live marker. After writes -stop, it waits for the final checkpoint and compares every row and column with -SQL, including the exact expected incremental event count. Reports and the write -journal stay under `$RUN`. The observed row age includes polling and replay -cost; it is a freshness observation, not a per-event latency benchmark. - -The latest-reader run uses `/data/nvme0n1/cse-snapshot-latest5709-20260921` and -installs its own `bin/cse-ctl`. Pass `--cse-binary "$RUN/bin/cse-ctl"` to -`demo.py prepare` and `start` so a later build cannot replace its exporter. - -The latest-reader validation seeded 3,000 rows plus an empty table at -`B=469229866966581249`. Initial catchup applied four DML events and one DDL, -matching all 3,001 SQL rows. The 60-second live phase committed 526 optimistic -transactions and 1,577 additional DML events; nine samples observed Kafka values -advancing while SQL writes were active. Final replay contained exactly 1,581 -incremental row events and matched all 3,002 SQL rows and columns. - -Killing the capture during `APPLYING` preserved generation -`6d38fc3d-ce47-4b81-ade1-2376cf9966c0`. Restart replayed 128 snapshot rows with -stable IDs; deduplication recovered the same 3,000 snapshot rows, all 1,581 -incremental events, and the matching 3,002 final rows. The already committed -feed retained zero snapshot duplicates after that restart. The wait helper -retries transient API failures while keyspace controllers initialize. - -## Recovery and observed result - -The second changefeed `native-snapshot-recovery` uses topic -`native-snapshot-recovery-20260921`. Its capture was SIGKILLed during APPLYING, -after Kafka had accepted part of a range but before its receipt was durable. -Restart reused generation `faa21988-3856-4376-a900-317b9c5ce7da`, replayed that -range, and then committed the marker and started incremental dispatchers. - -| Scenario | Unique snapshot rows | Replay duplicates | Incremental DML | DDL | Final SQL rows | -| --- | ---: | ---: | ---: | ---: | ---: | -| Initial run | 3,000 | 0 | 4 | 1 | 3,001 | -| Capture killed during APPLYING | 3,000 | 2,816 | 4 | 1 | 3,001 | - -Both runs compare equal for every final row and column. This demonstrates -**at-least-once** snapshot delivery, with stable IDs for downstream deduplication. -An already committed marker prevents snapshot replay on subsequent capture -restarts. Source-controller recovery is also tested at the export-published / -journal-not-updated boundary; status/list polls restart reconciliation. - -## Contract and demo limits - -Snapshot metadata keys in Kafka open protocol are `snapshot_record_id`, -`snapshot_id` and `snapshot_ts`. Full TableInfo is **not** repeated in Kafka rows -or SnapshotKV records. The immutable `schema.json` bundle is referenced by -`Spec.SchemaRef` (size + SHA-256), using the existing `TableInfo.Marshal()` bytes. -Capture verifies and caches it once per snapshot, decoded with -`UnmarshalJSONToTableInfo`. The verifier receives `-spec ` to validate -record identities against this same frozen metadata. - -Capture `[snapshot]` options `apply-workers` (default 4, range 1–32) and -`inflight-bytes` (default 64 MiB, range 32 MiB–1 GiB) are independent of Provider -`-workers`. Mounted batches share one capture-side byte budget, released only by -sink PostFlush callbacks. Each worker additionally holds at most one input chunk -(up to 64 MiB) and one batch (up to 256 rows or about 1 MiB, plus one oversized -record bounded by the 16 MiB record limit). Kafka encoding buffers and the rest -of the capture have their own memory overhead; this budget is not a total RSS -limit. Range workers join before abort or global commit. Per-row RecordIDs remain -independent of batching and concurrency. -Normal incremental event keys remain unchanged. - -Record ID is lowercase SHA-256 of `snapshot-key-v1\0`, u32-BE snapshot-ID byte -length, snapshot-ID UTF-8 bytes, u64-BE physical-table-ID, u32-BE inner-key length, -and the raw inner row key. It deliberately excludes attempt, lease and owner. - -SnapshotKV v1: `SNAPKV01`; u32-LE JSON-header length and header; repeated -u32-LE block length / u32-LE row count / framed records; zero block length, -u32-LE JSON-footer length, footer, `SNAPEND1`. Each record has u32-LE key/value -lengths, key, value. JSON byte fields are base64, counts are JSON u64. SHA-256 -covers the entire stored chunk. Footer and exact length/checksum are mandatory. - -This profile uses uncompressed 1 MiB blocks, 64 MiB target chunks (configurable -1–64 MiB in CSE), 16 MiB record ceiling plus the selected chunk budget, 64 KiB -header/footer, 4 MiB metadata and 512 MiB source file-memory quota. Metadata is -bounded before full allocation. Empty ranges publish a zero-row export/receipt. - -This is not a production distributed exporter: one Provider runs a bounded pool -of local CSE processes; the plan is limited to 4,096 ranges and 2,048 chunks per range. Local -flock/fsync/rename CAS requires one host and shared paths. Capture fencing uses -the local manager epoch and process writer lock. Multi-capture transport, remote -object CAS, Kubernetes Runner pools, compressed/encrypted chunk output, source -repair/retry policy, lake/relational sinks and scale qualification remain outside -this demo. Source backup decryption uses the existing packed reader support. -Per-row schema envelopes favor a simple verifiable demo over Kafka efficiency. -The test replay utility supports this fixture's integer primary key and DDL; -it is not a general open-protocol consumer. - -## Tests - -```sh -go test -tags=intest ./pkg/snapshot/... ./coordinator/changefeed ./pkg/sink/codec/open -go test -tags=intest ./maintainer ./coordinator ./api/v2 ./downstreamadapter/dispatchermanager ./downstreamadapter/dispatcherorchestrator -run '^$' -# CSE repository -cargo test -p cse-ctl snapshot -cargo test -p native_br packed_reader -``` - -### Local parallel export workers - -`demo.py start --provider-workers 4` runs up to four `cse-ctl snapshot -materialize-range` processes concurrently per job. The standalone Provider flag -is `-workers 4` (default 1; accepted range 1–32). Planning still runs once, and -TiCDC retains its existing snapshot consumption path. This is local process -concurrency, not Kubernetes scheduling or multiple TiCDC captures. - -Each worker has a separate attempt directory. Completed exports are validated -and published through the existing immutable winner/CAS journal. A worker error -cancels and joins the other workers before the job becomes FAILED; previously -published valid results remain durable. Recovery reconciles those winners -without exporting them again. - -Completed child processes also leave a diagnostic `worker-stats.json` in their -attempt directory, including user/system CPU seconds, peak RSS, elapsed wall -boundaries, and exit status. This file is optional observability data, not an -export receipt or part of the shared artifact protocol. A failure to write it -does not invalidate an otherwise completed export. +`demo.py` is the small SQL/Kafka fixture driver. Its `prepare` action creates a +backup as test setup, then performs incremental DML and DDL. `start` launches +only CDC; `create`, `wait`, and `verify` check snapshot plus incremental output. +Use `--export-workers` for CSE concurrency. `verify/main.go` identifies snapshot +rows by their commit timestamp matching the supplied immutable spec, and checks +row values, ordering and duplicate row keys without requiring extra Kafka fields. + +## Monitoring + +The TiCDC dashboard includes a Snapshot row with export and sink-ACK throughput, +active workers, range progress, shared write-memory usage, sampled artifact disk +usage, retry/failure counts, and stage and operation durations. Both throughput +series use logical KV key+value bytes. Apply counters advance on PostFlush, not +when a batch is enqueued, and count replayed writes again. Export and apply run +concurrently, so their wall-clock durations must not be added. + +`ticdc_snapshot_cse_cpu_seconds_total` accounts for completed subprocesses' user +and system CPU time; `last_cse_peak_rss_bytes` in `ticdc_snapshot_resource` is the +last completed command's peak RSS, not aggregate live CSE memory. Use process +monitoring for live CDC/CSE CPU and RSS. Artifact disk usage is sampled while CSE +commands run and retains its last sample afterward. diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py index 3f669c6ee3..fb797c7974 100644 --- a/tests/integration_tests/native_snapshot/demo.py +++ b/tests/integration_tests/native_snapshot/demo.py @@ -17,16 +17,13 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=["prepare", "start", "stop", "create", "wait", "verify"]) parser.add_argument("--root", required=True, type=Path) - parser.add_argument("--artifact-root", type=Path, help="persistent snapshot artifact directory") parser.add_argument("--keyspace", default="snap_demo_0921") parser.add_argument("--database", default="snapshot_demo") parser.add_argument("--pd", default="http://127.0.0.1:2379") parser.add_argument("--sql-port", default="4400") parser.add_argument("--broker", default="10.2.15.7:9092") parser.add_argument("--server", default="http://127.0.0.1:18300") - parser.add_argument("--provider-workers", type=int, default=1) - parser.add_argument("--provider", default="http://127.0.0.1:18400") - parser.add_argument("--embedded-provider", action="store_true", help="run the CSE export controller inside TiCDC") + parser.add_argument("--export-workers", type=int, default=1) parser.add_argument("--worker", default="http://127.0.0.1:39000") parser.add_argument("--name", default="native-snapshot-demo") parser.add_argument("--topic", default="native-snapshot-demo-20260921") @@ -39,7 +36,6 @@ def main(): if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", args.database): raise SystemExit("database must be a simple SQL identifier") root = args.root.resolve() - artifact_root = args.artifact_root.resolve() if args.artifact_root else root / "artifacts" root.mkdir(parents=True, exist_ok=True) (root / "logs").mkdir(exist_ok=True) @@ -93,9 +89,7 @@ def get(name): write("target.json", {"checkpoint_ts": target}) config_text = '[filter]\nrules=['+json.dumps(args.database+".*")+']\n[snapshot]\n' snapshot_config = {"backup-uri": manifest["backup_uri"], "backup-digest": manifest["backup_digest"]} - if not args.embedded_provider: - snapshot_config["provider-url"] = args.provider - snapshot_config["artifact-dir"] = str(artifact_root) + snapshot_config["export-workers"] = args.export_workers for k, v in snapshot_config.items(): config_text += k+"="+json.dumps(v)+"\n" (root / "changefeed.toml").write_text(config_text) @@ -107,12 +101,9 @@ def get(name): env.update(DFS_S3_KEY_ID=config("s3-key-id"), DFS_S3_SECRET_KEY=config("s3-secret-key")) from urllib.parse import urlsplit commands = { - "provider": [str(root/"bin/snapshot-provider"), "-root", str(artifact_root), "-cse-binary", args.cse_binary, "-listen", urlsplit(args.provider).netloc, "-workers", str(args.provider_workers)], "cdc": [str(root/"bin/cdc"), "server", "--pd="+args.pd, "--addr=0.0.0.0:"+str(urlsplit(args.server).port), "--advertise-addr="+args.advertise_addr, "--cluster-id="+args.cluster_id, "--data-dir="+str(root/"cdc-data"), "--log-file="+str(root/"logs/cdc.log"), "--config="+str(root/"cdc.toml")], } - if args.embedded_provider: - commands.pop("provider") - commands["cdc"].extend(["--snapshot-cse-binary="+args.cse_binary, "--snapshot-artifact-dir="+str(artifact_root), "--snapshot-export-workers="+str(args.provider_workers)]) + commands["cdc"].extend(["--snapshot-cse-binary="+args.cse_binary]) for name, command in commands.items(): pidfile = root/(name+".pid") if pidfile.exists() and Path("/proc/"+pidfile.read_text()+"/cmdline").exists(): @@ -132,7 +123,7 @@ def get(name): else: raise SystemExit("capture did not become ready; inspect logs/cdc.log") elif args.action == "stop": - for name, binary in [("cdc", "cdc"), ("provider", "snapshot-provider")]: + for name, binary in [("cdc", "cdc")]: pidfile = root/(name+".pid") if not pidfile.exists(): continue diff --git a/tests/integration_tests/native_snapshot/verify/main.go b/tests/integration_tests/native_snapshot/verify/main.go index cd6fd82828..0892cb650a 100644 --- a/tests/integration_tests/native_snapshot/verify/main.go +++ b/tests/integration_tests/native_snapshot/verify/main.go @@ -17,8 +17,6 @@ import ( "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" - "github.com/pingcap/tidb/pkg/kv" - "github.com/pingcap/tidb/pkg/tablecodec" ) type key struct { @@ -179,34 +177,27 @@ func main() { cols = v.Delete } id := number(cols["id"].Value) - if k.ID != "" { + if k.TS == spec.SnapshotTS { if incremental > 0 || ddls > 0 { log.Fatal("snapshot output after incremental activation") } - if k.TS != k.SnapshotTS || k.SnapshotTS == 0 || boundary != 0 && boundary != k.TS { - log.Fatal("snapshot boundary changed") - } boundary = k.TS - tableID := tableIDs[k.DB+"."+k.Table] - if k.Schema != "" || tableID == 0 || k.Snapshot != spec.SnapshotID || k.SnapshotTS != spec.SnapshotTS { - log.Fatal("snapshot metadata mismatch") - } - rawKey := tablecodec.EncodeRowKeyWithHandle(tableID, kv.IntHandle(id)) - if protocol.RecordID(k.Snapshot, tableID, rawKey) != k.ID { - log.Fatal("record ID differs from domain hash") + if tableID == 0 || k.Schema != "" || k.ID != "" || k.Snapshot != "" || k.SnapshotTS != 0 { + log.Fatal("unexpected snapshot envelope") } + recordID := fmt.Sprintf("%d/%d", tableID, id) if id < 1 || id > int64(*seed) || number(cols["balance"].Value) != id*10 || cols["note"].Value != fmt.Sprintf("snapshot-%d", id) || len(cols) != 3 { log.Fatal("snapshot differs from frozen SQL fixture") } - if old, ok := seen[k.ID]; ok { + if old, ok := seen[recordID]; ok { if old != id { - log.Fatal("record ID collision") + log.Fatal("row key collision") } duplicates++ continue } - seen[k.ID] = id + seen[recordID] = id snapshotRows++ } else { if boundary == 0 || k.TS <= boundary { From 455ee4af00edb070a91b0c61db2b045602299efa Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 30 Nov 2026 16:16:01 +0800 Subject: [PATCH 13/17] snapshot: clarify child RSS accounting and wrap long lines --- api/v2/changefeed.go | 42 ++++---- cmd/cdc/server/server.go | 14 ++- pkg/metrics/snapshot.go | 91 +++++++++++++--- pkg/snapshot/bootstrap/controller.go | 20 +++- pkg/snapshot/exporter/exporter.go | 17 ++- pkg/snapshot/protocol/chunk.go | 10 +- pkg/snapshot/protocol/types.go | 23 +++- pkg/snapshot/schema.go | 7 +- pkg/snapshot/service.go | 51 +++++++-- pkg/snapshot/state/repository.go | 5 +- pkg/snapshot/writer.go | 27 ++++- server/server.go | 9 +- .../native_snapshot/README.md | 10 +- .../native_snapshot/compare.py | 17 ++- .../integration_tests/native_snapshot/demo.py | 102 +++++++++++++++--- .../native_snapshot/verify/main.go | 26 ++++- 16 files changed, 393 insertions(+), 78 deletions(-) diff --git a/api/v2/changefeed.go b/api/v2/changefeed.go index d9a325590b..b1d42122cc 100644 --- a/api/v2/changefeed.go +++ b/api/v2/changefeed.go @@ -620,26 +620,28 @@ func CfInfoToAPIModel( } apiInfoModel := &ChangeFeedInfo{ - Snapshot: status.Snapshot, - BootstrapComplete: info.Config == nil || info.Config.Snapshot == nil || status.Snapshot != nil && status.Snapshot.Phase == "SNAPSHOT_COMMITTED", - UpstreamID: info.UpstreamID, - ID: info.ChangefeedID.Name(), - Keyspace: info.ChangefeedID.Keyspace(), - SinkURI: util.MaskSensitiveDataInURI(info.SinkURI), - CreateTime: info.CreateTime, - StartTs: info.StartTs, - TargetTs: info.TargetTs, - AdminJobType: info.AdminJobType, - Config: replicaConfig, - State: info.State, - Error: runningError, - CreatorVersion: info.CreatorVersion, - CheckpointTs: status.CheckpointTs, - ResolvedTs: status.CheckpointTs, - CheckpointTime: api.JSONTime(oracle.GetTimeFromTS(status.CheckpointTs)), - TaskStatus: taskStatus, - MaintainerAddr: status.GetMaintainerAddr(), - GID: info.ChangefeedID.ID(), + Snapshot: status.Snapshot, + BootstrapComplete: info.Config == nil || + info.Config.Snapshot == nil || + status.Snapshot != nil && status.Snapshot.Phase == "SNAPSHOT_COMMITTED", + UpstreamID: info.UpstreamID, + ID: info.ChangefeedID.Name(), + Keyspace: info.ChangefeedID.Keyspace(), + SinkURI: util.MaskSensitiveDataInURI(info.SinkURI), + CreateTime: info.CreateTime, + StartTs: info.StartTs, + TargetTs: info.TargetTs, + AdminJobType: info.AdminJobType, + Config: replicaConfig, + State: info.State, + Error: runningError, + CreatorVersion: info.CreatorVersion, + CheckpointTs: status.CheckpointTs, + ResolvedTs: status.CheckpointTs, + CheckpointTime: api.JSONTime(oracle.GetTimeFromTS(status.CheckpointTs)), + TaskStatus: taskStatus, + MaintainerAddr: status.GetMaintainerAddr(), + GID: info.ChangefeedID.ID(), } return apiInfoModel } diff --git a/cmd/cdc/server/server.go b/cmd/cdc/server/server.go index d54343c196..0ebef3c642 100644 --- a/cmd/cdc/server/server.go +++ b/cmd/cdc/server/server.go @@ -76,8 +76,18 @@ func (o *options) addFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&o.serverConfig.LogLevel, "log-level", o.serverConfig.LogLevel, "log level (etc: debug|info|warn|error)") cmd.Flags().StringVar(&o.serverConfig.DataDir, "data-dir", o.serverConfig.DataDir, "the path to the directory used to store TiCDC-generated data") - cmd.Flags().StringVar(&o.serverConfig.SnapshotCSEBinary, "snapshot-cse-binary", o.serverConfig.SnapshotCSEBinary, "CSE binary for embedded packed-backup snapshot export") - cmd.Flags().Int64Var(&o.serverConfig.SnapshotMinFreeBytes, "snapshot-min-free-bytes", o.serverConfig.SnapshotMinFreeBytes, "minimum free bytes before starting another snapshot range") + cmd.Flags().StringVar( + &o.serverConfig.SnapshotCSEBinary, + "snapshot-cse-binary", + o.serverConfig.SnapshotCSEBinary, + "CSE binary for embedded packed-backup snapshot export", + ) + cmd.Flags().Int64Var( + &o.serverConfig.SnapshotMinFreeBytes, + "snapshot-min-free-bytes", + o.serverConfig.SnapshotMinFreeBytes, + "minimum free bytes before starting another snapshot range", + ) cmd.Flags().StringSliceVar(&o.pdEndpoints, "pd", []string{"http://127.0.0.1:2379"}, "Set the PD endpoints to use. Use ',' to separate multiple PDs") cmd.Flags().StringVar(&o.serverConfigFilePath, "config", "", "Path of the configuration file") diff --git a/pkg/metrics/snapshot.go b/pkg/metrics/snapshot.go index 118390f8fa..39b979b349 100644 --- a/pkg/metrics/snapshot.go +++ b/pkg/metrics/snapshot.go @@ -10,20 +10,82 @@ import ( var snapshotLabels = []string{GetKeyspaceLabel(), "changefeed", "stage"} var ( - snapshotRetries = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "retries_total", Help: "CSE command retries started after a failed attempt."}, snapshotLabels) - snapshotBytes = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "bytes_total", Help: "Logical KV bytes published by export or acknowledged by the sink, including replayed writes."}, snapshotLabels) - snapshotRows = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "rows_total", Help: "KV rows published by export or acknowledged by the sink, including replayed writes."}, snapshotLabels) - snapshotStarted = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "stage_started_timestamp_seconds", Help: "Start of the latest execution attempt's stage. Export and apply overlap."}, snapshotLabels) - snapshotFinished = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "stage_finished_timestamp_seconds", Help: "Successful finish of the latest execution attempt's stage; zero while unfinished."}, snapshotLabels) - snapshotWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "active_workers", Help: "Active CSE commands or range apply workers."}, snapshotLabels) - snapshotDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "operation_duration_seconds", Help: "CSE command, shared write-budget acquisition, and batch enqueue-to-ACK duration.", Buckets: prometheus.ExponentialBuckets(0.001, 4, 11)}, snapshotLabels) - snapshotErrors = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "errors_total", Help: "Failed CSE commands or snapshot executions. Canceled executions are included."}, snapshotLabels) - snapshotCPU = prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "cse_cpu_seconds_total", Help: "Completed CSE commands' user and system CPU seconds."}, []string{GetKeyspaceLabel(), "changefeed"}) - snapshotValues = prometheus.NewGaugeVec(prometheus.GaugeOpts{Namespace: "ticdc", Subsystem: "snapshot", Name: "resource", Help: "Snapshot resource/progress values; kind identifies bytes, configured limits, or range counts."}, []string{GetKeyspaceLabel(), "changefeed", "kind"}) + snapshotRetries = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "retries_total", + Help: "CSE command retries started after a failed attempt.", + }, snapshotLabels) + snapshotBytes = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "bytes_total", + Help: "Logical KV bytes published by export or acknowledged by the sink, including replayed writes.", + }, snapshotLabels) + snapshotRows = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "rows_total", + Help: "KV rows published by export or acknowledged by the sink, including replayed writes.", + }, snapshotLabels) + snapshotStarted = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "stage_started_timestamp_seconds", + Help: "Start of the latest execution attempt's stage. Export and apply overlap.", + }, snapshotLabels) + snapshotFinished = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "stage_finished_timestamp_seconds", + Help: "Successful finish of the latest execution attempt's stage; zero while unfinished.", + }, snapshotLabels) + snapshotWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "active_workers", + Help: "Active CSE commands or range apply workers.", + }, snapshotLabels) + snapshotDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "operation_duration_seconds", + Help: "CSE command, shared write-budget acquisition, and batch enqueue-to-ACK duration.", + Buckets: prometheus.ExponentialBuckets(0.001, 4, 11), + }, snapshotLabels) + snapshotErrors = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "errors_total", + Help: "Failed CSE commands or snapshot executions. Canceled executions are included.", + }, snapshotLabels) + snapshotCPU = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "cse_cpu_seconds_total", + Help: "Completed CSE commands' user and system CPU seconds.", + }, []string{GetKeyspaceLabel(), "changefeed"}) + snapshotValues = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", + Subsystem: "snapshot", + Name: "resource", + Help: "Snapshot resource/progress values; kind identifies bytes, configured limits, or range counts.", + }, []string{GetKeyspaceLabel(), "changefeed", "kind"}) ) func initSnapshotMetrics(r *prometheus.Registry) { - r.MustRegister(snapshotBytes, snapshotRows, snapshotStarted, snapshotFinished, snapshotWorkers, snapshotDuration, snapshotErrors, snapshotRetries, snapshotCPU, snapshotValues) + r.MustRegister( + snapshotBytes, + snapshotRows, + snapshotStarted, + snapshotFinished, + snapshotWorkers, + snapshotDuration, + snapshotErrors, + snapshotRetries, + snapshotCPU, + snapshotValues, + ) } // SnapshotStatistics is shared by one executor's exporter, controller and sink. @@ -88,13 +150,14 @@ func (s *SnapshotStatistics) Add(kind string, delta float64) { } } -func (s *SnapshotStatistics) Process(cpu float64, peakRSS int64) { +func (s *SnapshotStatistics) Process(cpu float64, accountingPeakRSS int64) { if s == nil { return } snapshotCPU.WithLabelValues(s.keyspace, s.changefeed).Add(cpu) - // Per-command peak, rather than a sum of non-concurrent high-water marks. - s.Set("last_cse_peak_rss_bytes", float64(peakRSS)) + // This is child resource accounting from wait4. On Linux, its RSS high-water + // mark may include parent memory inherited before exec, rather than CSE runtime RSS. + s.Set("last_child_accounting_peak_rss_bytes", float64(accountingPeakRSS)) } func (s *SnapshotStatistics) Retry(operation string) { diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go index ae89eaeed4..e23d4ca326 100644 --- a/pkg/snapshot/bootstrap/controller.go +++ b/pkg/snapshot/bootstrap/controller.go @@ -100,7 +100,17 @@ func (c Controller) Run(ctx context.Context) (result error) { if err != nil { return err } - spec := protocol.Spec{ProtocolVersion: 1, JobID: state.Generation, SnapshotID: state.SnapshotID, SnapshotTS: c.TS, KeyspaceID: c.Keyspace, BackupURI: c.Config.BackupURI, BackupDigest: c.Config.BackupDigest, SelectedSpans: spans, SchemaRef: schema} + spec := protocol.Spec{ + ProtocolVersion: 1, + JobID: state.Generation, + SnapshotID: state.SnapshotID, + SnapshotTS: c.TS, + KeyspaceID: c.Keyspace, + BackupURI: c.Config.BackupURI, + BackupDigest: c.Config.BackupDigest, + SelectedSpans: spans, + SchemaRef: schema, + } state.SpecRef, err = objects.Put("cdc/"+state.Generation+"/spec.json", spec) if err != nil { return err @@ -270,7 +280,13 @@ func (c Controller) Run(ctx context.Context) (result error) { // All workers are joined before Run can abort the sink or release writer.lock. // Task page writes stay serialized; data application is bounded and concurrent. -func (c Controller) applyReady(ctx context.Context, tasks store.Tasks, spec protocol.Spec, ref protocol.ObjectRef, ready []store.Task) error { +func (c Controller) applyReady( + ctx context.Context, + tasks store.Tasks, + spec protocol.Spec, + ref protocol.ObjectRef, + ready []store.Task, +) error { if len(ready) == 0 { return nil } diff --git a/pkg/snapshot/exporter/exporter.go b/pkg/snapshot/exporter/exporter.go index 7081fea317..ae70f73c45 100644 --- a/pkg/snapshot/exporter/exporter.go +++ b/pkg/snapshot/exporter/exporter.go @@ -228,7 +228,15 @@ func (s *Runner) batch(ctx context.Context, id, command string, task map[string] // Observability only: worker resource accounting is not part of the export // protocol and must never turn a completed export into a failed attempt. if state := cmd.ProcessState; state != nil { - stats := map[string]any{"command": command, "pid": state.Pid(), "started_at": started.UnixNano(), "finished_at": time.Now().UnixNano(), "user_cpu_seconds": state.UserTime().Seconds(), "system_cpu_seconds": state.SystemTime().Seconds(), "success": state.Success()} + stats := map[string]any{ + "command": command, + "pid": state.Pid(), + "started_at": started.UnixNano(), + "finished_at": time.Now().UnixNano(), + "user_cpu_seconds": state.UserTime().Seconds(), + "system_cpu_seconds": state.SystemTime().Seconds(), + "success": state.Success(), + } if usage, ok := state.SysUsage().(*syscall.Rusage); ok { peakRSS := usage.Maxrss if runtime.GOOS != "darwin" { @@ -388,7 +396,12 @@ func (s *Runner) materialize(ctx context.Context, id string, j Job, r protocol.S return e } ref, e := retryBatch(ctx, func() (protocol.ObjectRef, error) { - return s.batch(ctx, id, "materialize-range", map[string]any{"spec": j.Spec, "range": r, "plan_digest": j.PlanRef.Digest, "chunk_bytes": 64 << 20}) + return s.batch(ctx, id, "materialize-range", map[string]any{ + "spec": j.Spec, + "range": r, + "plan_digest": j.PlanRef.Digest, + "chunk_bytes": 64 << 20, + }) }, func() { s.Statistics.Retry("materialize-range") }) if e != nil { return e diff --git a/pkg/snapshot/protocol/chunk.go b/pkg/snapshot/protocol/chunk.go index f650a4dea7..0943598451 100644 --- a/pkg/snapshot/protocol/chunk.go +++ b/pkg/snapshot/protocol/chunk.go @@ -144,7 +144,15 @@ func decode(r io.Reader, expected Header, span Span, ref Chunk, emit func([]byte if n, err := r.Read(tail[:]); n != 0 || err != io.EOF { return seen, Invalid("trailing chunk bytes") } - if footer.Blocks != seen.Blocks || footer.KVCount != seen.KVCount || footer.LogicalBytes != seen.LogicalBytes || !bytes.Equal(footer.First, seen.First) || !bytes.Equal(footer.Last, seen.Last) || footer.KVCount != ref.KVCount || footer.LogicalBytes != ref.LogicalBytes || !bytes.Equal(footer.First, ref.First) || !bytes.Equal(footer.Last, ref.Last) { + if footer.Blocks != seen.Blocks || + footer.KVCount != seen.KVCount || + footer.LogicalBytes != seen.LogicalBytes || + !bytes.Equal(footer.First, seen.First) || + !bytes.Equal(footer.Last, seen.Last) || + footer.KVCount != ref.KVCount || + footer.LogicalBytes != ref.LogicalBytes || + !bytes.Equal(footer.First, ref.First) || + !bytes.Equal(footer.Last, ref.Last) { return seen, Invalid("footer/statistics mismatch") } return footer, nil diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go index 451521ae75..d9a137ceac 100644 --- a/pkg/snapshot/protocol/types.go +++ b/pkg/snapshot/protocol/types.go @@ -240,7 +240,11 @@ func ValidatePlan(spec Spec, p Plan) error { next := s.Start for idx < len(ranges) && ranges[idx].TableID == s.TableID && bytes.Compare(ranges[idx].Start, s.End) < 0 { r := ranges[idx] - if r.RangeID == "" || ids[r.RangeID] || !bytes.Equal(r.Start, next) || bytes.Compare(r.Start, r.End) >= 0 || bytes.Compare(r.End, s.End) > 0 { + if r.RangeID == "" || + ids[r.RangeID] || + !bytes.Equal(r.Start, next) || + bytes.Compare(r.Start, r.End) >= 0 || + bytes.Compare(r.End, s.End) > 0 { return Invalid("coverage hole, overlap, or duplicate range") } ids[r.RangeID] = true @@ -258,13 +262,26 @@ func ValidatePlan(spec Spec, p Plan) error { } func ValidateExport(spec Spec, plan ObjectRef, r Span, e Export) error { - if e.ProtocolVersion != 1 || e.JobID != spec.JobID || e.SnapshotID != spec.SnapshotID || e.SnapshotTS != spec.SnapshotTS || e.PlanDigest != plan.Digest || !SameSpan(r, e.Range) || e.AttemptID == "" { + if e.ProtocolVersion != 1 || + e.JobID != spec.JobID || + e.SnapshotID != spec.SnapshotID || + e.SnapshotTS != spec.SnapshotTS || + e.PlanDigest != plan.Digest || + !SameSpan(r, e.Range) || + e.AttemptID == "" { return Invalid("export identity mismatch") } var count uint64 var last []byte for _, c := range e.Chunks { - if c.Size <= 0 || c.Size > 64<<20 || c.KVCount == 0 || len(c.Digest) != 64 || bytes.Compare(c.First, r.Start) < 0 || bytes.Compare(c.First, c.Last) > 0 || bytes.Compare(c.Last, r.End) >= 0 || last != nil && bytes.Compare(last, c.First) >= 0 { + if c.Size <= 0 || + c.Size > 64<<20 || + c.KVCount == 0 || + len(c.Digest) != 64 || + bytes.Compare(c.First, r.Start) < 0 || + bytes.Compare(c.First, c.Last) > 0 || + bytes.Compare(c.Last, r.End) >= 0 || + last != nil && bytes.Compare(last, c.First) >= 0 { return Invalid("invalid chunk bounds or size") } last = c.Last diff --git a/pkg/snapshot/schema.go b/pkg/snapshot/schema.go index 546843d331..eaa51e879c 100644 --- a/pkg/snapshot/schema.go +++ b/pkg/snapshot/schema.go @@ -19,7 +19,12 @@ import ( // FreezeSchema reads metadata at the backup timestamp directly. It never // registers tables or versions in the incremental SchemaStore. -func FreezeSchema(ctx context.Context, storage kv.Storage, ts uint64, cfg *config.ChangefeedConfig) (bootstrap.SchemaBundle, []protocol.Span, error) { +func FreezeSchema( + ctx context.Context, + storage kv.Storage, + ts uint64, + cfg *config.ChangefeedConfig, +) (bootstrap.SchemaBundle, []protocol.Span, error) { bundle := bootstrap.SchemaBundle{SnapshotTS: ts} f, err := filter.NewFilter(cfg.Filter, "", cfg.CaseSensitive, cfg.ForceReplicate) if err != nil { diff --git a/pkg/snapshot/service.go b/pkg/snapshot/service.go index c8d36335dc..578e1618f7 100644 --- a/pkg/snapshot/service.go +++ b/pkg/snapshot/service.go @@ -71,8 +71,24 @@ type Service struct { waiters map[string]chan response } -func NewService(ctx context.Context, self *node.Info, nodes Nodes, repo Repository, mc messaging.MessageCenter, storage StorageGetter) *Service { - s := &Service{ctx: ctx, self: self, nodes: nodes, repo: repo, mc: mc, storage: storage, jobs: make(map[common.ChangeFeedID]*execution), waiters: make(map[string]chan response)} +func NewService( + ctx context.Context, + self *node.Info, + nodes Nodes, + repo Repository, + mc messaging.MessageCenter, + storage StorageGetter, +) *Service { + s := &Service{ + ctx: ctx, + self: self, + nodes: nodes, + repo: repo, + mc: mc, + storage: storage, + jobs: make(map[common.ChangeFeedID]*execution), + waiters: make(map[string]chan response), + } mc.RegisterHandler(controlTopic, s.handle) return s } @@ -167,7 +183,10 @@ func (s *Service) poll(ctx context.Context, target node.ID, req request) (respon if err != nil { return response{}, protocol.Wrap(err) } - if err = s.mc.SendCommand(messaging.NewSingleTargetMessage(target, controlTopic, &protocol.Message{RequestID: id, Payload: payload})); err != nil { + if err = s.mc.SendCommand(messaging.NewSingleTargetMessage(target, controlTopic, &protocol.Message{ + RequestID: id, + Payload: payload, + })); err != nil { return response{}, err } timer := time.NewTimer(time.Second) @@ -211,7 +230,11 @@ func (s *Service) handle(_ context.Context, msg *messaging.TargetMessage) error if err != nil { return protocol.Wrap(err) } - return s.mc.SendCommand(messaging.NewSingleTargetMessage(msg.From, controlTopic, &protocol.Message{RequestID: m.RequestID, Response: true, Payload: b})) + return s.mc.SendCommand(messaging.NewSingleTargetMessage(msg.From, controlTopic, &protocol.Message{ + RequestID: m.RequestID, + Response: true, + Payload: b, + })) } func (s *Service) status(req request) response { @@ -331,9 +354,23 @@ func (s *Service) execute(ctx context.Context, req request) error { } } }() - ctl := bootstrap.Controller{Statistics: statistics, DestinationDigest: protocol.Digest(destination), ID: cfg.ChangefeedID, Epoch: cfg.Epoch, TS: cfg.StartTS, Keyspace: req.Keyspace, Config: cfg.Snapshot, ArtifactDir: dir, CSEBinary: server.SnapshotCSEBinary, MinFreeBytes: server.SnapshotMinFreeBytes, Repository: s.repo, Capture: writer, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { - return bundle, spans, nil - }} + ctl := bootstrap.Controller{ + Statistics: statistics, + DestinationDigest: protocol.Digest(destination), + ID: cfg.ChangefeedID, + Epoch: cfg.Epoch, + TS: cfg.StartTS, + Keyspace: req.Keyspace, + Config: cfg.Snapshot, + ArtifactDir: dir, + CSEBinary: server.SnapshotCSEBinary, + MinFreeBytes: server.SnapshotMinFreeBytes, + Repository: s.repo, + Capture: writer, + Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { + return bundle, spans, nil + }, + } err = ctl.Run(ctx) if err == nil { statistics.Finish("apply") diff --git a/pkg/snapshot/state/repository.go b/pkg/snapshot/state/repository.go index 3fedf46da6..8f5348d1dc 100644 --- a/pkg/snapshot/state/repository.go +++ b/pkg/snapshot/state/repository.go @@ -82,7 +82,10 @@ func (b *Repository) save(ctx context.Context, id common.ChangeFeedID, epoch uin if e != nil { return e } - res, e := b.Client.GetEtcdClient().Txn(ctx, []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision(infoKey), "=", ir.Kvs[0].ModRevision), clientv3.Compare(clientv3.ModRevision(statusKey), "=", rev)}, []clientv3.Op{clientv3.OpPut(statusKey, bts)}, nil) + res, e := b.Client.GetEtcdClient().Txn(ctx, []clientv3.Cmp{ + clientv3.Compare(clientv3.ModRevision(infoKey), "=", ir.Kvs[0].ModRevision), + clientv3.Compare(clientv3.ModRevision(statusKey), "=", rev), + }, []clientv3.Op{clientv3.OpPut(statusKey, bts)}, nil) if e != nil { return protocol.Wrap(e) } diff --git a/pkg/snapshot/writer.go b/pkg/snapshot/writer.go index dfc7ea4e36..bea6a5b2d4 100644 --- a/pkg/snapshot/writer.go +++ b/pkg/snapshot/writer.go @@ -40,7 +40,10 @@ func (e *Writer) getSnapshotRuntime(spec protocol.Spec) (*snapshotRuntime, error e.snapshotMu.Lock() defer e.snapshotMu.Unlock() if r := e.snapshotRuntime; r != nil { - if r.spec.JobID != spec.JobID || r.spec.SnapshotID != spec.SnapshotID || r.spec.SnapshotTS != spec.SnapshotTS || r.spec.SchemaRef != spec.SchemaRef { + if r.spec.JobID != spec.JobID || + r.spec.SnapshotID != spec.SnapshotID || + r.spec.SnapshotTS != spec.SnapshotTS || + r.spec.SchemaRef != spec.SchemaRef { return nil, protocol.Invalid("snapshot schema identity changed") } return r, nil @@ -116,7 +119,14 @@ func (a *snapshotAcks) wait(ctx context.Context) error { // ApplySnapshot mounts bounded batches into this execution attempt's independent sink. // Workers share a byte budget released by broker ACKs. Only range completion // drains all its callbacks; ordinary submission keeps the sink pipeline fed. -func (e *Writer) ApplySnapshot(ctx context.Context, _ common.ChangeFeedID, epoch uint64, spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export) (uint64, error) { +func (e *Writer) ApplySnapshot( + ctx context.Context, + _ common.ChangeFeedID, + epoch uint64, + spec protocol.Spec, + ref protocol.ObjectRef, + ex protocol.Export, +) (uint64, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() if e.sinkStopped != nil { @@ -194,7 +204,18 @@ func (e *Writer) ApplySnapshot(ctx context.Context, _ common.ChangeFeedID, epoch return nil } for seq, c := range ex.Chunks { - expected := protocol.Header{Version: 1, Compression: "none", JobID: spec.JobID, SnapshotID: spec.SnapshotID, SnapshotTS: spec.SnapshotTS, PlanDigest: ref.Digest, RangeID: ex.Range.RangeID, AttemptID: ex.AttemptID, TableID: ex.Range.TableID, Seq: uint64(seq)} + expected := protocol.Header{ + Version: 1, + Compression: "none", + JobID: spec.JobID, + SnapshotID: spec.SnapshotID, + SnapshotTS: spec.SnapshotTS, + PlanDigest: ref.Digest, + RangeID: ex.Range.RangeID, + AttemptID: ex.AttemptID, + TableID: ex.Range.TableID, + Seq: uint64(seq), + } _, err := protocol.DecodeChunk(c, expected, ex.Range, func(key, value []byte) error { if err := authorized(); err != nil { return err diff --git a/server/server.go b/server/server.go index 2ac3436efc..baa47451d8 100644 --- a/server/server.go +++ b/server/server.go @@ -241,7 +241,14 @@ func (c *server) initialize(ctx context.Context) error { NewElector(c, conf.Debug.Scheduler), } - snapshotService := snapshot.NewService(ctx, c.info, nodeManager, &snapshotstate.Repository{Client: c.EtcdClient}, appctx.GetService[messaging.MessageCenter](appctx.MessageCenter), appctx.GetService[keyspace.Manager](appctx.KeyspaceManager).GetStorage) + snapshotService := snapshot.NewService( + ctx, + c.info, + nodeManager, + &snapshotstate.Repository{Client: c.EtcdClient}, + appctx.GetService[messaging.MessageCenter](appctx.MessageCenter), + appctx.GetService[keyspace.Manager](appctx.KeyspaceManager).GetStorage, + ) c.subModules = []common.SubModule{ snapshotService, subscriptionClient, diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index feacf88fa7..4ad1ae9034 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -78,7 +78,9 @@ when a batch is enqueued, and count replayed writes again. Export and apply run concurrently, so their wall-clock durations must not be added. `ticdc_snapshot_cse_cpu_seconds_total` accounts for completed subprocesses' user -and system CPU time; `last_cse_peak_rss_bytes` in `ticdc_snapshot_resource` is the -last completed command's peak RSS, not aggregate live CSE memory. Use process -monitoring for live CDC/CSE CPU and RSS. Artifact disk usage is sampled while CSE -commands run and retains its last sample afterward. +and system CPU time. `last_child_accounting_peak_rss_bytes` in +`ticdc_snapshot_resource` and `peak_rss_bytes` in `worker-stats.json` report the +last completed child's `wait4` resource-accounting high-water mark. On Linux, +this can include parent RSS inherited before exec; it does not measure CSE's +runtime RSS. Use live process sampling for CDC/CSE CPU and RSS. Artifact disk +usage is sampled while CSE commands run and retains its last sample afterward. diff --git a/tests/integration_tests/native_snapshot/compare.py b/tests/integration_tests/native_snapshot/compare.py index 717487cd91..392bb1c311 100644 --- a/tests/integration_tests/native_snapshot/compare.py +++ b/tests/integration_tests/native_snapshot/compare.py @@ -15,8 +15,21 @@ raise SystemExit("invalid database") result = json.load(open(args.result)) sql = "SELECT JSON_OBJECT('id',id,'balance',balance,'note',note,'revision',revision) FROM "+args.database+".accounts ORDER BY id" -data = subprocess.check_output(["mysql", "--batch", "--raw", "--skip-column-names", "-h"+args.host, "-P"+args.port, "-u"+args.user, "-e", sql], text=True) +data = subprocess.check_output(["mysql", + "--batch", + "--raw", + "--skip-column-names", + "-h"+args.host, + "-P"+args.port, + "-u"+args.user, + "-e", + sql], + text=True) expected = {str(row["id"]): row for row in map(json.loads, data.splitlines())} assert result["final_rows"] == expected, "Kafka replay differs from SQL rows" assert result["incremental_rows"] >= 4 and result["ddl_events"] >= 1 -print(json.dumps({"sql_rows": len(expected), "all_columns_equal": True, **{k: v for k, v in result.items() if k != "final_rows"}}, indent=2)) +print(json.dumps({"sql_rows": len(expected), + "all_columns_equal": True, + **{k: v for k, + v in result.items() if k != "final_rows"}}, + indent=2)) diff --git a/tests/integration_tests/native_snapshot/demo.py b/tests/integration_tests/native_snapshot/demo.py index fb797c7974..85f8fc9300 100644 --- a/tests/integration_tests/native_snapshot/demo.py +++ b/tests/integration_tests/native_snapshot/demo.py @@ -40,10 +40,21 @@ def main(): (root / "logs").mkdir(exist_ok=True) def sql(query): - return subprocess.check_output(["mysql", "--batch", "--raw", "--skip-column-names", "-h127.0.0.1", "-P"+args.sql_port, "-uroot", "-e", query], text=True) + return subprocess.check_output(["mysql", + "--batch", + "--raw", + "--skip-column-names", + "-h127.0.0.1", + "-P"+args.sql_port, + "-uroot", + "-e", + query], + text=True) def http(url, data=None): - request = urllib.request.Request(url, data=None if data is None else json.dumps(data).encode(), headers={"Content-Type": "application/json"}) + request = urllib.request.Request(url, + data=None if data is None else json.dumps(data).encode(), + headers={"Content-Type": "application/json"}) return json.load(urllib.request.urlopen(request, timeout=120)) def write(name, value): @@ -63,27 +74,58 @@ def get(name): raise SystemExit("TiCDC keyspace names must be at most 20 characters") if args.reset_fixture: sql("DROP DATABASE IF EXISTS " + args.database) - sql('CREATE DATABASE '+args.database+'; CREATE TABLE '+args.database+'.accounts(id BIGINT PRIMARY KEY,balance BIGINT NOT NULL,note VARCHAR(100)); CREATE TABLE '+args.database+'.empty_table(id INT PRIMARY KEY); SET GLOBAL tidb_gc_life_time="24h";') + sql('CREATE DATABASE '+args.database+'; CREATE TABLE '+args.database+'.accounts(id BIGINT PRIMARY KEY,balance BIGINT NOT NULL,note' + ' VARCHAR(100)); CREATE TABLE '+args.database+'.empty_table(id INT PRIMARY KEY); SET GLOBAL tidb_gc_life_time="24h";') for start in range(1, 3001, 500): values = ",".join("(%d,%d,'snapshot-%d')" % (i, i*10, i) for i in range(start, start+500)) sql("INSERT INTO "+args.database+".accounts VALUES " + values) backup = http(args.worker+"/api/v1/x/cluster/lightweight_backup", {}) write("backup.json", backup) with (root / "logs/pack.log").open("w") as log: - subprocess.run([args.cse_binary, "pack-backup", "--config", args.cse_config, "--backup-name", backup["backup_name"], "--keyspace-name", args.keyspace, "--data-dir", str(root/"pack-work")], stdout=log, stderr=subprocess.STDOUT, check=True) - info = subprocess.check_output([args.cse_binary, "show", "backup", "--config", args.cse_config, "--name", backup["backup_name"]], stderr=subprocess.STDOUT, text=True) + subprocess.run([args.cse_binary, + "pack-backup", + "--config", + args.cse_config, + "--backup-name", + backup["backup_name"], + "--keyspace-name", + args.keyspace, + "--data-dir", + str(root/"pack-work")], + stdout=log, + stderr=subprocess.STDOUT, + check=True) + info = subprocess.check_output([args.cse_binary, + "show", + "backup", + "--config", + args.cse_config, + "--name", + backup["backup_name"]], + stderr=subprocess.STDOUT, + text=True) (root / "logs/backup-info.log").write_text(info) ts = int(re.search(r"backup_ts:\s*(\d+)", info).group(1)) path = re.search(r"Copyable path: (\S+)", (root/"logs/pack.log").read_text()).group(1) bucket, key = path.split("/", 1) import boto3 # Only the backup preparation helper needs this dependency. config = cse_config() - client = boto3.client("s3", endpoint_url=config("s3-endpoint"), aws_access_key_id=config("s3-key-id"), aws_secret_access_key=config("s3-secret-key")) + client = boto3.client("s3", + endpoint_url=config("s3-endpoint"), + aws_access_key_id=config("s3-key-id"), + aws_secret_access_key=config("s3-secret-key")) data = client.get_object(Bucket=bucket, Key=key)["Body"].read() keyspace = http(args.pd+"/pd/api/v2/keyspaces/"+args.keyspace) - manifest = {"snapshot_ts": ts, "keyspace_id": keyspace["id"], "backup_uri": "s3://"+path+"?endpoint="+config("s3-endpoint")+"®ion=local", "backup_digest": hashlib.sha256(data).hexdigest()} + manifest = {"snapshot_ts": ts, + "keyspace_id": keyspace["id"], + "backup_uri": "s3://"+path+"?endpoint="+config("s3-endpoint")+"®ion=local", + "backup_digest": hashlib.sha256(data).hexdigest()} write("manifest.json", manifest) - sql("USE "+args.database+"; UPDATE accounts SET balance=99999,note='updated-after-B' WHERE id=1; DELETE FROM accounts WHERE id=2; INSERT INTO accounts VALUES(3001,30010,'inserted-after-B'); ALTER TABLE accounts ADD COLUMN revision INT DEFAULT 0; INSERT INTO accounts VALUES(3002,30020,'after-DDL',1);") + sql("USE "+args.database+"; UPDATE accounts SET balance=99999,note='updated-after-B' W" + 'HERE id=1; DELETE FROM accounts WHERE id=2; INSERT INTO acco' + "unts VALUES(3001,30010,'inserted-after-B'); ALTER TABLE acco" + 'unts ADD COLUMN revision INT DEFAULT 0; INSERT INTO accounts' + " VALUES(3002,30020,'after-DDL',1);") # An SQL snapshot TSO taken after all fixture commits bounds the wait. target = int(sql("BEGIN; SELECT @@tidb_current_ts; COMMIT;").strip()) write("target.json", {"checkpoint_ts": target}) @@ -101,7 +143,15 @@ def get(name): env.update(DFS_S3_KEY_ID=config("s3-key-id"), DFS_S3_SECRET_KEY=config("s3-secret-key")) from urllib.parse import urlsplit commands = { - "cdc": [str(root/"bin/cdc"), "server", "--pd="+args.pd, "--addr=0.0.0.0:"+str(urlsplit(args.server).port), "--advertise-addr="+args.advertise_addr, "--cluster-id="+args.cluster_id, "--data-dir="+str(root/"cdc-data"), "--log-file="+str(root/"logs/cdc.log"), "--config="+str(root/"cdc.toml")], + "cdc": [str(root/"bin/cdc"), + "server", + "--pd="+args.pd, + "--addr=0.0.0.0:"+str(urlsplit(args.server).port), + "--advertise-addr="+args.advertise_addr, + "--cluster-id="+args.cluster_id, + "--data-dir="+str(root/"cdc-data"), + "--log-file="+str(root/"logs/cdc.log"), + "--config="+str(root/"cdc.toml")], } commands["cdc"].extend(["--snapshot-cse-binary="+args.cse_binary]) for name, command in commands.items(): @@ -142,7 +192,19 @@ def get(name): pidfile.unlink() elif args.action == "create": manifest = json.loads((root/"manifest.json").read_text()) - subprocess.run([str(root/"bin/cdc"), "cli", "changefeed", "create", "--server="+args.server, "--keyspace="+args.keyspace, "--changefeed-id="+args.name, "--sink-uri=kafka://"+args.broker+"/"+args.topic+"?protocol=open-protocol&partition-num=1&replication-factor=1&required-acks=-1", "--start-ts="+str(manifest["snapshot_ts"]), "--config="+str(root/"changefeed.toml"), "--no-confirm"], check=True) + subprocess.run([str(root/"bin/cdc"), + "cli", + "changefeed", + "create", + "--server="+args.server, + "--keyspace="+args.keyspace, + "--changefeed-id="+args.name, + "--sink-uri=kafka://"+args.broker+"/"+args.topic+"?protocol=open-protocol&partition-num=1" + "&replication-factor=1&required-acks=-1", + "--start-ts="+str(manifest["snapshot_ts"]), + "--config="+str(root/"changefeed.toml"), + "--no-confirm"], + check=True) elif args.action == "wait": target = json.loads((root/"target.json").read_text())["checkpoint_ts"] state = {} @@ -170,8 +232,24 @@ def get(name): raise SystemExit("changefeed did not catch up: "+str(state.get("error"))) elif args.action == "verify": output = root/(args.name+"-verification.json") - subprocess.run([str(root/"bin/snapshot-verify"), "-broker", args.broker, "-topic", args.topic, "-output", str(output), "-spec", http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace)["snapshot"]["spec_ref"]["uri"]], check=True) - subprocess.run(["python3", str(Path(__file__).with_name("compare.py")), str(output), "--port", args.sql_port, "--database", args.database], check=True) + subprocess.run([str(root/"bin/snapshot-verify"), + "-broker", + args.broker, + "-topic", + args.topic, + "-output", + str(output), + "-spec", + http(args.server+"/api/v2/changefeeds/"+args.name+"?keyspace="+args.keyspace)["snapshot"]["spec_ref"]["uri"]], + check=True) + subprocess.run(["python3", + str(Path(__file__).with_name("compare.py")), + str(output), + "--port", + args.sql_port, + "--database", + args.database], + check=True) if __name__ == "__main__": diff --git a/tests/integration_tests/native_snapshot/verify/main.go b/tests/integration_tests/native_snapshot/verify/main.go index 0892cb650a..f3217fcea0 100644 --- a/tests/integration_tests/native_snapshot/verify/main.go +++ b/tests/integration_tests/native_snapshot/verify/main.go @@ -187,7 +187,11 @@ func main() { log.Fatal("unexpected snapshot envelope") } recordID := fmt.Sprintf("%d/%d", tableID, id) - if id < 1 || id > int64(*seed) || number(cols["balance"].Value) != id*10 || cols["note"].Value != fmt.Sprintf("snapshot-%d", id) || len(cols) != 3 { + if id < 1 || + id > int64(*seed) || + number(cols["balance"].Value) != id*10 || + cols["note"].Value != fmt.Sprintf("snapshot-%d", id) || + len(cols) != 3 { log.Fatal("snapshot differs from frozen SQL fixture") } if old, ok := seen[recordID]; ok { @@ -223,7 +227,15 @@ func main() { if snapshotRows != *seed { log.Fatalf("snapshot rows %d != %d", snapshotRows, *seed) } - result := map[string]any{"snapshot_unique_rows": snapshotRows, "snapshot_duplicates": duplicates, "incremental_rows": incremental, "ddl_events": ddls, "snapshot_ts": boundary, "kafka_end_offset": end, "final_rows": rows} + result := map[string]any{ + "snapshot_unique_rows": snapshotRows, + "snapshot_duplicates": duplicates, + "incremental_rows": incremental, + "ddl_events": ddls, + "snapshot_ts": boundary, + "kafka_end_offset": end, + "final_rows": rows, + } f, err := os.Create(*out) if err != nil { log.Fatal(err) @@ -234,5 +246,13 @@ func main() { if err = enc.Encode(result); err != nil { log.Fatal(err) } - fmt.Printf("snapshot=%d duplicates=%d incremental=%d ddl=%d final=%d end_offset=%d\n", snapshotRows, duplicates, incremental, ddls, len(rows), end) + fmt.Printf( + "snapshot=%d duplicates=%d incremental=%d ddl=%d final=%d end_offset=%d\n", + snapshotRows, + duplicates, + incremental, + ddls, + len(rows), + end, + ) } From e5f91fbb5146c51895b7f456a2f50bd8c68ded7a Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 30 Nov 2026 19:41:54 +0800 Subject: [PATCH 14/17] snapshot: give each apply worker an independent producer --- maintainer/snapshot_test.go | 5 +- metrics/grafana/ticdc_new_arch.json | 390 +++++++++++++++++- .../ticdc_new_arch_next_gen.json | 390 +++++++++++++++++- .../ticdc_new_arch_with_keyspace_name.json | 390 +++++++++++++++++- pkg/metrics/snapshot.go | 33 +- pkg/sink/kafka/factory.go | 17 + pkg/sink/kafka/franz_factory.go | 27 +- pkg/sink/kafka/franz_factory_test.go | 47 +++ pkg/sink/kafka/franz_metrics_hook.go | 42 +- pkg/sink/kafka/franz_metrics_hook_test.go | 21 + pkg/sink/kafka/metrics.go | 1 + pkg/sink/kafka/options.go | 2 + pkg/sink/kafka/sarama_async_producer.go | 92 +++-- pkg/sink/kafka/sarama_factory.go | 4 + pkg/sink/kafka/snapshot_metrics.go | 129 ++++++ pkg/snapshot/bootstrap/controller.go | 225 +++++----- pkg/snapshot/bootstrap/controller_test.go | 73 +++- pkg/snapshot/kafka_output.go | 220 ++++++++++ pkg/snapshot/kafka_output_test.go | 67 +++ pkg/snapshot/output_mock_test.go | 76 ++++ pkg/snapshot/protocol/protocol_test.go | 13 +- pkg/snapshot/protocol/types.go | 16 +- pkg/snapshot/service.go | 33 +- pkg/snapshot/writer.go | 147 +++++-- pkg/snapshot/writer_test.go | 56 ++- scripts/generate-mock.sh | 1 + .../native_snapshot/README.md | 9 +- 27 files changed, 2287 insertions(+), 239 deletions(-) create mode 100644 pkg/sink/kafka/snapshot_metrics.go create mode 100644 pkg/snapshot/kafka_output.go create mode 100644 pkg/snapshot/kafka_output_test.go create mode 100644 pkg/snapshot/output_mock_test.go diff --git a/maintainer/snapshot_test.go b/maintainer/snapshot_test.go index e6a445fac7..eb218b6d76 100644 --- a/maintainer/snapshot_test.go +++ b/maintainer/snapshot_test.go @@ -9,7 +9,6 @@ import ( "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" - "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/stretchr/testify/require" "go.uber.org/atomic" @@ -23,8 +22,8 @@ func TestSnapshotMaintainerCanStopBeforeDispatcherBootstrap(t *testing.T) { cfg := config.GetDefaultReplicaConfig() cfg.Snapshot = &protocol.Config{} m := &Maintainer{removed: atomic.NewBool(false), ctx: ctx, cancel: cancel, changefeedID: common.NewChangeFeedIDWithName("snapshot-stop", common.DefaultKeyspaceName), info: &config.ChangeFeedInfo{Config: cfg}, snapshotRunning: true} - metrics.MaintainerGauge.WithLabelValues(m.changefeedID.Keyspace(), m.changefeedID.Name()).Inc() - defer metrics.MaintainerGauge.DeleteLabelValues(m.changefeedID.Keyspace(), m.changefeedID.Name()) + maintainerGauge.WithLabelValues(m.changefeedID.Keyspace(), m.changefeedID.Name()).Inc() + defer maintainerGauge.DeleteLabelValues(m.changefeedID.Keyspace(), m.changefeedID.Name()) m.onRemoveMaintainer(cascade, false) require.True(t, m.removed.Load()) require.True(t, m.removing.Load()) diff --git a/metrics/grafana/ticdc_new_arch.json b/metrics/grafana/ticdc_new_arch.json index 4c8bb3ff54..57adfe87a4 100644 --- a/metrics/grafana/ticdc_new_arch.json +++ b/metrics/grafana/ticdc_new_arch.json @@ -29725,7 +29725,7 @@ "dashLength": 10, "dashes": false, "datasource": "${DS_TEST-CLUSTER}", - "description": "Shared budget covers mounted rows awaiting sink ACKs. Input chunks and sink internal buffers are additional memory; this is not process RSS.", + "description": "Each apply worker owns its write budget. The configured total is apply-workers times write-memory-quota-per-worker. Chunk buffers and client overhead are additional; this is not process RSS.", "fieldConfig": { "defaults": { "links": [] @@ -30327,6 +30327,394 @@ "yaxis": { "align": false } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Worker throughput counts logical KV bytes only after downstream acknowledgment.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 64 + }, + "hiddenSeries": false, + "id": 62211, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum by (namespace,changefeed,worker)(rate(ticdc_snapshot_worker_acknowledged_bytes_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}[$__rate_interval]))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker KV throughput", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "Bps", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Private mounted-data budget usage for each apply worker; the default quota is 128 MiB.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 64 + }, + "hiddenSeries": false, + "id": 62212, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max by (namespace,changefeed,worker)(ticdc_snapshot_worker_inflight_bytes{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker write memory", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Independent Kafka client requests awaiting broker responses, summed across brokers.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 71 + }, + "hiddenSeries": false, + "id": 62213, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum by (namespace,changefeed,worker)(ticdc_snapshot_kafka_producer_in_flight_requests{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker Kafka requests in flight", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Mean broker request latency by worker. Sarama uses its client histogram; Franz uses completed request durations.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 71 + }, + "hiddenSeries": false, + "id": 62214, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "avg by (namespace,changefeed,worker)(ticdc_snapshot_kafka_producer_request_latency_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}) or (sum by (namespace,changefeed,worker)(rate(ticdc_snapshot_kafka_producer_request_duration_seconds_sum{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}[$__rate_interval])) / sum by (namespace,changefeed,worker)(rate(ticdc_snapshot_kafka_producer_request_duration_seconds_count{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", namespace=~\"$namespace\", changefeed=~\"$changefeed\"}[$__rate_interval])))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{namespace}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker Kafka request latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } } ], "title": "Snapshot", diff --git a/metrics/nextgengrafana/ticdc_new_arch_next_gen.json b/metrics/nextgengrafana/ticdc_new_arch_next_gen.json index 22c9b0e882..5fcea2b9f6 100644 --- a/metrics/nextgengrafana/ticdc_new_arch_next_gen.json +++ b/metrics/nextgengrafana/ticdc_new_arch_next_gen.json @@ -29725,7 +29725,7 @@ "dashLength": 10, "dashes": false, "datasource": "${DS_TEST-CLUSTER}", - "description": "Shared budget covers mounted rows awaiting sink ACKs. Input chunks and sink internal buffers are additional memory; this is not process RSS.", + "description": "Each apply worker owns its write budget. The configured total is apply-workers times write-memory-quota-per-worker. Chunk buffers and client overhead are additional; this is not process RSS.", "fieldConfig": { "defaults": { "links": [] @@ -30327,6 +30327,394 @@ "yaxis": { "align": false } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Worker throughput counts logical KV bytes only after downstream acknowledgment.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 64 + }, + "hiddenSeries": false, + "id": 62211, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum by (keyspace_name,changefeed,worker)(rate(ticdc_snapshot_worker_acknowledged_bytes_total{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval]))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker KV throughput", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "Bps", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Private mounted-data budget usage for each apply worker; the default quota is 128 MiB.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 64 + }, + "hiddenSeries": false, + "id": 62212, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max by (keyspace_name,changefeed,worker)(ticdc_snapshot_worker_inflight_bytes{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker write memory", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Independent Kafka client requests awaiting broker responses, summed across brokers.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 71 + }, + "hiddenSeries": false, + "id": 62213, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum by (keyspace_name,changefeed,worker)(ticdc_snapshot_kafka_producer_in_flight_requests{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker Kafka requests in flight", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Mean broker request latency by worker. Sarama uses its client histogram; Franz uses completed request durations.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 71 + }, + "hiddenSeries": false, + "id": 62214, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "avg by (keyspace_name,changefeed,worker)(ticdc_snapshot_kafka_producer_request_latency_seconds{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) or (sum by (keyspace_name,changefeed,worker)(rate(ticdc_snapshot_kafka_producer_request_duration_seconds_sum{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])) / sum by (keyspace_name,changefeed,worker)(rate(ticdc_snapshot_kafka_producer_request_duration_seconds_count{k8s_cluster=\"$k8s_cluster\", sharedpool_id=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker Kafka request latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } } ], "title": "Snapshot", diff --git a/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json b/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json index 2721241e2f..9ee582b9ae 100644 --- a/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json +++ b/metrics/nextgengrafana/ticdc_new_arch_with_keyspace_name.json @@ -13015,7 +13015,7 @@ "dashLength": 10, "dashes": false, "datasource": "${DS_TEST-CLUSTER}", - "description": "Shared budget covers mounted rows awaiting sink ACKs. Input chunks and sink internal buffers are additional memory; this is not process RSS.", + "description": "Each apply worker owns its write budget. The configured total is apply-workers times write-memory-quota-per-worker. Chunk buffers and client overhead are additional; this is not process RSS.", "fieldConfig": { "defaults": { "links": [] @@ -13617,6 +13617,394 @@ "yaxis": { "align": false } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Worker throughput counts logical KV bytes only after downstream acknowledgment.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 64 + }, + "hiddenSeries": false, + "id": 62211, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum by (keyspace_name,changefeed,worker)(rate(ticdc_snapshot_worker_acknowledged_bytes_total{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval]))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker KV throughput", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "Bps", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Private mounted-data budget usage for each apply worker; the default quota is 128 MiB.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 64 + }, + "hiddenSeries": false, + "id": 62212, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "max by (keyspace_name,changefeed,worker)(ticdc_snapshot_worker_inflight_bytes{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker write memory", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Independent Kafka client requests awaiting broker responses, summed across brokers.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 71 + }, + "hiddenSeries": false, + "id": 62213, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "sum by (keyspace_name,changefeed,worker)(ticdc_snapshot_kafka_producer_in_flight_requests{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker Kafka requests in flight", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_TEST-CLUSTER}", + "description": "Mean broker request latency by worker. Sarama uses its client histogram; Franz uses completed request durations.", + "fieldConfig": { + "defaults": { + "links": [] + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 71 + }, + "hiddenSeries": false, + "id": 62214, + "legend": { + "alignAsTable": true, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "options": { + "alertThreshold": true + }, + "paceLength": 10, + "percentage": false, + "pluginVersion": "7.5.17", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "exemplar": true, + "expr": "avg by (keyspace_name,changefeed,worker)(ticdc_snapshot_kafka_producer_request_latency_seconds{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}) or (sum by (keyspace_name,changefeed,worker)(rate(ticdc_snapshot_kafka_producer_request_duration_seconds_sum{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])) / sum by (keyspace_name,changefeed,worker)(rate(ticdc_snapshot_kafka_producer_request_duration_seconds_count{k8s_cluster=\"$k8s_cluster\", tidb_cluster=\"$tidb_cluster\", keyspace_name=~\"$keyspace_name\", changefeed=~\"$changefeed\"}[$__rate_interval])))", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "{{keyspace_name}}-{{changefeed}}-worker {{worker}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Snapshot worker Kafka request latency", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": false + } + ], + "yaxis": { + "align": false + } } ], "title": "Snapshot", diff --git a/pkg/metrics/snapshot.go b/pkg/metrics/snapshot.go index 39b979b349..ee683310b4 100644 --- a/pkg/metrics/snapshot.go +++ b/pkg/metrics/snapshot.go @@ -2,6 +2,7 @@ package metrics import ( + "strconv" "time" "github.com/prometheus/client_golang/prometheus" @@ -50,7 +51,7 @@ var ( Namespace: "ticdc", Subsystem: "snapshot", Name: "operation_duration_seconds", - Help: "CSE command, shared write-budget acquisition, and batch enqueue-to-ACK duration.", + Help: "CSE command, worker write-budget acquisition, and batch enqueue-to-ACK duration.", Buckets: prometheus.ExponentialBuckets(0.001, 4, 11), }, snapshotLabels) snapshotErrors = prometheus.NewCounterVec(prometheus.CounterOpts{ @@ -73,8 +74,36 @@ var ( }, []string{GetKeyspaceLabel(), "changefeed", "kind"}) ) +var snapshotWorkerInflight = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", Subsystem: "snapshot", Name: "worker_inflight_bytes", + Help: "Mounted data awaiting ACKs in each apply worker; excludes chunk and client overhead.", +}, []string{GetKeyspaceLabel(), "changefeed", "worker"}) + +var snapshotWorkerBytes = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", Subsystem: "snapshot", Name: "worker_acknowledged_bytes_total", + Help: "Logical KV bytes acknowledged by each apply worker, including replayed writes.", +}, []string{GetKeyspaceLabel(), "changefeed", "worker"}) + +func (s *SnapshotStatistics) ResetWorker(worker int) { + if s != nil { + snapshotWorkerInflight.WithLabelValues(s.keyspace, s.changefeed, strconv.Itoa(worker)).Set(0) + } +} + +func (s *SnapshotStatistics) WorkerInflight(worker int, delta float64) { + if s != nil { + snapshotWorkerInflight.WithLabelValues(s.keyspace, s.changefeed, strconv.Itoa(worker)).Add(delta) + } +} + +func (s *SnapshotStatistics) WorkerOutput(worker int, bytes uint64) { + if s != nil { + snapshotWorkerBytes.WithLabelValues(s.keyspace, s.changefeed, strconv.Itoa(worker)).Add(float64(bytes)) + } +} + func initSnapshotMetrics(r *prometheus.Registry) { - r.MustRegister( + r.MustRegister(snapshotWorkerInflight, snapshotWorkerBytes, snapshotBytes, snapshotRows, snapshotStarted, diff --git a/pkg/sink/kafka/factory.go b/pkg/sink/kafka/factory.go index 00e7a4274c..ae05978e64 100644 --- a/pkg/sink/kafka/factory.go +++ b/pkg/sink/kafka/factory.go @@ -30,6 +30,23 @@ func NewFactory(ctx context.Context, o *options, changefeedID common.ChangeFeedI return newFranzFactory(ctx, o, changefeedID, stats) } +// NewSnapshotFactory creates an independent factory/client with worker-scoped +// metrics. It never aliases the normal sink's client or metric lifecycle. +func NewSnapshotFactory(ctx context.Context, o *options, id common.ChangeFeedID, worker string) (Factory, error) { + copyOptions := *o + copyOptions.snapshotWorker = worker + return NewFactory(ctx, ©Options, id, nil) +} + +// CloseSnapshotProducer joins asynchronous client shutdown before the snapshot +// can commit. Normal sinks retain their nonblocking Close behavior. +func CloseSnapshotProducer(producer AsyncProducer) { + producer.Close() + if p, ok := producer.(*saramaAsyncProducer); ok && p.closeDone != nil { + <-p.closeDone + } +} + // Factory creates Kafka components for one changefeed. type Factory interface { // Close releases factory-owned resources after all components are closed. diff --git a/pkg/sink/kafka/franz_factory.go b/pkg/sink/kafka/franz_factory.go index 9a63add20c..d9630c212c 100644 --- a/pkg/sink/kafka/franz_factory.go +++ b/pkg/sink/kafka/franz_factory.go @@ -30,10 +30,11 @@ import ( ) type franzFactory struct { - changefeedID common.ChangeFeedID - statistics *statistics.Statistics - client *kgo.Client - closed atomic.Bool + changefeedID common.ChangeFeedID + statistics *statistics.Statistics + client *kgo.Client + closed atomic.Bool + snapshotWorker string } func newFranzFactory(ctx context.Context, o *options, changefeedID common.ChangeFeedID, stats *statistics.Statistics) (Factory, error) { @@ -56,7 +57,12 @@ func newFranzFactory(ctx context.Context, o *options, changefeedID common.Change return nil, err } producerOpts := producerOptions(o) - metricsHook := newMetricsHook(changefeedID) + var metricsHook *metricsHook + if o.snapshotWorker != "" { + metricsHook = newSnapshotMetricsHook(changefeedID, o.snapshotWorker) + } else { + metricsHook = newMetricsHook(changefeedID) + } opts := make([]kgo.Opt, 0, len(clientOpts)+len(producerOpts)+3) opts = append(opts, clientOpts...) opts = append(opts, @@ -67,7 +73,7 @@ func newFranzFactory(ctx context.Context, o *options, changefeedID common.Change client, err := kgo.NewClient(opts...) if err != nil { - cleanupMetrics(changefeedID) + cleanupFactoryMetrics(changefeedID, o.snapshotWorker) return nil, errors.WrapError(errors.ErrNewKafkaSink, err) } @@ -88,9 +94,10 @@ func newFranzFactory(ctx context.Context, o *options, changefeedID common.Change zap.Duration("readTimeout", o.ReadTimeout), zap.Duration("writeTimeout", o.WriteTimeout)) return &franzFactory{ - changefeedID: changefeedID, - statistics: stats, - client: client, + changefeedID: changefeedID, + snapshotWorker: o.snapshotWorker, + statistics: stats, + client: client, }, nil } @@ -124,7 +131,7 @@ func (f *franzFactory) Close() { if f.client != nil { f.client.Close() } - cleanupMetrics(f.changefeedID) + cleanupFactoryMetrics(f.changefeedID, f.snapshotWorker) } func (f *franzFactory) MetricsCollector(AdminClient) MetricsCollector { diff --git a/pkg/sink/kafka/franz_factory_test.go b/pkg/sink/kafka/franz_factory_test.go index 3205516a56..8326821ae1 100644 --- a/pkg/sink/kafka/franz_factory_test.go +++ b/pkg/sink/kafka/franz_factory_test.go @@ -76,3 +76,50 @@ func TestSharedClientLifecycle(t *testing.T) { require.ErrorIs(t, asyncProducer.client.Context().Err(), context.Canceled) factory.Close() } + +// The snapshot API must isolate real clients, not just producer wrappers. +func TestSnapshotFactoriesOwnClientsAndMetrics(t *testing.T) { + for _, client := range []string{KafkaClientSarama, KafkaClientFranz} { + t.Run(client, func(t *testing.T) { + const topic = "snapshot-clients" + cluster := kfake.MustCluster(kfake.NumBrokers(1), kfake.SeedTopics(1, topic)) + defer cluster.Close() + o := testOptions(cluster.ListenAddrs()) + o.Client = client + o.Topic = topic + id := common.NewChangefeedID4Test(common.DefaultKeyspaceName, "snapshot-"+client) + first, err := NewSnapshotFactory(t.Context(), o, id, "0") + require.NoError(t, err) + defer first.Close() + second, err := NewSnapshotFactory(t.Context(), o, id, "1") + require.NoError(t, err) + defer second.Close() + p1, err := first.AsyncProducer(t.Context()) + require.NoError(t, err) + defer CloseSnapshotProducer(p1) + p2, err := second.AsyncProducer(t.Context()) + require.NoError(t, err) + defer CloseSnapshotProducer(p2) + if client == KafkaClientFranz { + require.NotSame(t, p1.(*asyncProducer).client, p2.(*asyncProducer).client) + } else { + require.NotSame(t, p1.(*saramaAsyncProducer).client, p2.(*saramaAsyncProducer).client) + require.NotSame(t, first.(*saramaFactory).metricRegistry, second.(*saramaFactory).metricRegistry) + } + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { done <- p2.AsyncRunCallback(ctx) }() + CloseSnapshotProducer(p1) + first.Close() + ack := make(chan struct{}) + require.NoError(t, p2.AsyncSend(ctx, topic, 0, &codecCommon.Message{Value: []byte("still alive"), Callback: func() { close(ack) }})) + select { + case <-ack: + case <-time.After(5 * time.Second): + t.Fatal("closing another worker stopped this producer") + } + cancel() + <-done + }) + } +} diff --git a/pkg/sink/kafka/franz_metrics_hook.go b/pkg/sink/kafka/franz_metrics_hook.go index 67cf72a48e..eaaa32982c 100644 --- a/pkg/sink/kafka/franz_metrics_hook.go +++ b/pkg/sink/kafka/franz_metrics_hook.go @@ -31,6 +31,7 @@ import ( type metricsHook struct { keyspace string changefeed string + worker string brokers sync.Map @@ -57,6 +58,22 @@ func newMetricsHook(changefeedID common.ChangeFeedID) *metricsHook { } } +func newSnapshotMetricsHook(id common.ChangeFeedID, worker string) *metricsHook { + return &metricsHook{ + keyspace: id.Keyspace(), changefeed: id.Name(), worker: worker, + recordsPerBatch: snapshotRecordsPerBatch.WithLabelValues(id.Keyspace(), id.Name(), worker), + compressionRatio: snapshotCompressionRatio.WithLabelValues(id.Keyspace(), id.Name(), worker), + } +} + +func cleanupFactoryMetrics(id common.ChangeFeedID, worker string) { + if worker == "" { + cleanupMetrics(id) + return + } + cleanSnapshotProducerMetrics(id, worker) +} + func (h *metricsHook) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) { if meta.NodeID < 0 { return @@ -73,12 +90,25 @@ func (h *metricsHook) broker(nodeID int32) *brokerMetrics { } brokerID := strconv.Itoa(int(nodeID)) - metrics := &brokerMetrics{ - outgoingBytesTotal: outgoingBytesTotal.WithLabelValues(h.keyspace, h.changefeed, brokerID), - requestsTotal: requestsTotal.WithLabelValues(h.keyspace, h.changefeed, brokerID), - requestsInFlight: requestsInFlightGauge.WithLabelValues(h.keyspace, h.changefeed, brokerID), - requestDuration: requestDuration.WithLabelValues(h.keyspace, h.changefeed, brokerID), - throttleTime: throttleTime.WithLabelValues(h.keyspace, h.changefeed, brokerID), + var metrics *brokerMetrics + if h.worker == "" { + metrics = &brokerMetrics{ + outgoingBytesTotal: outgoingBytesTotal.WithLabelValues(h.keyspace, h.changefeed, brokerID), + requestsTotal: requestsTotal.WithLabelValues(h.keyspace, h.changefeed, brokerID), + requestsInFlight: requestsInFlightGauge.WithLabelValues(h.keyspace, h.changefeed, brokerID), + requestDuration: requestDuration.WithLabelValues(h.keyspace, h.changefeed, brokerID), + throttleTime: throttleTime.WithLabelValues(h.keyspace, h.changefeed, brokerID), + } + } + if h.worker != "" { + labels := []string{h.keyspace, h.changefeed, h.worker, brokerID} + metrics = &brokerMetrics{ + outgoingBytesTotal: snapshotOutgoingBytes.WithLabelValues(labels...), + requestsTotal: snapshotRequests.WithLabelValues(labels...), + requestsInFlight: snapshotRequestsInFlight.WithLabelValues(labels...), + requestDuration: snapshotRequestDuration.WithLabelValues(labels...), + throttleTime: snapshotThrottleTime.WithLabelValues(labels...), + } } actual, _ := h.brokers.LoadOrStore(nodeID, metrics) diff --git a/pkg/sink/kafka/franz_metrics_hook_test.go b/pkg/sink/kafka/franz_metrics_hook_test.go index 685318b27e..c65568a003 100644 --- a/pkg/sink/kafka/franz_metrics_hook_test.go +++ b/pkg/sink/kafka/franz_metrics_hook_test.go @@ -120,3 +120,24 @@ func TestMetricsHook(t *testing.T) { require.False(t, recordsPerBatch.DeleteLabelValues(keyspace, changefeed)) require.False(t, compressionRatio.DeleteLabelValues(keyspace, changefeed)) } + +func TestSnapshotMetricCleanupIsScopedToWorker(t *testing.T) { + id := common.NewChangefeedID4Test(common.DefaultKeyspaceName, "snapshot-hook") + normal := newMetricsHook(id) + first, second := newSnapshotMetricsHook(id, "0"), newSnapshotMetricsHook(id, "1") + t.Cleanup(func() { + cleanupMetrics(id) + cleanSnapshotProducerMetrics(id, "0") + cleanSnapshotProducerMetrics(id, "1") + }) + meta := kgo.BrokerMetadata{NodeID: 1} + for _, hook := range []*metricsHook{normal, first, second} { + hook.OnBrokerWrite(meta, 0, 12, 0, 0, nil) + } + cleanSnapshotProducerMetrics(id, "0") + require.False(t, snapshotRequestsInFlight.DeleteLabelValues(id.Keyspace(), id.Name(), "0", "1")) + require.Equal(t, float64(1), testutil.ToFloat64(second.broker(1).requestsInFlight)) + require.Equal(t, float64(1), testutil.ToFloat64(normal.broker(1).requestsInFlight)) + require.True(t, snapshotRequestsInFlight.DeleteLabelValues(id.Keyspace(), id.Name(), "1", "1")) + require.True(t, requestsInFlightGauge.DeleteLabelValues(id.Keyspace(), id.Name(), "1")) +} diff --git a/pkg/sink/kafka/metrics.go b/pkg/sink/kafka/metrics.go index 5c217d0316..be3666bfbe 100644 --- a/pkg/sink/kafka/metrics.go +++ b/pkg/sink/kafka/metrics.go @@ -88,6 +88,7 @@ var ( // RegisterMetrics registers all metrics owned by this package. func RegisterMetrics(registry *prometheus.Registry) { + registerSnapshotProducerMetrics(registry) registry.MustRegister( outgoingBytesTotal, requestsTotal, diff --git a/pkg/sink/kafka/options.go b/pkg/sink/kafka/options.go index b124b8ec5e..bbd05e3c75 100644 --- a/pkg/sink/kafka/options.go +++ b/pkg/sink/kafka/options.go @@ -159,6 +159,8 @@ type urlConfig struct { // options stores Kafka sink configurations type options struct { + // snapshotWorker scopes metrics for an independently owned snapshot client. + snapshotWorker string Client string Topic string BrokerEndpoints []string diff --git a/pkg/sink/kafka/sarama_async_producer.go b/pkg/sink/kafka/sarama_async_producer.go index 5a6315bd10..a3310aa26c 100644 --- a/pkg/sink/kafka/sarama_async_producer.go +++ b/pkg/sink/kafka/sarama_async_producer.go @@ -15,6 +15,7 @@ package kafka import ( "context" + "sync" "time" "github.com/IBM/sarama" @@ -33,7 +34,9 @@ type saramaAsyncProducer struct { changefeedID common.ChangeFeedID statistics *statistics.Statistics - closed *atomic.Bool + closed *atomic.Bool + closeDone chan struct{} + closeOnce sync.Once } type messageMetadata struct { @@ -42,49 +45,54 @@ type messageMetadata struct { } func (p *saramaAsyncProducer) Close() { - p.closed.Store(true) - go func() { - // We need to close it asynchronously. Otherwise, we might get stuck - // with an unhealthy(i.e. Network jitter, isolation) state of Kafka. - // Safety: - // * If the kafka cluster is running well, it will be closed as soon as possible. - // Also, we cancel all table pipelines before closed, so it's safe. - // * If there is a problem with the kafka cluster, it will shut down the client first, - // which means no more data will be sent because the connection to the broker is dropped. - // Also, we cancel all table pipelines before closed, so it's safe. - // * For Kafka Sink, duplicate data is acceptable. - // * There is a risk of goroutine leakage, but it is acceptable and our main - // goal is not to get stuck with the processor tick. + p.closeOnce.Do(func() { + p.closed.Store(true) + go func() { + if p.closeDone != nil { + defer close(p.closeDone) + } + // We need to close it asynchronously. Otherwise, we might get stuck + // with an unhealthy(i.e. Network jitter, isolation) state of Kafka. + // Safety: + // * If the kafka cluster is running well, it will be closed as soon as possible. + // Also, we cancel all table pipelines before closed, so it's safe. + // * If there is a problem with the kafka cluster, it will shut down the client first, + // which means no more data will be sent because the connection to the broker is dropped. + // Also, we cancel all table pipelines before closed, so it's safe. + // * For Kafka Sink, duplicate data is acceptable. + // * There is a risk of goroutine leakage, but it is acceptable and our main + // goal is not to get stuck with the processor tick. - // `client` is mainly used by `asyncProducer` to fetch metadata and perform other related - // operations. When we close the `kafkaSaramaProducer`, - // there is no need for TiCDC to make sure that all buffered messages are flushed. - // Consider the situation where the broker is irresponsive. If the client were not - // closed, `asyncProducer.Close()` would waste a mount of time to try flush all messages. - // To prevent the scenario mentioned above, close the client first. - start := time.Now() - if err := p.client.Close(); err != nil { - log.Warn("kafka async producer client close failed", - zap.String("keyspace", p.changefeedID.Keyspace()), - zap.String("changefeed", p.changefeedID.Name()), - zap.Duration("duration", time.Since(start)), - zap.Error(err)) - } + // `client` is mainly used by `asyncProducer` to fetch metadata and perform other related + // operations. When we close the `kafkaSaramaProducer`, + // there is no need for TiCDC to make sure that all buffered messages are flushed. + // Consider the situation where the broker is irresponsive. If the client were not + // closed, `asyncProducer.Close()` would waste a mount of time to try flush all messages. + // To prevent the scenario mentioned above, close the client first. + start := time.Now() + if err := p.client.Close(); err != nil { + log.Warn("kafka async producer client close failed", + zap.String("keyspace", p.changefeedID.Keyspace()), + zap.String("changefeed", p.changefeedID.Name()), + zap.Duration("duration", time.Since(start)), + zap.Error(err)) + } - start = time.Now() - if err := p.producer.Close(); err != nil { - log.Warn("kafka async producer close failed", - zap.String("keyspace", p.changefeedID.Keyspace()), - zap.String("changefeed", p.changefeedID.Name()), - zap.Duration("duration", time.Since(start)), - zap.Error(err)) - } else { - log.Info("kafka async producer closed", - zap.String("keyspace", p.changefeedID.Keyspace()), - zap.String("changefeed", p.changefeedID.Name()), - zap.Duration("duration", time.Since(start))) - } - }() + start = time.Now() + if err := p.producer.Close(); err != nil { + log.Warn("kafka async producer close failed", + zap.String("keyspace", p.changefeedID.Keyspace()), + zap.String("changefeed", p.changefeedID.Name()), + zap.Duration("duration", time.Since(start)), + zap.Error(err)) + } else { + log.Info("kafka async producer closed", + zap.String("keyspace", p.changefeedID.Keyspace()), + zap.String("changefeed", p.changefeedID.Name()), + zap.Duration("duration", time.Since(start))) + } + }() + }) } func (p *saramaAsyncProducer) AsyncRunCallback( diff --git a/pkg/sink/kafka/sarama_factory.go b/pkg/sink/kafka/sarama_factory.go index 8d5a8c3f6d..cab5f6666c 100644 --- a/pkg/sink/kafka/sarama_factory.go +++ b/pkg/sink/kafka/sarama_factory.go @@ -179,12 +179,16 @@ func (f *saramaFactory) AsyncProducer(ctx context.Context) (AsyncProducer, error client: client, statistics: f.statistics, producer: p, + closeDone: make(chan struct{}), changefeedID: f.changefeedID, closed: atomic.NewBool(false), }, nil } func (f *saramaFactory) MetricsCollector(adminClient AdminClient) MetricsCollector { + if f.option.snapshotWorker != "" { + return &snapshotSaramaCollector{factory: f, admin: adminClient} + } return &saramaMetricsCollector{ changefeedID: f.changefeedID, adminClient: adminClient, diff --git a/pkg/sink/kafka/snapshot_metrics.go b/pkg/sink/kafka/snapshot_metrics.go new file mode 100644 index 0000000000..0bf1d967d2 --- /dev/null +++ b/pkg/sink/kafka/snapshot_metrics.go @@ -0,0 +1,129 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package kafka + +import ( + "context" + "strconv" + "time" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/metrics" + "github.com/prometheus/client_golang/prometheus" + gometrics "github.com/rcrowley/go-metrics" +) + +var snapshotProducerLabels = []string{metrics.GetKeyspaceLabel(), "changefeed", "worker", "broker"} +var ( + snapshotOutgoingBytes = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_outgoing_bytes_total", + Help: "Franz worker client bytes written to Kafka.", + }, snapshotProducerLabels) + snapshotRequests = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_requests_total", + Help: "Franz worker client request writes.", + }, snapshotProducerLabels) + snapshotRequestsInFlight = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_in_flight_requests", + Help: "Requests awaiting Kafka responses for each worker.", + }, snapshotProducerLabels) + snapshotRequestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_request_duration_seconds", + Help: "Franz worker client successful request duration.", + }, snapshotProducerLabels) + snapshotThrottleTime = prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_throttle_time_seconds", + Help: "Franz worker client broker throttling duration.", + }, snapshotProducerLabels) + snapshotRecordsPerBatch = prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_records_per_batch", + Help: "Franz worker client records in successful batches.", + }, snapshotProducerLabels[:3]) + snapshotCompressionRatio = prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_batch_compression_ratio", + Help: "Franz worker client batch compression ratio times 100.", + }, snapshotProducerLabels[:3]) + snapshotOutgoingRate = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_outgoing_byte_rate", + Help: "Sarama worker client outgoing byte rate.", + }, snapshotProducerLabels) + snapshotRequestRate = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_request_rate", + Help: "Sarama worker client request rate.", + }, snapshotProducerLabels) + snapshotRequestLatency = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "ticdc", Subsystem: "snapshot", + Name: "kafka_producer_request_latency_seconds", + Help: "Sarama worker client mean request latency.", + }, snapshotProducerLabels) +) + +func registerSnapshotProducerMetrics(r *prometheus.Registry) { + r.MustRegister( + snapshotOutgoingBytes, snapshotRequests, snapshotRequestsInFlight, + snapshotRequestDuration, snapshotThrottleTime, snapshotRecordsPerBatch, + snapshotCompressionRatio, snapshotOutgoingRate, snapshotRequestRate, snapshotRequestLatency, + ) +} + +func cleanSnapshotProducerMetrics(id common.ChangeFeedID, worker string) { + labels := prometheus.Labels{metrics.GetKeyspaceLabel(): id.Keyspace(), "changefeed": id.Name(), "worker": worker} + snapshotOutgoingBytes.DeletePartialMatch(labels) + snapshotRequests.DeletePartialMatch(labels) + snapshotRequestsInFlight.DeletePartialMatch(labels) + snapshotRequestDuration.DeletePartialMatch(labels) + snapshotThrottleTime.DeletePartialMatch(labels) + snapshotRecordsPerBatch.DeletePartialMatch(labels) + snapshotCompressionRatio.DeletePartialMatch(labels) + snapshotOutgoingRate.DeletePartialMatch(labels) + snapshotRequestRate.DeletePartialMatch(labels) + snapshotRequestLatency.DeletePartialMatch(labels) +} + +// Snapshot producers never write or delete another worker's metric series. +type snapshotSaramaCollector struct { + factory *saramaFactory + admin AdminClient +} + +func (m *snapshotSaramaCollector) Run(ctx context.Context) { + defer cleanSnapshotProducerMetrics(m.factory.changefeedID, m.factory.option.snapshotWorker) + brokers := m.admin.GetAllBrokers(ctx) + ticker := time.NewTicker(refreshMetricsInterval) + defer ticker.Stop() + for { + for _, broker := range brokers { + m.collect(strconv.Itoa(int(broker.ID))) + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +func (m *snapshotSaramaCollector) collect(broker string) { + f := m.factory + labels := []string{f.changefeedID.Keyspace(), f.changefeedID.Name(), f.option.snapshotWorker, broker} + if v, ok := f.metricRegistry.Get(getBrokerMetricName(outgoingByteRateMetricNamePrefix, broker)).(gometrics.Meter); ok { + snapshotOutgoingRate.WithLabelValues(labels...).Set(v.Snapshot().Rate1()) + } + if v, ok := f.metricRegistry.Get(getBrokerMetricName(requestRateMetricNamePrefix, broker)).(gometrics.Meter); ok { + snapshotRequestRate.WithLabelValues(labels...).Set(v.Snapshot().Rate1()) + } + if v, ok := f.metricRegistry.Get(getBrokerMetricName(requestLatencyInMsMetricNamePrefix, broker)).(gometrics.Histogram); ok { + snapshotRequestLatency.WithLabelValues(labels...).Set(v.Snapshot().Mean() / 1000) + } + if v, ok := f.metricRegistry.Get(getBrokerMetricName(requestsInFlightMetricNamePrefix, broker)).(gometrics.Counter); ok { + snapshotRequestsInFlight.WithLabelValues(labels...).Set(float64(v.Snapshot().Count())) + } +} diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go index e23d4ca326..4354932d3f 100644 --- a/pkg/snapshot/bootstrap/controller.go +++ b/pkg/snapshot/bootstrap/controller.go @@ -16,7 +16,6 @@ import ( "github.com/pingcap/ticdc/pkg/snapshot/exporter" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" - "golang.org/x/sync/errgroup" ) type Controller struct { @@ -184,79 +183,50 @@ func (c Controller) Run(ctx context.Context) (result error) { return err } } - complete := false - for { - all, err := tasks.List() - if err != nil { - return err - } - applied := 0 - var ready []store.Task - for _, task := range all { - if task.State == "APPLIED" { - applied++ - } else if task.State == "READY" { - ready = append(ready, task) - } - } - c.Statistics.Set("ready_ranges", float64(len(ready))) - c.Statistics.Set("committed_ranges", float64(applied)) - if err = c.applyReady(ctx, tasks, spec, state.PlanRef, ready); err != nil { - return err - } - applied += len(ready) - state.Applied = applied - c.Statistics.Set("committed_ranges", float64(applied)) - if err = save(); err != nil { - return err - } - if complete && applied == len(plan.Ranges) { - break - } + err = c.applyRanges(ctx, tasks, spec, state.PlanRef, func() (bool, error) { page, err := local.List(spec.JobID, state.Cursor, 64) if err != nil { - return err + return false, err } for _, ref := range page.Exports { var ex protocol.Export if err = protocol.Read(ref, &ex); err != nil { - return err + return false, err } found := false for _, r := range plan.Ranges { if r.RangeID == ex.Range.RangeID { found = true if err = protocol.ValidateExport(spec, state.PlanRef, r, ex); err != nil { - return err + return false, err } break } } if !found { - return protocol.Invalid("exporter returned unknown range") + return false, protocol.Invalid("exporter returned unknown range") } if err = tasks.Ready(ex.Range.RangeID, ref); err != nil { - return err + return false, err } } // Task pages are durable before advancing the runtime cursor. state.Cursor = page.Cursor - complete = page.Complete if err = save(); err != nil { - return err + return false, err } - if len(page.Exports) == 0 { - if job, err = local.Status(spec.JobID); err != nil { - return err - } - if job.Phase == "FAILED" || job.Phase == "CANCELED" { - return protocol.Invalid("source job failed: %s", job.Error) - } - if err = wait(); err != nil { - return err - } + if job, err = local.Status(spec.JobID); err != nil { + return false, err } + if job.Phase == "FAILED" || job.Phase == "CANCELED" { + return false, protocol.Invalid("source job failed: %s", job.Error) + } + return page.Complete, nil + }, func(applied int) error { state.Applied = applied; return save() }) + if err != nil { + return err } + state.Phase = "DRAINING" if err = save(); err != nil { return err @@ -278,78 +248,115 @@ func (c Controller) Run(ctx context.Context) (result error) { return save() } -// All workers are joined before Run can abort the sink or release writer.lock. -// Task page writes stay serialized; data application is bounded and concurrent. -func (c Controller) applyReady( - ctx context.Context, - tasks store.Tasks, - spec protocol.Spec, - ref protocol.ObjectRef, - ready []store.Task, +// applyRanges continuously feeds a fixed pool as exports arrive. Only this +// goroutine mutates task pages; receiving completions never waits for a full wave. +// All workers are joined before Run can abort outputs or release writer.lock. +func (c Controller) applyRanges(ctx context.Context, tasks store.Tasks, spec protocol.Spec, + ref protocol.ObjectRef, poll func() (bool, error), progress func(int) error, ) error { - if len(ready) == 0 { - return nil + ctx, cancel := context.WithCancel(ctx) + var workers sync.WaitGroup + defer func() { cancel(); workers.Wait() }() + type receipt struct { + task store.Task + export protocol.Export + rows uint64 + err error } - group, ctx := errgroup.WithContext(ctx) - jobs := make(chan store.Task) - var taskMu sync.Mutex - group.Go(func() error { - defer close(jobs) - for _, task := range ready { - select { - case jobs <- task: - case <-ctx.Done(): - return protocol.Wrap(ctx.Err()) + jobs := make(chan store.Task, c.Config.ApplyConcurrency()) + results := make(chan receipt, c.Config.ApplyConcurrency()) + for i := 0; i < c.Config.ApplyConcurrency(); i++ { + workers.Add(1) + go func() { + defer workers.Done() + for { + select { + case <-ctx.Done(): + return + case task := <-jobs: + result := receipt{task: task} + if result.err = protocol.Read(task.Export, &result.export); result.err == nil { + result.err = protocol.ValidateExport(spec, ref, task.Range, result.export) + } + if result.err == nil { + result.rows, result.err = c.Capture.ApplySnapshot(ctx, c.ID, c.Epoch, spec, ref, result.export) + } + select { + case results <- result: + case <-ctx.Done(): + return + } + if result.err != nil { + return + } + } } + }() + } + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + complete, err := poll() + if err != nil { + return err + } + active := 0 + for { + all, err := tasks.List() + if err != nil { + return err } - return nil - }) - for i := 0; i < min(c.Config.ApplyConcurrency(), len(ready)); i++ { - group.Go(func() error { - for task := range jobs { - if err := ctx.Err(); err != nil { - return protocol.Wrap(err) - } - taskMu.Lock() - assigned, err := tasks.Assign(task.Range.RangeID) - taskMu.Unlock() - if err != nil { - return err - } - var ex protocol.Export - if err = protocol.Read(assigned.Export, &ex); err != nil { - return err - } - if err = protocol.ValidateExport(spec, ref, task.Range, ex); err != nil { - return err - } - rows, err := c.Capture.ApplySnapshot(ctx, c.ID, c.Epoch, spec, ref, ex) - if err != nil { - return err - } - if err = ctx.Err(); err != nil { - return protocol.Wrap(err) - } - taskMu.Lock() - err = tasks.Commit(task.Range.RangeID, assigned.Lease, rows) - if err == nil { - c.Statistics.Add("committed_ranges", 1) - c.Statistics.Add("ready_ranges", -1) - } - taskMu.Unlock() - if err != nil { - return err - } - { - if err = removeExportChunks(c.artifactDir(), spec.JobID, ex); err != nil { + applied, ready := 0, 0 + for _, task := range all { + switch task.State { + case "APPLIED": + applied++ + case "READY": + ready++ + if active < c.Config.ApplyConcurrency() { + assigned, err := tasks.Assign(task.Range.RangeID) + if err != nil { return err } + jobs <- assigned // Capacity is at least the number of outstanding assignments. + active++ + ready-- } } + } + c.Statistics.Set("ready_ranges", float64(ready)) + c.Statistics.Set("committed_ranges", float64(applied)) + if err = progress(applied); err != nil { + return err + } + if complete && applied == len(all) && active == 0 { return nil - }) + } + select { + case <-ctx.Done(): + return protocol.Wrap(ctx.Err()) + case result := <-results: + active-- + if result.err != nil { + return result.err + } + if err = ctx.Err(); err != nil { + return protocol.Wrap(err) + } + if err = tasks.Commit(result.task.Range.RangeID, result.task.Lease, result.rows); err != nil { + return err + } + if err = removeExportChunks(c.artifactDir(), spec.JobID, result.export); err != nil { + return err + } + case <-ticker.C: + if !complete { + complete, err = poll() + if err != nil { + return err + } + } + } } - return group.Wait() } func (c Controller) artifactDir() string { return c.ArtifactDir } diff --git a/pkg/snapshot/bootstrap/controller_test.go b/pkg/snapshot/bootstrap/controller_test.go index f5a8bd2b50..2c08b8b065 100644 --- a/pkg/snapshot/bootstrap/controller_test.go +++ b/pkg/snapshot/bootstrap/controller_test.go @@ -38,8 +38,6 @@ func TestApplyReadyBoundedReceiptsAndCancellation(t *testing.T) { require.NoError(t, err) require.NoError(t, tasks.Ready(r.RangeID, export)) } - ready, err := tasks.List() - require.NoError(t, err) capture := NewMockCapture(gomock.NewController(t)) started := make(chan struct{}, 6) release := make(chan struct{}) @@ -70,7 +68,9 @@ func TestApplyReadyBoundedReceiptsAndCancellation(t *testing.T) { }).AnyTimes() c := Controller{Epoch: 1, Config: &protocol.Config{ApplyWorkers: 2}, Capture: capture} done := make(chan error, 1) - go func() { done <- c.applyReady(ctx, tasks, spec, ref, ready) }() + go func() { + done <- c.applyRanges(ctx, tasks, spec, ref, func() (bool, error) { return true, nil }, func(int) error { return nil }) + }() for i := 0; i < 2; i++ { select { case <-started: @@ -160,3 +160,70 @@ plan={k:s[k] for k in ('protocol_version','job_id','snapshot_id','snapshot_ts')} } require.NoError(t, c.Run(ctx)) } + +func TestApplyRangesDiscoversWorkWhileAnotherRangeWaitsForAck(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + objects := store.Local{Root: t.TempDir()} + spec := protocol.Spec{ProtocolVersion: 1, JobID: "pipeline", SnapshotID: "s", SnapshotTS: 42} + plan := protocol.Plan{ProtocolVersion: 1, JobID: spec.JobID, SnapshotID: "s", SnapshotTS: 42} + for i := 0; i < 3; i++ { + plan.Ranges = append(plan.Ranges, protocol.Span{RangeID: fmt.Sprint(i), TableID: int64(i + 1), Start: []byte("a"), End: []byte("z")}) + } + ref, err := objects.Put("plan", plan) + require.NoError(t, err) + tasks := store.Tasks{Objects: objects, Job: spec.JobID, Digest: ref.Digest, Epoch: 1, Plan: plan} + require.NoError(t, tasks.Init()) + exports := make([]protocol.ObjectRef, 3) + for i, span := range plan.Ranges { + exports[i], err = objects.Put("export-"+span.RangeID, protocol.Export{ProtocolVersion: 1, JobID: spec.JobID, SnapshotID: "s", SnapshotTS: 42, PlanDigest: ref.Digest, Range: span, AttemptID: "a"}) + require.NoError(t, err) + if i < 2 { + require.NoError(t, tasks.Ready(span.RangeID, exports[i])) + } + } + releaseSlow := make(chan struct{}) + fastDone, lateStarted := make(chan struct{}), make(chan struct{}) + capture := NewMockCapture(gomock.NewController(t)) + capture.EXPECT().ApplySnapshot(gomock.Any(), gomock.Any(), uint64(1), spec, ref, gomock.Any()).DoAndReturn(func(ctx context.Context, _ common.ChangeFeedID, _ uint64, _ protocol.Spec, _ protocol.ObjectRef, ex protocol.Export) (uint64, error) { + switch ex.Range.RangeID { + case "0": + select { + case <-releaseSlow: + case <-ctx.Done(): + return 0, ctx.Err() + } + case "1": + close(fastDone) + case "2": + close(lateStarted) + } + return 0, nil + }).Times(3) + c := Controller{Epoch: 1, Config: &protocol.Config{ApplyWorkers: 2}, Capture: capture} + done := make(chan error, 1) + go func() { + done <- c.applyRanges(ctx, tasks, spec, ref, func() (bool, error) { + select { + case <-fastDone: + return true, tasks.Ready("2", exports[2]) + default: + return false, nil + } + }, func(int) error { return nil }) + }() + select { + case <-lateStarted: + case <-ctx.Done(): + t.Fatal("new export was blocked behind the slow range") + } + require.Eventually(t, func() bool { + all, err := tasks.List() + if err != nil { + return false + } + return all[0].State == "APPLYING" && all[2].State == "APPLIED" + }, time.Second, time.Millisecond) + close(releaseSlow) + require.NoError(t, <-done) +} diff --git a/pkg/snapshot/kafka_output.go b/pkg/snapshot/kafka_output.go new file mode 100644 index 0000000000..f3b4ca37c7 --- /dev/null +++ b/pkg/snapshot/kafka_output.go @@ -0,0 +1,220 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "context" + "net/url" + "strconv" + + "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" + "github.com/pingcap/ticdc/downstreamadapter/sink/eventrouter" + "github.com/pingcap/ticdc/downstreamadapter/sink/helper" + "github.com/pingcap/ticdc/downstreamadapter/sink/topicmanager" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/metrics" + "github.com/pingcap/ticdc/pkg/sink/codec" + codecCommon "github.com/pingcap/ticdc/pkg/sink/codec/common" + "github.com/pingcap/ticdc/pkg/sink/codec/schemamanager" + "github.com/pingcap/ticdc/pkg/sink/kafka" + "github.com/pingcap/ticdc/pkg/sink/kafka/claimcheck" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/util" + "github.com/pingcap/ticdc/pkg/writelease" + "golang.org/x/sync/errgroup" +) + +// kafkaContext owns immutable routing/encoding settings and shared topic metadata. +// Producers and encoders belong to individual workers, never this context. +type kafkaContext struct { + router *eventrouter.EventRouter + columns *columnselector.ColumnSelectors + topics topicmanager.TopicManager + admin kafka.AdminClient + metadataFactory kafka.Factory + claimCheck *claimcheck.ClaimCheck + gate *writelease.Gate +} + +func (s *kafkaContext) close() { + if s.topics != nil { + s.topics.Close() + } + if s.admin != nil { + s.admin.Close() + } + if s.claimCheck != nil { + s.claimCheck.Close() + } + if s.metadataFactory != nil { + s.metadataFactory.Close() + } +} + +// newKafkaWriter creates a real factory/client for every worker for both Kafka +// implementations. In particular, franz producers from one factory share a client. +func newKafkaWriter(ctx context.Context, cfg *config.ChangefeedConfig, uri *url.URL, + gate *writelease.Gate, statistics *metrics.SnapshotStatistics, +) (_ *Writer, err error) { + shared := &kafkaContext{gate: gate} + var outputs []snapshotOutput + defer func() { + if err != nil { + for _, output := range outputs { + output.Close() + } + shared.close() + } + }() + wireProtocol, err := helper.GetProtocol(util.GetOrZero(cfg.SinkConfig.Protocol)) + if err != nil { + return nil, err + } + topic, err := helper.GetTopic(uri) + if err != nil { + return nil, err + } + options := kafka.NewOptions() + if err = options.Apply(cfg.ChangefeedID, uri, cfg.SinkConfig); err != nil { + return nil, err + } + options.Topic = topic + shared.metadataFactory, err = kafka.NewFactory(ctx, options, cfg.ChangefeedID, nil) + if err != nil { + return nil, err + } + shared.admin, err = shared.metadataFactory.AdminClient(ctx) + if err != nil { + return nil, err + } + shared.topics, err = topicmanager.GetTopicManagerAndTryCreateTopic( + ctx, cfg.ChangefeedID, topic, options.DeriveTopicConfig(), shared.admin, + ) + if err != nil { + return nil, err + } + avro := wireProtocol == config.ProtocolAvro || wireProtocol == config.ProtocolDebeziumAvro + shared.router, err = eventrouter.NewEventRouter(cfg.SinkConfig, cfg.CaseSensitive, topic, false, avro) + if err != nil { + return nil, err + } + shared.columns, err = columnselector.New(cfg.SinkConfig, cfg.CaseSensitive) + if err != nil { + return nil, err + } + encoderConfig, err := helper.GetEncoderConfig( + cfg.ChangefeedID, uri, wireProtocol, cfg.SinkConfig, options.MaxMessageBytes, options.MaxBatchedBytes, + ) + if err != nil { + return nil, err + } + if options.Client == kafka.KafkaClientFranz { + encoderConfig.WithKafkaRecordBatchSize() + } + shared.claimCheck, err = claimcheck.New(ctx, encoderConfig.LargeMessageHandle, cfg.ChangefeedID) + if err != nil { + return nil, err + } + if shared.claimCheck != nil { + shared.claimCheck.SetWriteGate(gate) + } + var schemaManager schemamanager.SchemaManager + if avro { + schemaManager, err = schemamanager.NewSchemaManager(ctx, encoderConfig) + if err != nil { + return nil, err + } + } + for i := 0; i < cfg.Snapshot.ApplyConcurrency(); i++ { + output := &kafkaOutput{shared: shared} + // Include partial construction in cleanup before making network resources. + outputs = append(outputs, output) + output.encoder, err = codec.NewEventEncoder(encoderConfig, shared.claimCheck, schemaManager) + if err != nil { + return nil, err + } + output.factory, err = kafka.NewSnapshotFactory(ctx, options, cfg.ChangefeedID, strconv.Itoa(i)) + if err != nil { + return nil, err + } + output.producer, err = output.factory.AsyncProducer(ctx) + if err != nil { + return nil, err + } + output.collector = output.factory.MetricsCollector(shared.admin) + } + writer := newWriter(ctx, outputs, cfg.Snapshot, cfg.Epoch, statistics) + writer.cleanup = shared.close + return writer, nil +} + +type kafkaOutput struct { + shared *kafkaContext + encoder codecCommon.EventEncoder + factory kafka.Factory + producer kafka.AsyncProducer + collector kafka.MetricsCollector +} + +// Write encodes one bounded batch on its owning worker. Kafka callbacks retain +// the batch's ACK accounting while the worker continues filling its own budget. +func (o *kafkaOutput) Write(ctx context.Context, event *commonEvent.DMLEvent) error { + s := o.shared + schema, table := event.TableInfo.GetSchemaName(), event.TableInfo.GetTableName() + topic := s.router.GetTopicForRowChange(schema, table) + if err := writelease.WaitForWrite(ctx, s.gate); err != nil { + return err + } + partitions, err := s.topics.GetPartitionNum(ctx, topic) + if err != nil { + return err + } + rows, err := helper.NewMQRowEvents( + event, topic, partitions, s.router.GetPartitionGenerator(schema, table), s.columns.GetForTableInfo(event.TableInfo), + ) + if err != nil { + return err + } + groups := make(map[commonEvent.TopicPartitionKey][]*commonEvent.RowEvent) + for _, row := range rows { + groups[row.Key] = append(groups[row.Key], &row.RowEvent) + } + for key, group := range groups { + for _, row := range group { + if err = o.encoder.AppendRowChangedEvent(ctx, key.Topic, row); err != nil { + return err + } + } + messages := o.encoder.Build() + if err = codecCommon.AttachMessageLogInfo(messages, group); err != nil { + return protocol.Wrap(err) + } + for _, message := range messages { + if err = writelease.WaitForWrite(ctx, s.gate); err != nil { + return err + } + if err = o.producer.AsyncSend(ctx, key.Topic, key.Partition, message); err != nil { + return err + } + } + } + return nil +} + +func (o *kafkaOutput) Run(ctx context.Context) error { + group, ctx := errgroup.WithContext(ctx) + group.Go(func() error { return o.producer.AsyncRunCallback(ctx) }) + if o.collector != nil { + group.Go(func() error { o.collector.Run(ctx); return nil }) + } + return group.Wait() +} + +func (o *kafkaOutput) Close() { + if o.producer != nil { + kafka.CloseSnapshotProducer(o.producer) + } + if o.factory != nil { + o.factory.Close() + } +} diff --git a/pkg/snapshot/kafka_output_test.go b/pkg/snapshot/kafka_output_test.go new file mode 100644 index 0000000000..9dad8abfa6 --- /dev/null +++ b/pkg/snapshot/kafka_output_test.go @@ -0,0 +1,67 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "context" + "net/url" + "testing" + "time" + + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/util" + "github.com/stretchr/testify/require" + "github.com/twmb/franz-go/pkg/kfake" +) + +func TestKafkaWorkersEncodeAndAcknowledgeIndependently(t *testing.T) { + for _, client := range []string{"sarama", "franz"} { + t.Run(client, func(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + helper.DDL2Job("create table test.snapshot_output (id int primary key, v varchar(50))") + const topic = "snapshot-output" + cluster := kfake.MustCluster(kfake.NumBrokers(1), kfake.SeedTopics(2, topic)) + defer cluster.Close() + uri, err := url.Parse( + "kafka://" + cluster.ListenAddrs()[0] + "/" + topic + "?kafka-client=" + client + "&partition-num=2&replication-factor=1", + ) + require.NoError(t, err) + sinkConfig := config.GetDefaultReplicaConfig().Sink + sinkConfig.Protocol = util.AddressOf("open-protocol") + cfg := &config.ChangefeedConfig{ + ChangefeedID: common.NewChangeFeedIDWithName("snapshot-output-"+client, common.DefaultKeyspaceName), + Epoch: 7, SinkConfig: sinkConfig, CaseSensitive: true, Snapshot: &protocol.Config{ApplyWorkers: 2}, + } + w, err := newKafkaWriter(t.Context(), cfg, uri, nil, nil) + require.NoError(t, err) + defer w.Close() + first, second := <-w.idle, <-w.idle + require.NotSame(t, first.output, second.output) + require.NotSame(t, first.output.(*kafkaOutput).encoder, second.output.(*kafkaOutput).encoder) + events := []*commonEvent.DMLEvent{ + helper.DML2Event("test", "snapshot_output", "insert into test.snapshot_output values(1,'first')"), + helper.DML2Event("test", "snapshot_output", "insert into test.snapshot_output values(2,'second')"), + } + ack := make(chan struct{}, 2) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + for i, worker := range []*applyWorker{first, second} { + events[i].AddPostFlushFunc(func() { ack <- struct{}{} }) + require.NoError(t, worker.output.Write(ctx, events[i])) + } + for range events { + select { + case <-ack: + case <-ctx.Done(): + t.Fatal("worker's encoded batch was not acknowledged") + } + } + w.idle <- first + w.idle <- second + require.NoError(t, w.DrainSnapshot(ctx, common.ChangeFeedID{}, 7)) + }) + } +} diff --git a/pkg/snapshot/output_mock_test.go b/pkg/snapshot/output_mock_test.go new file mode 100644 index 0000000000..d3cff8e036 --- /dev/null +++ b/pkg/snapshot/output_mock_test.go @@ -0,0 +1,76 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pkg/snapshot/writer.go + +// Package snapshot is a generated GoMock package. +package snapshot + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + event "github.com/pingcap/ticdc/pkg/common/event" +) + +// MocksnapshotOutput is a mock of snapshotOutput interface. +type MocksnapshotOutput struct { + ctrl *gomock.Controller + recorder *MocksnapshotOutputMockRecorder +} + +// MocksnapshotOutputMockRecorder is the mock recorder for MocksnapshotOutput. +type MocksnapshotOutputMockRecorder struct { + mock *MocksnapshotOutput +} + +// NewMocksnapshotOutput creates a new mock instance. +func NewMocksnapshotOutput(ctrl *gomock.Controller) *MocksnapshotOutput { + mock := &MocksnapshotOutput{ctrl: ctrl} + mock.recorder = &MocksnapshotOutputMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MocksnapshotOutput) EXPECT() *MocksnapshotOutputMockRecorder { + return m.recorder +} + +// Close mocks base method. +func (m *MocksnapshotOutput) Close() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Close") +} + +// Close indicates an expected call of Close. +func (mr *MocksnapshotOutputMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MocksnapshotOutput)(nil).Close)) +} + +// Run mocks base method. +func (m *MocksnapshotOutput) Run(arg0 context.Context) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Run", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Run indicates an expected call of Run. +func (mr *MocksnapshotOutputMockRecorder) Run(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MocksnapshotOutput)(nil).Run), arg0) +} + +// Write mocks base method. +func (m *MocksnapshotOutput) Write(arg0 context.Context, arg1 *event.DMLEvent) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Write", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// Write indicates an expected call of Write. +func (mr *MocksnapshotOutputMockRecorder) Write(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MocksnapshotOutput)(nil).Write), arg0, arg1) +} diff --git a/pkg/snapshot/protocol/protocol_test.go b/pkg/snapshot/protocol/protocol_test.go index 3a3e4112da..566186645f 100644 --- a/pkg/snapshot/protocol/protocol_test.go +++ b/pkg/snapshot/protocol/protocol_test.go @@ -105,9 +105,16 @@ func TestRuntimeLimits(t *testing.T) { var defaults *Config require.NoError(t, defaults.ValidateRuntime()) require.Equal(t, 4, defaults.ApplyConcurrency()) - require.EqualValues(t, 256<<20, defaults.InflightLimit()) - for _, c := range []Config{{ApplyWorkers: -1}, {ApplyWorkers: 33}, {WriteMemoryQuota: 1}, {WriteMemoryQuota: (1 << 30) + 1}} { + require.EqualValues(t, 128<<20, defaults.InflightLimit()) + var configured Config + require.NoError(t, json.Unmarshal([]byte(`{"apply-workers":8,"write-memory-quota-per-worker":268435456}`), &configured)) + require.EqualValues(t, 256<<20, configured.InflightLimit()) + encoded, err := json.Marshal(configured) + require.NoError(t, err) + require.Contains(t, string(encoded), `"write-memory-quota-per-worker":268435456`) + require.NotContains(t, string(encoded), `"write-memory-quota":`) + for _, c := range []Config{{ApplyWorkers: -1}, {ApplyWorkers: 33}, {WriteMemoryQuotaPerWorker: 1}, {WriteMemoryQuotaPerWorker: (1 << 30) + 1}} { require.Error(t, c.ValidateRuntime()) } - require.NoError(t, (&Config{ApplyWorkers: 16, WriteMemoryQuota: 32 << 20}).ValidateRuntime()) + require.NoError(t, (&Config{ApplyWorkers: 16, WriteMemoryQuotaPerWorker: 32 << 20}).ValidateRuntime()) } diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go index d9a137ceac..422863eb04 100644 --- a/pkg/snapshot/protocol/types.go +++ b/pkg/snapshot/protocol/types.go @@ -110,9 +110,9 @@ type State struct { // Config controls the independent snapshot pipeline. Quotas are in bytes. type Config struct { ApplyWorkers int `toml:"apply-workers" json:"apply-workers,omitempty"` - // WriteMemoryQuota bounds mounted rows awaiting sink ACKs across all apply - // workers. Default: 256 MiB. Chunk buffers and sink overhead are additional. - WriteMemoryQuota int64 `toml:"write-memory-quota" json:"write-memory-quota,omitempty"` + // WriteMemoryQuotaPerWorker bounds mounted rows awaiting sink ACKs in each + // apply worker. Default: 128 MiB. Chunk buffers and sink overhead are additional. + WriteMemoryQuotaPerWorker int64 `toml:"write-memory-quota-per-worker" json:"write-memory-quota-per-worker,omitempty"` // ReadMemoryQuotaPerProcess bounds SST file contents cached in memory, not process RSS. ReadMemoryQuotaPerProcess int64 `toml:"read-memory-quota-per-process" json:"read-memory-quota-per-process,omitempty"` ExportWorkers int `toml:"export-workers" json:"export-workers,omitempty"` @@ -123,7 +123,7 @@ type Config struct { } // ApplyConcurrency and InflightLimit bound capture-side work independently of -// CSE export workers. The byte budget covers mounted data awaiting ACK; +// CSE export workers. Each worker owns a byte budget for mounted data awaiting ACK; // each worker additionally owns at most one bounded input chunk and batch. func (c *Config) ApplyConcurrency() int { if c == nil || c.ApplyWorkers == 0 { @@ -133,10 +133,10 @@ func (c *Config) ApplyConcurrency() int { } func (c *Config) InflightLimit() int64 { - if c == nil || c.WriteMemoryQuota == 0 { - return 256 << 20 + if c == nil || c.WriteMemoryQuotaPerWorker == 0 { + return 128 << 20 } - return c.WriteMemoryQuota + return c.WriteMemoryQuotaPerWorker } func (c *Config) ReadLimit() int64 { @@ -174,7 +174,7 @@ func (c *Config) ValidateRuntime() error { return Invalid("apply-workers must be between 1 and 32") } if c.InflightLimit() < 32<<20 || c.InflightLimit() > 1<<30 { - return Invalid("write-memory-quota must be between 32 MiB and 1 GiB") + return Invalid("write-memory-quota-per-worker must be between 32 MiB and 1 GiB") } return nil } diff --git a/pkg/snapshot/service.go b/pkg/snapshot/service.go index 578e1618f7..ab5ef0f500 100644 --- a/pkg/snapshot/service.go +++ b/pkg/snapshot/service.go @@ -4,6 +4,7 @@ package snapshot import ( "context" "encoding/json" + "net/url" "os" "path/filepath" "sync" @@ -331,19 +332,33 @@ func (s *Service) execute(ctx context.Context, req request) error { if err != nil { return protocol.Wrap(err) } - sk, err := sink.New(ctx, cfg, cfg.ChangefeedID, req.Keyspace) - if err != nil { - return err - } - if gate, ok := appcontext.TryGetService[*writelease.Gate](appcontext.CaptureWriteGate); ok { - sk.SetWriteGate(gate) - } statistics := metrics.NewSnapshotStatistics(cfg.ChangefeedID.Keyspace(), cfg.ChangefeedID.Name()) statistics.Start("overall") statistics.Set("inflight_bytes", 0) - statistics.Set("write_memory_quota_bytes", float64(cfg.Snapshot.InflightLimit())) + statistics.Set("write_memory_quota_per_worker_bytes", float64(cfg.Snapshot.InflightLimit())) + statistics.Set("write_memory_quota_bytes", float64(cfg.Snapshot.InflightLimit())*float64(cfg.Snapshot.ApplyConcurrency())) statistics.Set("disk_quota_bytes", float64(cfg.Snapshot.DiskLimit())) - writer := NewWriter(ctx, sk, cfg.Snapshot, cfg.Epoch, statistics) + uri, err := url.Parse(cfg.SinkURI) + if err != nil { + return protocol.Invalid("invalid snapshot sink URI") + } + gate, _ := appcontext.TryGetService[*writelease.Gate](appcontext.CaptureWriteGate) + var writer *Writer + scheme := config.GetScheme(uri) + if scheme == config.KafkaScheme || scheme == config.KafkaSSLScheme { + writer, err = newKafkaWriter(ctx, cfg, uri, gate, statistics) + } else { + var sk sink.Sink + sk, err = sink.New(ctx, cfg, cfg.ChangefeedID, req.Keyspace) + if err == nil { + sk.SetWriteGate(gate) + writer = NewWriter(ctx, sk, cfg.Snapshot, cfg.Epoch, statistics) + } + } + if err != nil { + statistics.Error("overall") + return err + } defer writer.Close() go func() { select { diff --git a/pkg/snapshot/writer.go b/pkg/snapshot/writer.go index bea6a5b2d4..db6a8b69ad 100644 --- a/pkg/snapshot/writer.go +++ b/pkg/snapshot/writer.go @@ -16,6 +16,7 @@ import ( "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/tidb/pkg/util/chunk" + "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" ) @@ -29,8 +30,6 @@ const ( type snapshotRuntime struct { spec protocol.Spec tables map[int64]*common.TableInfo - budget *semaphore.Weighted - limit int64 } // The immutable schema bundle is shared by all range workers of this capture. @@ -73,7 +72,7 @@ func (e *Writer) getSnapshotRuntime(spec protocol.Spec) (*snapshotRuntime, error } tables[s.TableID] = table } - r := &snapshotRuntime{spec: spec, tables: tables, limit: cfg.InflightLimit(), budget: semaphore.NewWeighted(cfg.InflightLimit())} + r := &snapshotRuntime{spec: spec, tables: tables} e.snapshotRuntime = r return r, nil } @@ -116,16 +115,36 @@ func (a *snapshotAcks) wait(ctx context.Context) error { return nil } -// ApplySnapshot mounts bounded batches into this execution attempt's independent sink. -// Workers share a byte budget released by broker ACKs. Only range completion -// drains all its callbacks; ordinary submission keeps the sink pipeline fed. -func (e *Writer) ApplySnapshot( - ctx context.Context, - _ common.ChangeFeedID, - epoch uint64, - spec protocol.Spec, - ref protocol.ObjectRef, - ex protocol.Export, +// ApplySnapshot leases one long-lived worker for the entire range, including ACKs. +func (e *Writer) ApplySnapshot(ctx context.Context, _ common.ChangeFeedID, epoch uint64, + spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export, +) (uint64, error) { + select { + case <-ctx.Done(): + return 0, protocol.Wrap(ctx.Err()) + case <-e.ctx.Done(): + return 0, protocol.Wrap(e.ctx.Err()) + case worker := <-e.idle: + defer func() { e.idle <- worker }() + rows, err := worker.apply(ctx, e, epoch, spec, ref, ex) + if err != nil { + e.cancel() + } + return rows, err + } +} + +// Each worker retains its mounter, output and private ACK budget across ranges. +type applyWorker struct { + id int + output snapshotOutput + budget *semaphore.Weighted + limit int64 + mounter commonEvent.Mounter +} + +func (w *applyWorker) apply(ctx context.Context, e *Writer, epoch uint64, + spec protocol.Spec, ref protocol.ObjectRef, ex protocol.Export, ) (uint64, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() @@ -168,7 +187,7 @@ func (e *Writer) ApplySnapshot( if table == nil { return 0, protocol.Invalid("missing frozen table schema") } - mounter := commonEvent.NewMounter(time.UTC, &integrity.Config{}) + mounter := w.mounter acks := newSnapshotAcks() dispatcherID := common.NewDispatcherID() var rows uint64 @@ -178,28 +197,33 @@ func (e *Writer) ApplySnapshot( return nil } charge := batch.ApproximateSize + int64(batch.Length)*snapshotRowOverhead - if charge > runtime.limit { + if charge > w.limit { return protocol.Invalid("snapshot batch exceeds in-flight byte budget") } waitStarted := time.Now() - if err := runtime.budget.Acquire(ctx, charge); err != nil { + if err := w.budget.Acquire(ctx, charge); err != nil { return protocol.Wrap(err) } e.statistics.Observe("write_budget_wait", time.Since(waitStarted)) if err := authorized(); err != nil { - runtime.budget.Release(charge) + w.budget.Release(charge) return err } batchBytes, batchRows := uint64(batch.ApproximateSize), uint64(batch.Length) submittedAt := time.Now() e.statistics.Add("inflight_bytes", float64(charge)) + e.statistics.WorkerInflight(w.id, float64(charge)) batch.AddPostFlushFunc(acks.add(func() { - runtime.budget.Release(charge) + w.budget.Release(charge) e.statistics.Add("inflight_bytes", -float64(charge)) + e.statistics.WorkerInflight(w.id, -float64(charge)) e.statistics.Output("apply", batchBytes, batchRows) + e.statistics.WorkerOutput(w.id, batchBytes) e.statistics.Observe("sink_ack", time.Since(submittedAt)) })) - e.writeSink.AddDMLEvent(batch) + if err := w.output.Write(ctx, batch); err != nil { + return err + } batch = nil return nil } @@ -279,14 +303,34 @@ func (e *Writer) DrainSnapshot(ctx context.Context, _ common.ChangeFeedID, epoch default: } e.Close() + return e.sinkErr +} + +// snapshotOutput has only the operations used by the snapshot data path. +type snapshotOutput interface { + Write(context.Context, *commonEvent.DMLEvent) error + Run(context.Context) error + Close() +} + +// storageOutput preserves one backend's file/index ownership across all workers. +type storageOutput struct{ sink.Sink } + +func (s storageOutput) Write(ctx context.Context, event *commonEvent.DMLEvent) error { + if err := ctx.Err(); err != nil { + return protocol.Wrap(err) + } + s.AddDMLEvent(event) return nil } -// Writer owns exactly one snapshot sink. All workers share its write budget. +// Writer owns a fixed worker pool and all output lifetimes for one execution. type Writer struct { ctx context.Context cancel context.CancelFunc - writeSink sink.Sink + outputs []snapshotOutput + cleanup func() + idle chan *applyWorker sinkStopped chan struct{} sinkErr error epoch uint64 @@ -299,25 +343,60 @@ type Writer struct { statistics *metrics.SnapshotStatistics } -func NewWriter(ctx context.Context, sk sink.Sink, cfg *protocol.Config, epoch uint64, statistics ...*metrics.SnapshotStatistics) *Writer { +func newWriter( + ctx context.Context, outputs []snapshotOutput, cfg *protocol.Config, epoch uint64, stats *metrics.SnapshotStatistics, +) *Writer { ctx, cancel := context.WithCancel(ctx) - w := &Writer{ctx: ctx, cancel: cancel, writeSink: sk, config: cfg, epoch: epoch, sinkStopped: make(chan struct{})} - if len(statistics) > 0 { - w.statistics = statistics[0] + w := &Writer{ + ctx: ctx, cancel: cancel, outputs: outputs, config: cfg, epoch: epoch, + sinkStopped: make(chan struct{}), + idle: make(chan *applyWorker, cfg.ApplyConcurrency()), statistics: stats, } - go func() { - w.sinkErr = sk.Run(ctx) - if ctx.Err() != nil { - w.sinkErr = nil - } else if w.sinkErr == nil { - w.sinkErr = protocol.Invalid("snapshot sink stopped unexpectedly") + for i := 0; i < cfg.ApplyConcurrency(); i++ { + stats.ResetWorker(i) + w.idle <- &applyWorker{ + id: i, output: outputs[i%len(outputs)], limit: cfg.InflightLimit(), + budget: semaphore.NewWeighted(cfg.InflightLimit()), + mounter: commonEvent.NewMounter(time.UTC, &integrity.Config{}), } - close(w.sinkStopped) - }() + } + group, runCtx := errgroup.WithContext(ctx) + for _, output := range outputs { + group.Go(func() error { + err := output.Run(runCtx) + if runCtx.Err() != nil { + return nil + } + if err == nil { + return protocol.Invalid("snapshot output stopped unexpectedly") + } + return err + }) + } + go func() { w.sinkErr = group.Wait(); close(w.sinkStopped) }() return w } +// NewWriter uses one shared storage backend while each worker owns its quota. +func NewWriter(ctx context.Context, sk sink.Sink, cfg *protocol.Config, epoch uint64, statistics ...*metrics.SnapshotStatistics) *Writer { + var stats *metrics.SnapshotStatistics + if len(statistics) > 0 { + stats = statistics[0] + } + return newWriter(ctx, []snapshotOutput{storageOutput{sk}}, cfg, epoch, stats) +} + func (w *Writer) Close() { - w.closeOnce.Do(func() { w.writePathClosed.Store(true); w.cancel(); <-w.sinkStopped; w.writeSink.Close() }) + w.closeOnce.Do(func() { + w.writePathClosed.Store(true) + w.cancel() + <-w.sinkStopped + for _, output := range w.outputs { + output.Close() + } + if w.cleanup != nil { + w.cleanup() + } + }) } func (w *Writer) AbortSnapshot(common.ChangeFeedID) { w.Close() } diff --git a/pkg/snapshot/writer_test.go b/pkg/snapshot/writer_test.go index f0b341fd51..be10f8bd44 100644 --- a/pkg/snapshot/writer_test.go +++ b/pkg/snapshot/writer_test.go @@ -16,12 +16,14 @@ import ( "github.com/pingcap/ticdc/downstreamadapter/sink/mock" "github.com/pingcap/ticdc/pkg/common" commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/integrity" "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" + "golang.org/x/sync/semaphore" ) func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { @@ -73,7 +75,9 @@ func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { sk.EXPECT().AddDMLEvent(gomock.Any()).Do(func(ev *commonEvent.DMLEvent) { submitted <- ev }).AnyTimes() metricFeed := fmt.Sprintf("snapshot-ack-%d", time.Now().UnixNano()) statistics := metrics.NewSnapshotStatistics("test", metricFeed) - manager := &Writer{statistics: statistics, epoch: 7, ctx: context.Background(), writeSink: sk, sinkStopped: make(chan struct{})} + manager := &Writer{statistics: statistics, epoch: 7, ctx: context.Background(), cancel: func() {}, idle: make(chan *applyWorker, 1), sinkStopped: make(chan struct{})} + worker := &applyWorker{output: storageOutput{sk}, limit: 128 << 20, budget: semaphore.NewWeighted(128 << 20), mounter: commonEvent.NewMounter(time.UTC, &integrity.Config{})} + manager.idle <- worker run := func(ctx context.Context) <-chan error { done := make(chan error, 1) go func() { @@ -114,8 +118,8 @@ func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { require.Equal(t, float64(size), snapshotMetricValue(t, "bytes_total", metricFeed, "apply")) runtime, err := manager.getSnapshotRuntime(spec) require.NoError(t, err) - require.True(t, runtime.budget.TryAcquire(runtime.limit)) - runtime.budget.Release(runtime.limit) + require.True(t, worker.budget.TryAcquire(worker.limit)) + worker.budget.Release(worker.limit) require.NoError(t, os.Remove(schemaRef.URI)) cached, err := manager.getSnapshotRuntime(spec) require.NoError(t, err) @@ -126,12 +130,12 @@ func TestSnapshotBatchAcksBudgetAndFence(t *testing.T) { require.ErrorContains(t, err, "identity changed") // Backpressure can be canceled before submission, without leaking a waiter. - require.NoError(t, runtime.budget.Acquire(context.Background(), runtime.limit)) + require.NoError(t, worker.budget.Acquire(context.Background(), worker.limit)) ctx, cancel := context.WithCancel(context.Background()) done = run(ctx) cancel() require.Error(t, <-done) - runtime.budget.Release(runtime.limit) + worker.budget.Release(worker.limit) select { case <-submitted: t.Fatal("submitted without budget") @@ -230,3 +234,45 @@ func snapshotMetricValue(t *testing.T, name, changefeed, stage string) float64 { } return 0 } + +func TestWriterWorkerBudgetsAreIndependentAndOutputsJoined(t *testing.T) { + ctrl := gomock.NewController(t) + first, second := NewMocksnapshotOutput(ctrl), NewMocksnapshotOutput(ctrl) + runStarted := make(chan struct{}, 2) + failure := protocol.Invalid("worker producer failed") + fail := make(chan struct{}) + first.EXPECT().Run(gomock.Any()).DoAndReturn(func(ctx context.Context) error { + runStarted <- struct{}{} + select { + case <-ctx.Done(): + return ctx.Err() + case <-fail: + return failure + } + }) + second.EXPECT().Run(gomock.Any()).DoAndReturn(func(ctx context.Context) error { runStarted <- struct{}{}; <-ctx.Done(); return ctx.Err() }) + first.EXPECT().Close().Times(1) + second.EXPECT().Close().Times(1) + w := newWriter(t.Context(), []snapshotOutput{first, second}, &protocol.Config{ApplyWorkers: 2}, 7, nil) + <-runStarted + <-runStarted + a, b := <-w.idle, <-w.idle + require.NotSame(t, a.output, b.output) + require.EqualValues(t, 128<<20, a.limit) + require.NoError(t, a.budget.Acquire(t.Context(), a.limit)) + require.True(t, b.budget.TryAcquire(b.limit), "one saturated worker must not block another") + b.budget.Release(b.limit) + a.budget.Release(a.limit) + w.idle <- a + w.idle <- b + require.Same(t, a, (<-w.idle)) + close(fail) + select { + case <-w.sinkStopped: + case <-time.After(5 * time.Second): + t.Fatal("failed output did not cancel and join its sibling") + } + require.ErrorIs(t, w.sinkErr, failure) + w.Close() + w.Close() +} diff --git a/scripts/generate-mock.sh b/scripts/generate-mock.sh index 0c618b670a..c30caba356 100755 --- a/scripts/generate-mock.sh +++ b/scripts/generate-mock.sh @@ -70,6 +70,7 @@ run_mockgen -source pkg/redo/writer/writer.go -destination pkg/redo/writer/write run_mockgen -source downstreamadapter/sink/sink.go -destination downstreamadapter/sink/mock/sink_mock.go -package mock run_mockgen -destination pkg/messaging/mock/message_center_mock.go -package mock github.com/pingcap/ticdc/pkg/messaging MessageCenter run_mockgen -destination pkg/snapshot/service_mock_test.go -package snapshot github.com/pingcap/ticdc/pkg/snapshot Nodes,Repository +run_mockgen -source pkg/snapshot/writer.go -destination pkg/snapshot/output_mock_test.go -package snapshot run_mockgen -source pkg/snapshot/bootstrap/interfaces.go -destination pkg/snapshot/bootstrap/interfaces_mock_test.go -package bootstrap wait_for_batch diff --git a/tests/integration_tests/native_snapshot/README.md b/tests/integration_tests/native_snapshot/README.md index 4ad1ae9034..f548f0f94e 100644 --- a/tests/integration_tests/native_snapshot/README.md +++ b/tests/integration_tests/native_snapshot/README.md @@ -27,7 +27,7 @@ read-memory-quota-per-process = 536870912 apply-workers = 4 # Mounted rows awaiting sink ACKs; shared by all apply workers (default 256 MiB). # Input chunks and the sink's internal buffers are additional memory. -write-memory-quota = 268435456 +write-memory-quota-per-worker = 134217728 # 128 MiB per apply worker # Entire per-changefeed snapshot directory, including partial export attempts. # Default is decimal 200 GB. Export admission pauses near the quota; a range # exceeding it is interrupted and must be retried with a sufficient quota. @@ -37,6 +37,11 @@ disk-quota = 200000000000 Disk usage checks are sampled and may briefly overshoot the quota; this is not a filesystem hard quota. +Each apply worker keeps its own Kafka producer/client and encoder across ranges. +The default write quota is 128 MiB per worker; four workers allow 512 MiB of +mounted data awaiting ACKs in total. Cloud storage shares one file/index backend +while retaining independent worker quotas. + All byte quotas are integers. Snapshot files live under `/snapshot//`, alongside the sorter's parent directory. Install the matching `cse-ctl` at `/usr/local/bin/cse-ctl`, or set the absolute @@ -71,7 +76,7 @@ row values, ordering and duplicate row keys without requiring extra Kafka fields ## Monitoring The TiCDC dashboard includes a Snapshot row with export and sink-ACK throughput, -active workers, range progress, shared write-memory usage, sampled artifact disk +active workers, range progress, per-worker write-memory usage, sampled artifact disk usage, retry/failure counts, and stage and operation durations. Both throughput series use logical KV key+value bytes. Apply counters advance on PostFlush, not when a batch is enqueued, and count replayed writes again. Export and apply run From 0be992e98381c58df77c265efb03a83594c30bb0 Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 30 Nov 2026 20:21:37 +0800 Subject: [PATCH 15/17] snapshot: put copyright before the platform build tag --- pkg/snapshot/exporter/process_other.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pkg/snapshot/exporter/process_other.go b/pkg/snapshot/exporter/process_other.go index c72e1dee79..0191842454 100644 --- a/pkg/snapshot/exporter/process_other.go +++ b/pkg/snapshot/exporter/process_other.go @@ -1,6 +1,7 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. + //go:build !linux -// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. package exporter import "os/exec" From 25c4474a77af3b059148350133d3a4cbe653d54b Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Mon, 30 Nov 2026 20:31:15 +0800 Subject: [PATCH 16/17] snapshot: satisfy current static checks --- coordinator/changefeed/etcd_backend.go | 4 ++-- coordinator/changefeed/etcd_backend_test.go | 2 +- pkg/errors/snapshot.go | 4 +--- pkg/snapshot/bootstrap/cleanup_test.go | 2 +- pkg/snapshot/bootstrap/controller.go | 10 ++++---- pkg/snapshot/bootstrap/controller_test.go | 6 ++--- pkg/snapshot/exporter/cleanup_test.go | 2 +- pkg/snapshot/exporter/disk.go | 2 +- pkg/snapshot/exporter/exporter.go | 17 +++++++------- pkg/snapshot/exporter/exporter_test.go | 4 ++-- pkg/snapshot/exporter/process_other.go | 2 +- pkg/snapshot/protocol/chunk.go | 8 +++---- pkg/snapshot/protocol/protocol_test.go | 2 +- pkg/snapshot/protocol/types.go | 4 ++-- pkg/snapshot/state/repository.go | 2 +- pkg/snapshot/store/local.go | 10 ++++---- pkg/snapshot/store/store_test.go | 8 +++---- pkg/snapshot/store/tasks.go | 2 +- pkg/snapshot/writer.go | 23 +++++++++++-------- .../native_snapshot/verify/main.go | 8 +++---- 20 files changed, 59 insertions(+), 63 deletions(-) diff --git a/coordinator/changefeed/etcd_backend.go b/coordinator/changefeed/etcd_backend.go index d23b4393f0..31764bf083 100644 --- a/coordinator/changefeed/etcd_backend.go +++ b/coordinator/changefeed/etcd_backend.go @@ -181,7 +181,7 @@ func (b *EtcdBackend) UpdateChangefeed(ctx context.Context, info *config.ChangeF if err != nil { return errors.Trace(err) } - for retry := 0; retry < 20; retry++ { + for range 20 { status, revision, err := b.etcdClient.GetChangeFeedStatus(ctx, info.ChangefeedID) if err != nil { return errors.Trace(err) @@ -473,7 +473,7 @@ func (b *EtcdBackend) UpdateChangefeedCheckpointTs(ctx context.Context, cps map[ } for start := 0; start < len(ids); start += 128 { saved := false - for retry := 0; retry < 20; retry++ { + for range 20 { var ops []clientv3.Op var comparisons []clientv3.Cmp for _, id := range ids[start:min(start+128, len(ids))] { diff --git a/coordinator/changefeed/etcd_backend_test.go b/coordinator/changefeed/etcd_backend_test.go index a280c28aea..eef6ee7680 100644 --- a/coordinator/changefeed/etcd_backend_test.go +++ b/coordinator/changefeed/etcd_backend_test.go @@ -139,7 +139,7 @@ func TestUpdateChangefeed(t *testing.T) { Return(&clientv3.TxnResponse{Succeeded: false}, nil).Times(20) require.NotNil(t, backend.UpdateChangefeed(context.Background(), &config.ChangeFeedInfo{}, 0, config.ProgressStopping)) - etcdClient.EXPECT().Txn(gomock.Any(), gomock.Len(1), NewFuncMatcher(func(i interface{}) bool { + etcdClient.EXPECT().Txn(gomock.Any(), gomock.Len(1), NewFuncMatcher(func(i any) bool { ops := i.([]clientv3.Op) require.Len(t, ops, 2) require.True(t, ops[0].IsPut()) diff --git a/pkg/errors/snapshot.go b/pkg/errors/snapshot.go index 2b420100ce..b331b7e22b 100644 --- a/pkg/errors/snapshot.go +++ b/pkg/errors/snapshot.go @@ -1,6 +1,4 @@ // Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. package errors -import "github.com/pingcap/errors" - -var ErrSnapshotBootstrap = errors.Normalize("snapshot bootstrap: %s", errors.RFCCodeText("CDC:ErrSnapshotBootstrap")) +var ErrSnapshotBootstrap = Normalize("snapshot bootstrap: %s", RFCCodeText("CDC:ErrSnapshotBootstrap")) diff --git a/pkg/snapshot/bootstrap/cleanup_test.go b/pkg/snapshot/bootstrap/cleanup_test.go index ff33c6f9a0..cd245cf0d0 100644 --- a/pkg/snapshot/bootstrap/cleanup_test.go +++ b/pkg/snapshot/bootstrap/cleanup_test.go @@ -16,7 +16,7 @@ func TestRemoveAppliedChunksOnlyInsideJobAttempts(t *testing.T) { require.NoError(t, os.MkdirAll(attempt, 0o700)) chunk := filepath.Join(attempt, "chunk-000000.skv") require.NoError(t, os.WriteFile(chunk, []byte("data"), 0o600)) - export := protocol.Export{JobID: "job", Chunks: []protocol.Chunk{{ObjectRef: protocol.ObjectRef{URI: chunk}}}} + export := protocol.Export{JobID: "job", Chunks: []protocol.Chunk{{URI: chunk}}} require.NoError(t, removeExportChunks(root, "job", export)) require.NoFileExists(t, chunk) require.NoError(t, removeExportChunks(root, "job", export)) diff --git a/pkg/snapshot/bootstrap/controller.go b/pkg/snapshot/bootstrap/controller.go index 4354932d3f..0a7500cb32 100644 --- a/pkg/snapshot/bootstrap/controller.go +++ b/pkg/snapshot/bootstrap/controller.go @@ -48,11 +48,11 @@ func (c Controller) Run(ctx context.Context) (result error) { if err != nil { return protocol.Wrap(err) } - defer lock.Close() + defer func() { _ = lock.Close() }() if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { return protocol.Invalid("previous snapshot writer has not drained") } - defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + defer func() { _ = syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) }() // An aborted writer must stop actual sink mutation before a new owner can // acquire the lock. Process death releases flock; old process cannot retry. defer func() { @@ -266,9 +266,7 @@ func (c Controller) applyRanges(ctx context.Context, tasks store.Tasks, spec pro jobs := make(chan store.Task, c.Config.ApplyConcurrency()) results := make(chan receipt, c.Config.ApplyConcurrency()) for i := 0; i < c.Config.ApplyConcurrency(); i++ { - workers.Add(1) - go func() { - defer workers.Done() + workers.Go(func() { for { select { case <-ctx.Done(): @@ -291,7 +289,7 @@ func (c Controller) applyRanges(ctx context.Context, tasks store.Tasks, spec pro } } } - }() + }) } ticker := time.NewTicker(200 * time.Millisecond) defer ticker.Stop() diff --git a/pkg/snapshot/bootstrap/controller_test.go b/pkg/snapshot/bootstrap/controller_test.go index 2c08b8b065..3e4e71ddaa 100644 --- a/pkg/snapshot/bootstrap/controller_test.go +++ b/pkg/snapshot/bootstrap/controller_test.go @@ -25,7 +25,7 @@ func TestApplyReadyBoundedReceiptsAndCancellation(t *testing.T) { objects := store.Local{Root: t.TempDir()} spec := protocol.Spec{ProtocolVersion: 1, JobID: "j", SnapshotID: "s", SnapshotTS: 42} plan := protocol.Plan{ProtocolVersion: 1, JobID: "j", SnapshotID: "s", SnapshotTS: 42} - for i := 0; i < 6; i++ { + for i := range 6 { plan.Ranges = append(plan.Ranges, protocol.Span{RangeID: fmt.Sprint(i), TableID: int64(i + 1), Start: []byte("a"), End: []byte("z")}) } ref, err := objects.Put("plan", plan) @@ -71,7 +71,7 @@ func TestApplyReadyBoundedReceiptsAndCancellation(t *testing.T) { go func() { done <- c.applyRanges(ctx, tasks, spec, ref, func() (bool, error) { return true, nil }, func(int) error { return nil }) }() - for i := 0; i < 2; i++ { + for range 2 { select { case <-started: case <-ctx.Done(): @@ -167,7 +167,7 @@ func TestApplyRangesDiscoversWorkWhileAnotherRangeWaitsForAck(t *testing.T) { objects := store.Local{Root: t.TempDir()} spec := protocol.Spec{ProtocolVersion: 1, JobID: "pipeline", SnapshotID: "s", SnapshotTS: 42} plan := protocol.Plan{ProtocolVersion: 1, JobID: spec.JobID, SnapshotID: "s", SnapshotTS: 42} - for i := 0; i < 3; i++ { + for i := range 3 { plan.Ranges = append(plan.Ranges, protocol.Span{RangeID: fmt.Sprint(i), TableID: int64(i + 1), Start: []byte("a"), End: []byte("z")}) } ref, err := objects.Put("plan", plan) diff --git a/pkg/snapshot/exporter/cleanup_test.go b/pkg/snapshot/exporter/cleanup_test.go index 3a887be6ca..d7c82ce5d2 100644 --- a/pkg/snapshot/exporter/cleanup_test.go +++ b/pkg/snapshot/exporter/cleanup_test.go @@ -17,7 +17,7 @@ func TestCleanupPreservesUnjournaledWinnerAndAcceptedPlan(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(root, name), 0o700)) require.NoError(t, os.WriteFile(filepath.Join(root, name, "file"), []byte("data"), 0o600)) } - _, err := s.Objects.Put("br/job/range-exports/range.json", protocol.Export{Chunks: []protocol.Chunk{{ObjectRef: protocol.ObjectRef{URI: filepath.Join(root, "published", "file")}}}}) + _, err := s.Objects.Put("br/job/range-exports/range.json", protocol.Export{Chunks: []protocol.Chunk{{URI: filepath.Join(root, "published", "file")}}}) require.NoError(t, err) // Simulate death after winner publication but before append to Job.Exports. require.NoError(t, s.cleanupAttempts("job", Job{PlanRef: protocol.ObjectRef{URI: filepath.Join(root, "plan", "file")}})) diff --git a/pkg/snapshot/exporter/disk.go b/pkg/snapshot/exporter/disk.go index 9bdd648a93..a854a50139 100644 --- a/pkg/snapshot/exporter/disk.go +++ b/pkg/snapshot/exporter/disk.go @@ -13,7 +13,7 @@ import ( func directoryUsage(root string) (int64, error) { var bytes int64 - err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + err := filepath.WalkDir(root, func(_ string, d fs.DirEntry, err error) error { if err != nil { if os.IsNotExist(err) { return nil diff --git a/pkg/snapshot/exporter/exporter.go b/pkg/snapshot/exporter/exporter.go index ae70f73c45..015fc8053c 100644 --- a/pkg/snapshot/exporter/exporter.go +++ b/pkg/snapshot/exporter/exporter.go @@ -18,6 +18,7 @@ import ( "syscall" "time" + "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/snapshot/store" @@ -63,7 +64,7 @@ func validID(id string) bool { return false } for _, r := range id { - if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-') { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '-' { return false } } @@ -71,7 +72,7 @@ func validID(id string) bool { } func (s *Runner) update(id string, fn func(*Job) error) error { - for retry := 0; retry < 30; retry++ { + for range 30 { var j Job v, e := s.Objects.Read(key(id), &j) if e != nil { @@ -207,6 +208,7 @@ func (s *Runner) batch(ctx context.Context, id, command string, task map[string] if s.ReadMemoryQuota > 0 { args = append(args, "--file-memory-limit-mib", strconv.FormatInt(s.ReadMemoryQuota>>20, 10)) } + // #nosec G204 -- The executable is trusted CDC server configuration; arguments never use a shell. cmd := exec.CommandContext(ctx, s.Binary, args...) configureProcess(cmd) cmd.Stdout = output @@ -222,7 +224,7 @@ func (s *Runner) batch(ctx context.Context, id, command string, task map[string] _ = os.WriteFile(filepath.Join(dir, "worker.log"), output.safe(), 0o600) cancel(nil) <-monitorDone - if cause := context.Cause(ctx); cause != context.Canceled && cause != nil { + if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) { e = cause } // Observability only: worker resource accounting is not part of the export @@ -321,10 +323,7 @@ func (s *Runner) run(ctx context.Context, id string) error { if e := protocol.Read(j.PlanRef, &plan); e != nil { return e } - workers := s.Workers - if workers < 1 { - workers = 1 - } + workers := max(s.Workers, 1) s.Statistics.Start("export") if e := materializeRanges(ctx, workers, plan.Ranges, func(ctx context.Context, r protocol.Span) error { return s.materialize(ctx, id, j, r) @@ -366,7 +365,7 @@ func materializeRanges(ctx context.Context, workers int, ranges []protocol.Span, } return nil }) - for i := 0; i < workers; i++ { + for range workers { group.Go(func() error { for r := range jobs { if e := ctx.Err(); e != nil { @@ -471,7 +470,7 @@ func (s *Runner) materialize(ctx context.Context, id string, j Job, r protocol.S // are never retried; callers validate each successful candidate before publish. func retryBatch(ctx context.Context, run func() (protocol.ObjectRef, error), onRetry ...func()) (protocol.ObjectRef, error) { var err error - for attempt := 0; attempt < 3; attempt++ { + for attempt := range 3 { if e := ctx.Err(); e != nil { return protocol.ObjectRef{}, protocol.Wrap(e) } diff --git a/pkg/snapshot/exporter/exporter_test.go b/pkg/snapshot/exporter/exporter_test.go index bac0a95a6f..27cb65b0d3 100644 --- a/pkg/snapshot/exporter/exporter_test.go +++ b/pkg/snapshot/exporter/exporter_test.go @@ -154,7 +154,7 @@ func TestMaterializeRangesBoundedAndComplete(t *testing.T) { return nil }) }() - for i := 0; i < 4; i++ { + for range 4 { select { case <-started: case <-ctx.Done(): @@ -201,7 +201,7 @@ func TestMaterializeRangesFailureCancelsAndJoins(t *testing.T) { return ctx.Err() }) }() - for i := 0; i < 4; i++ { + for range 4 { select { case <-started: case <-ctx.Done(): diff --git a/pkg/snapshot/exporter/process_other.go b/pkg/snapshot/exporter/process_other.go index 0191842454..a8e1e87242 100644 --- a/pkg/snapshot/exporter/process_other.go +++ b/pkg/snapshot/exporter/process_other.go @@ -6,4 +6,4 @@ package exporter import "os/exec" -func configureProcess(cmd *exec.Cmd) {} +func configureProcess(_ *exec.Cmd) {} diff --git a/pkg/snapshot/protocol/chunk.go b/pkg/snapshot/protocol/chunk.go index 0943598451..6e5a160c64 100644 --- a/pkg/snapshot/protocol/chunk.go +++ b/pkg/snapshot/protocol/chunk.go @@ -21,7 +21,7 @@ func DecodeChunk(ref Chunk, expected Header, span Span, emit func([]byte, []byte if err != nil { return zero, Wrap(err) } - defer f.Close() + defer func() { _ = f.Close() }() info, err := f.Stat() if err != nil { return zero, Wrap(err) @@ -66,8 +66,8 @@ func (r *bufferReader) take(n uint32) ([]byte, error) { return b, nil } -func readN(r io.Reader, n uint32, max uint32) ([]byte, error) { - if n > max { +func readN(r io.Reader, n uint32, maxBytes uint32) ([]byte, error) { + if n > maxBytes { return nil, Invalid("frame exceeds limit") } if r, ok := r.(*bufferReader); ok { @@ -165,7 +165,7 @@ func decode(r io.Reader, expected Header, span Span, ref Chunk, emit func([]byte return seen, e } block := &bufferReader{data: b} - for i := uint32(0); i < count; i++ { + for range count { kl, e := readU32(block) if e != nil { return seen, e diff --git a/pkg/snapshot/protocol/protocol_test.go b/pkg/snapshot/protocol/protocol_test.go index 566186645f..9f7bb98adf 100644 --- a/pkg/snapshot/protocol/protocol_test.go +++ b/pkg/snapshot/protocol/protocol_test.go @@ -87,7 +87,7 @@ func TestVerifiedBufferTruncationAndRetainedRows(t *testing.T) { expected := Header{Version: 1, Compression: "none", JobID: "golden", SnapshotID: "golden", SnapshotTS: 42, PlanDigest: "golden", RangeID: "r0", AttemptID: "a0", TableID: 1} ref := Chunk{KVCount: 2, LogicalBytes: 12, First: []byte("a"), Last: []byte("b")} span := Span{Start: []byte("a"), End: []byte("z")} - for i := 0; i < len(b); i++ { + for i := range b { _, err := decode(&bufferReader{data: b[:i]}, expected, span, ref, func([]byte, []byte) error { return nil }) require.Error(t, err, "truncation at %d", i) } diff --git a/pkg/snapshot/protocol/types.go b/pkg/snapshot/protocol/types.go index 422863eb04..d897ed0637 100644 --- a/pkg/snapshot/protocol/types.go +++ b/pkg/snapshot/protocol/types.go @@ -185,7 +185,7 @@ func Ref(path string) (ObjectRef, error) { if e != nil { return ObjectRef{}, Wrap(e) } - defer f.Close() + defer func() { _ = f.Close() }() h := sha256.New() n, e := io.Copy(h, f) return ObjectRef{path, hex.EncodeToString(h.Sum(nil)), n}, Wrap(e) @@ -199,7 +199,7 @@ func Read(ref ObjectRef, dst any) error { if e != nil { return Wrap(e) } - defer f.Close() + defer func() { _ = f.Close() }() b, e := io.ReadAll(io.LimitReader(f, (4<<20)+1)) if e != nil { return Wrap(e) diff --git a/pkg/snapshot/state/repository.go b/pkg/snapshot/state/repository.go index 8f5348d1dc..7505a24986 100644 --- a/pkg/snapshot/state/repository.go +++ b/pkg/snapshot/state/repository.go @@ -40,7 +40,7 @@ func (b *Repository) Bind(ctx context.Context, id common.ChangeFeedID, epoch uin func (b *Repository) save(ctx context.Context, id common.ChangeFeedID, epoch uint64, next *protocol.State, previous *string) error { infoKey := etcd.GetEtcdKeyChangeFeedInfo(b.Client.GetClusterID(), id.DisplayName) statusKey := etcd.GetEtcdKeyJob(b.Client.GetClusterID(), id.DisplayName) - for retry := 0; retry < 20; retry++ { + for range 20 { ir, e := b.Client.GetEtcdClient().Get(ctx, infoKey) if e != nil { return protocol.Wrap(e) diff --git a/pkg/snapshot/store/local.go b/pkg/snapshot/store/local.go index 1159e88a49..c20d4a62f3 100644 --- a/pkg/snapshot/store/local.go +++ b/pkg/snapshot/store/local.go @@ -50,11 +50,11 @@ func (s Local) CAS(key, expected string, value any) (bool, error) { if e != nil { return false, protocol.Wrap(e) } - defer lock.Close() + defer func() { _ = lock.Close() }() if e = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); e != nil { return false, protocol.Wrap(e) } - defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + defer func() { _ = syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) }() old, e := os.ReadFile(p) if e != nil && !os.IsNotExist(e) { return false, protocol.Wrap(e) @@ -74,8 +74,8 @@ func (s Local) CAS(key, expected string, value any) (bool, error) { if e != nil { return false, protocol.Wrap(e) } - defer os.Remove(f.Name()) - defer f.Close() + defer func() { _ = os.Remove(f.Name()) }() + defer func() { _ = f.Close() }() if _, e = f.Write(b); e != nil { return false, protocol.Wrap(e) } @@ -92,7 +92,7 @@ func (s Local) CAS(key, expected string, value any) (bool, error) { if e != nil { return false, protocol.Wrap(e) } - defer dir.Close() + defer func() { _ = dir.Close() }() return true, protocol.Wrap(dir.Sync()) } diff --git a/pkg/snapshot/store/store_test.go b/pkg/snapshot/store/store_test.go index dfebb6a2ce..c9f79dfaa6 100644 --- a/pkg/snapshot/store/store_test.go +++ b/pkg/snapshot/store/store_test.go @@ -15,10 +15,8 @@ func TestCASAndTaskRecovery(t *testing.T) { require.NoError(t, e) require.True(t, ok) var wg sync.WaitGroup - for i := 0; i < 16; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range 16 { + wg.Go(func() { for { var n int v, e := s.Read("counter", &n) @@ -35,7 +33,7 @@ func TestCASAndTaskRecovery(t *testing.T) { return } } - }() + }) } wg.Wait() var n int diff --git a/pkg/snapshot/store/tasks.go b/pkg/snapshot/store/tasks.go index d88525b308..99382ae616 100644 --- a/pkg/snapshot/store/tasks.go +++ b/pkg/snapshot/store/tasks.go @@ -62,7 +62,7 @@ func (t Tasks) Init() error { } func (t Tasks) edit(index int, fn func(*Page) error, adopt bool) error { - for retry := 0; retry < 20; retry++ { + for range 20 { var p Page v, e := t.Objects.Read(t.key(index), &p) if e != nil { diff --git a/pkg/snapshot/writer.go b/pkg/snapshot/writer.go index db6a8b69ad..098f4bcd6b 100644 --- a/pkg/snapshot/writer.go +++ b/pkg/snapshot/writer.go @@ -364,8 +364,11 @@ func newWriter( for _, output := range outputs { group.Go(func() error { err := output.Run(runCtx) - if runCtx.Err() != nil { + // An intentional shutdown cancels the callback loop after range ACKs. + select { + case <-runCtx.Done(): return nil + default: } if err == nil { return protocol.Invalid("snapshot output stopped unexpectedly") @@ -386,17 +389,17 @@ func NewWriter(ctx context.Context, sk sink.Sink, cfg *protocol.Config, epoch ui return newWriter(ctx, []snapshotOutput{storageOutput{sk}}, cfg, epoch, stats) } -func (w *Writer) Close() { - w.closeOnce.Do(func() { - w.writePathClosed.Store(true) - w.cancel() - <-w.sinkStopped - for _, output := range w.outputs { +func (e *Writer) Close() { + e.closeOnce.Do(func() { + e.writePathClosed.Store(true) + e.cancel() + <-e.sinkStopped + for _, output := range e.outputs { output.Close() } - if w.cleanup != nil { - w.cleanup() + if e.cleanup != nil { + e.cleanup() } }) } -func (w *Writer) AbortSnapshot(common.ChangeFeedID) { w.Close() } +func (e *Writer) AbortSnapshot(common.ChangeFeedID) { e.Close() } diff --git a/tests/integration_tests/native_snapshot/verify/main.go b/tests/integration_tests/native_snapshot/verify/main.go index f3217fcea0..26eee1068d 100644 --- a/tests/integration_tests/native_snapshot/verify/main.go +++ b/tests/integration_tests/native_snapshot/verify/main.go @@ -102,7 +102,7 @@ func main() { if err != nil { log.Fatal(err) } - defer client.Close() + defer func() { _ = client.Close() }() partitions, err := client.Partitions(*topic) if err != nil || len(partitions) != 1 { log.Fatalf("expected one partition: %v %v", partitions, err) @@ -118,12 +118,12 @@ func main() { if err != nil { log.Fatal(err) } - defer consumer.Close() + defer func() { _ = consumer.Close() }() pc, err := consumer.ConsumePartition(*topic, 0, sarama.OffsetOldest) if err != nil { log.Fatal(err) } - defer pc.Close() + defer func() { _ = pc.Close() }() rows := map[int64]map[string]any{} seen := map[string]int64{} snapshotRows := 0 @@ -240,7 +240,7 @@ func main() { if err != nil { log.Fatal(err) } - defer f.Close() + defer func() { _ = f.Close() }() enc := json.NewEncoder(f) enc.SetIndent("", " ") if err = enc.Encode(result); err != nil { From 99a46f7d28a50c80783236e8e1034b6cb16c466c Mon Sep 17 00:00:00 2001 From: dongmen <414110582@qq.com> Date: Fri, 4 Dec 2026 12:06:22 +0800 Subject: [PATCH 17/17] snapshot: preserve storage output from concurrent ranges Use a private snapshot sink configuration to include dispatcher IDs in storage filenames and indexes. Preserve the incremental configuration. Cover concurrent ranges, replay and a later incremental write with the real storage sink. Verify 20M snapshot rows and 10 incremental rows in a 100GB Cloud NG run on a dedicated 8 vCPU / 16 GiB CDC node. --- pkg/snapshot/service.go | 8 +- pkg/snapshot/storage_output.go | 28 ++++ pkg/snapshot/storage_output_test.go | 224 ++++++++++++++++++++++++++++ 3 files changed, 253 insertions(+), 7 deletions(-) create mode 100644 pkg/snapshot/storage_output.go create mode 100644 pkg/snapshot/storage_output_test.go diff --git a/pkg/snapshot/service.go b/pkg/snapshot/service.go index ab5ef0f500..a0383001cc 100644 --- a/pkg/snapshot/service.go +++ b/pkg/snapshot/service.go @@ -11,7 +11,6 @@ import ( "time" "github.com/google/uuid" - "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/pkg/common" appcontext "github.com/pingcap/ticdc/pkg/common/context" "github.com/pingcap/ticdc/pkg/config" @@ -348,12 +347,7 @@ func (s *Service) execute(ctx context.Context, req request) error { if scheme == config.KafkaScheme || scheme == config.KafkaSSLScheme { writer, err = newKafkaWriter(ctx, cfg, uri, gate, statistics) } else { - var sk sink.Sink - sk, err = sink.New(ctx, cfg, cfg.ChangefeedID, req.Keyspace) - if err == nil { - sk.SetWriteGate(gate) - writer = NewWriter(ctx, sk, cfg.Snapshot, cfg.Epoch, statistics) - } + writer, err = newStorageWriter(ctx, cfg, req.Keyspace, gate, statistics) } if err != nil { statistics.Error("overall") diff --git a/pkg/snapshot/storage_output.go b/pkg/snapshot/storage_output.go new file mode 100644 index 0000000000..2f93381568 --- /dev/null +++ b/pkg/snapshot/storage_output.go @@ -0,0 +1,28 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "context" + + "github.com/pingcap/ticdc/downstreamadapter/sink" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/metrics" + "github.com/pingcap/ticdc/pkg/writelease" +) + +func newStorageWriter( + ctx context.Context, cfg *config.ChangefeedConfig, keyspaceID uint32, + gate *writelease.Gate, statistics *metrics.SnapshotStatistics, +) (*Writer, error) { + snapshotSinkCfg := *cfg + // Concurrent ranges and retries use independent dispatcher IDs. Include those + // IDs in storage filenames so their successful writes cannot overwrite each + // other, without changing the configuration used by incremental replication. + snapshotSinkCfg.EnableTableAcrossNodes = true + sk, err := sink.New(ctx, &snapshotSinkCfg, cfg.ChangefeedID, keyspaceID) + if err != nil { + return nil, err + } + sk.SetWriteGate(gate) + return NewWriter(ctx, sk, cfg.Snapshot, cfg.Epoch, statistics), nil +} diff --git a/pkg/snapshot/storage_output_test.go b/pkg/snapshot/storage_output_test.go new file mode 100644 index 0000000000..7ecccb12c9 --- /dev/null +++ b/pkg/snapshot/storage_output_test.go @@ -0,0 +1,224 @@ +// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. +package snapshot + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/pingcap/ticdc/downstreamadapter/sink" + "github.com/pingcap/ticdc/pkg/common" + appcontext "github.com/pingcap/ticdc/pkg/common/context" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/pdutil" + "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" + "github.com/pingcap/ticdc/pkg/snapshot/protocol" + "github.com/pingcap/ticdc/pkg/snapshot/store" + "github.com/pingcap/ticdc/pkg/util" + "github.com/stretchr/testify/require" + "golang.org/x/sync/errgroup" +) + +func TestStorageSnapshotConcurrentRangesAndReplay(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + job := helper.DDL2Job("create table test.snapshot_storage (id int primary key, v varchar(50))") + table := helper.GetTableInfo(job) + appcontext.SetService(appcontext.DefaultPDClock, pdutil.NewClock4Test()) + + objects := store.Local{Root: t.TempDir()} + schema, err := table.Marshal() + require.NoError(t, err) + spec := protocol.Spec{JobID: "storage", SnapshotID: "storage", SnapshotTS: table.GetUpdateTS()} + spec.SchemaRef, err = objects.Put("schema.json", bootstrap.SchemaBundle{ + SnapshotTS: spec.SnapshotTS, Tables: []bootstrap.Schema{{TableID: table.TableName.TableID, Data: schema}}, + }) + require.NoError(t, err) + plan := protocol.ObjectRef{Digest: "storage-plan"} + const rangeCount, rowsPerRange = 8, 16 + exports := make([]protocol.Export, rangeCount) + for i := range exports { + values := make([]string, rowsPerRange) + for j := range values { + id := i*rowsPerRange + j + 1 + values[j] = fmt.Sprintf("insert into test.snapshot_storage values(%d,'value-%d')", id, id) + } + raw := helper.DML2RawKv(table.TableName.TableID, spec.SnapshotTS, + values...) + require.Len(t, raw, rowsPerRange) + exports[i] = storageTestExport(t, objects.Root, spec, plan, table.TableName.TableID, i, raw) + } + + dir := t.TempDir() + sinkConfig := config.GetDefaultReplicaConfig().Sink + sinkConfig.Protocol = util.AddressOf("canal-json") + sinkConfig.DateSeparator = util.AddressOf(config.DateSeparatorNone) + sinkConfig.CloudStorageConfig = &config.CloudStorageConfig{SpoolBaseDir: util.AddressOf(t.TempDir())} + cfg := &config.ChangefeedConfig{ + ChangefeedID: common.NewChangeFeedIDWithName("snapshot-storage", common.DefaultKeyspaceName), + SinkURI: "file://" + filepath.ToSlash(dir) + "?flush-interval=100ms&worker-count=4", + SinkConfig: sinkConfig, CaseSensitive: true, Epoch: 7, + Snapshot: &protocol.Config{ApplyWorkers: 4}, + // The caller's incremental scheduler stays in single-dispatcher mode. + EnableTableAcrossNodes: false, + } + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + w, err := newStorageWriter(ctx, cfg, 0, nil, nil) + require.NoError(t, err) + defer w.Close() + require.False(t, cfg.EnableTableAcrossNodes) + group, runCtx := errgroup.WithContext(ctx) + for _, ex := range exports { + group.Go(func() error { + n, err := w.ApplySnapshot(runCtx, cfg.ChangefeedID, cfg.Epoch, spec, plan, ex) + if err == nil && n != rowsPerRange { + return fmt.Errorf("unexpected range row count %d", n) + } + return err + }) + } + require.NoError(t, group.Wait()) + // A replay gets a fresh dispatcher namespace, retaining both copies. + n, err := w.ApplySnapshot(ctx, cfg.ChangefeedID, cfg.Epoch, spec, plan, exports[0]) + require.NoError(t, err) + require.EqualValues(t, rowsPerRange, n) + require.NoError(t, w.DrainSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch)) + + counts, files := readStorageTestRows(t, dir) + for id := 1; id <= rangeCount*rowsPerRange; id++ { + want := 1 + if id <= rowsPerRange { + want = 2 + } + require.Equal(t, want, counts[id], "row %d must survive concurrent ranges and replay", id) + } + require.NotEmpty(t, files) + for _, name := range files { + require.True(t, strings.HasPrefix(name, "CDC_"), "snapshot file must have a dispatcher namespace: %s", name) + } + + // Reuse the unmodified configuration for ordinary incremental output. + sk, err := sink.New(ctx, cfg, cfg.ChangefeedID, 0) + require.NoError(t, err) + defer sk.Close() + sinkCtx, stopSink := context.WithCancel(ctx) + defer stopSink() + done := make(chan error, 1) + go func() { done <- sk.Run(sinkCtx) }() + event := helper.DML2Event("test", "snapshot_storage", + fmt.Sprintf("insert into test.snapshot_storage values(%d,'value-%d')", rangeCount*rowsPerRange+1, rangeCount*rowsPerRange+1)) + event.TableInfoVersion = spec.SnapshotTS + acked := make(chan struct{}, 1) + event.AddPostFlushFunc(func() { acked <- struct{}{} }) + sk.AddDMLEvent(event) + select { + case <-acked: + case <-ctx.Done(): + t.Fatal("incremental row was not acknowledged") + } + stopSink() + <-done + counts, files = readStorageTestRows(t, dir) + require.Len(t, counts, rangeCount*rowsPerRange+1) + require.Equal(t, 1, counts[rangeCount*rowsPerRange+1]) + legacyFile := false + for _, name := range files { + legacyFile = legacyFile || !strings.HasPrefix(name, "CDC_") + } + require.True(t, legacyFile, "incremental sink must keep its original filename mode") + require.False(t, cfg.EnableTableAcrossNodes) +} + +func storageTestExport( + t *testing.T, dir string, spec protocol.Spec, plan protocol.ObjectRef, tableID int64, index int, raw []*common.RawKVEntry, +) protocol.Export { + t.Helper() + span := protocol.Span{ + RangeID: fmt.Sprintf("range-%d", index), TableID: tableID, + Start: raw[0].Key, End: append(bytes.Clone(raw[len(raw)-1].Key), 0), + } + header := protocol.Header{ + Version: 1, Compression: "none", JobID: spec.JobID, SnapshotID: spec.SnapshotID, + SnapshotTS: spec.SnapshotTS, PlanDigest: plan.Digest, RangeID: span.RangeID, AttemptID: "first", TableID: tableID, + } + var file, block bytes.Buffer + u32 := func(b *bytes.Buffer, n int) { require.NoError(t, binary.Write(b, binary.LittleEndian, uint32(n))) } + metadata := func(v any) []byte { b, err := json.Marshal(v); require.NoError(t, err); return b } + file.WriteString("SNAPKV01") + h := metadata(header) + u32(&file, len(h)) + file.Write(h) + var size uint64 + for _, kv := range raw { + u32(&block, len(kv.Key)) + u32(&block, len(kv.Value)) + block.Write(kv.Key) + block.Write(kv.Value) + size += uint64(len(kv.Key) + len(kv.Value)) + } + u32(&file, block.Len()) + u32(&file, len(raw)) + file.Write(block.Bytes()) + footer := metadata(protocol.Footer{Blocks: 1, KVCount: uint64(len(raw)), LogicalBytes: size, First: raw[0].Key, Last: raw[len(raw)-1].Key}) + u32(&file, 0) + u32(&file, len(footer)) + file.Write(footer) + file.WriteString("SNAPEND1") + path := filepath.Join(dir, span.RangeID+".skv") + require.NoError(t, os.WriteFile(path, file.Bytes(), 0o600)) + ref, err := protocol.Ref(path) + require.NoError(t, err) + return protocol.Export{Range: span, AttemptID: header.AttemptID, KVCount: uint64(len(raw)), Chunks: []protocol.Chunk{{ + ObjectRef: ref, KVCount: uint64(len(raw)), LogicalBytes: size, First: raw[0].Key, Last: raw[len(raw)-1].Key, + }}} +} + +func readStorageTestRows(t *testing.T, dir string) (map[int]int, []string) { + t.Helper() + counts := make(map[int]int) + var files []string + err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error { + require.NoError(t, err) + if entry.IsDir() || !strings.HasPrefix(entry.Name(), "CDC") || !strings.HasSuffix(entry.Name(), ".json") { + return nil + } + files = append(files, entry.Name()) + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + decoder := json.NewDecoder(f) + for { + var event struct { + Type string `json:"type"` + Data []map[string]string `json:"data"` + } + err := decoder.Decode(&event) + if err == io.EOF { + break + } + require.NoError(t, err) + require.Equal(t, "INSERT", event.Type) + for _, row := range event.Data { + id, err := strconv.Atoi(row["id"]) + require.NoError(t, err) + require.Equal(t, fmt.Sprintf("value-%d", id), row["v"]) + counts[id]++ + } + } + return nil + }) + require.NoError(t, err) + return counts, files +}