// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. package snapshot import ( "bytes" "context" "sync" "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" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" ) 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 } // 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 *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 { return nil, protocol.Invalid("snapshot schema identity changed") } return r, nil } var cfg *protocol.Config if e.config != nil { cfg = e.config } if err := cfg.ValidateRuntime(); err != nil { return nil, err } var bundle bootstrap.SchemaBundle if err := protocol.Read(spec.SchemaRef, &bundle); err != nil { return nil, err } if bundle.SnapshotTS != spec.SnapshotTS { return nil, protocol.Invalid("schema timestamp mismatch") } tables := make(map[int64]*common.TableInfo, len(bundle.Tables)) for _, s := range bundle.Tables { 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} 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 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() if e.sinkStopped != nil { go func() { select { case <-e.sinkStopped: cancel() case <-ctx.Done(): } }() } 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.epoch != epoch || e.writePathClosed.Load() { return protocol.Invalid("snapshot writer fenced") } return nil } 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 } table := runtime.tables[ex.Range.TableID] if table == nil { return 0, protocol.Invalid("missing frozen table schema") } mounter := w.mounter acks := newSnapshotAcks() dispatcherID := common.NewDispatcherID() var rows uint64 var batch *commonEvent.DMLEvent submit := func() error { if batch == nil || batch.Length == 0 { return nil } charge := batch.ApproximateSize + int64(batch.Length)*snapshotRowOverhead if charge > w.limit { return protocol.Invalid("snapshot batch exceeds in-flight byte budget") } waitStarted := time.Now() 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 { 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() { 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)) })) if err := w.output.Write(ctx, batch); err != nil { return err } 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 := authorized(); err != nil { return err } 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) } raw := &common.RawKVEntry{Key: key, Value: value, CRTs: spec.SnapshotTS} 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") } 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 batch.Length >= snapshotBatchRows || batch.ApproximateSize >= snapshotBatchBytes { return submit() } return nil }) if err != nil { return rows, err } } 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 { return rows, protocol.Invalid("apply count mismatch") } return rows, nil } func (e *Writer) DrainSnapshot(ctx context.Context, _ common.ChangeFeedID, epoch uint64) error { if err := ctx.Err(); err != nil { return protocol.Wrap(err) } 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 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 a fixed worker pool and all output lifetimes for one execution. type Writer struct { ctx context.Context cancel context.CancelFunc outputs []snapshotOutput cleanup func() idle chan *applyWorker 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, outputs []snapshotOutput, cfg *protocol.Config, epoch uint64, stats *metrics.SnapshotStatistics, ) *Writer { ctx, cancel := context.WithCancel(ctx) w := &Writer{ ctx: ctx, cancel: cancel, outputs: outputs, config: cfg, epoch: epoch, sinkStopped: make(chan struct{}), idle: make(chan *applyWorker, cfg.ApplyConcurrency()), statistics: stats, } 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{}), } } group, runCtx := errgroup.WithContext(ctx) for _, output := range outputs { group.Go(func() error { err := output.Run(runCtx) // 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") } 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 (e *Writer) Close() { e.closeOnce.Do(func() { e.writePathClosed.Store(true) e.cancel() <-e.sinkStopped for _, output := range e.outputs { output.Close() } if e.cleanup != nil { e.cleanup() } }) } func (e *Writer) AbortSnapshot(common.ChangeFeedID) { e.Close() }