// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. // 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 exporter import ( "context" "encoding/base64" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "sync" "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" "golang.org/x/sync/errgroup" ) 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 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. ReadMemoryQuota int64 DiskQuota int64 Workers int mu sync.Mutex running map[string]context.CancelFunc closed bool workers sync.WaitGroup } 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 { 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 *Runner) update(id string, fn func(*Job) error) error { for range 30 { 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 *Runner) 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 == "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 *Runner) 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() 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" j.Error = e.Error() } return nil }) } }() } // Close stops all local export processes and waits for their work to finish. func (s *Runner) Close() { s.mu.Lock() s.closed = true for _, cancel := range s.running { cancel() } s.mu.Unlock() s.workers.Wait() } 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) } 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 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) } 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)) } // #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 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 != nil && !errors.Is(cause, context.Canceled) { 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 { 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 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" if command == "plan" { name = "plan.json" } return protocol.Ref(filepath.Join(dir, name)) } 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 { if e := activeJob(j); e != nil { return e } j.Phase = "PLANNING" return nil }); e != nil { return e } 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 } 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) > 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 { 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 } 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) }); e != nil { return e } s.Statistics.Finish("export") return 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") } 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: } } return nil }) for range workers { group.Go(func() error { for r := range jobs { if e := ctx.Err(); e != nil { return protocol.Wrap(e) } if e := run(ctx, r); e != nil { return e } } return nil }) } return group.Wait() } 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" var ex protocol.Export v, e := s.Objects.Read(exportKey, &ex) if e != nil { return e } if v == "" { 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, }) }, func() { s.Statistics.Retry("materialize-range") }) 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 } published := false if e = s.update(id, func(j *Job) error { published = false if e := activeJob(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) 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), onRetry ...func()) (protocol.ObjectRef, error) { var err error for attempt := range 3 { 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 { 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: } } return protocol.ObjectRef{}, err } func (s *Runner) waitForSpace(ctx context.Context, id string) error { if s.MinFreeBytes == 0 && s.DiskQuota == 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) } 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 { 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): } } } // 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") } 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 *Runner) List(id, cursor string, limit int) (Page, error) { j, err := s.Status(id) if err != nil { return Page{}, err } 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) } } if offset < 0 || offset > len(j.Exports) { return Page{}, protocol.Invalid("cursor outside journal") } if limit < 1 || limit > 256 { limit = 64 } 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 }