Skip to content

fix(cdc): accelerate bounded initial snapshots - #27939

Merged
XuPeng-SH merged 45 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-27863-cdc-snapshot-scheduling
Sep 6, 2026
Merged

XuPeng-SH merged 45 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-27863-cdc-snapshot-scheduling

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes

Fixes #27863

Root cause

The incident has two independent resource boundaries: CN-side retained source batches and target-side transaction work. The old fixed two-batch admission path serialized wide/slow tables behind the same slots, so a TPCC initial snapshot could spend more than 21 minutes waiting for a batch permit. Simply making the target snapshot one transaction removes retry ambiguity, but creates an unbounded target transaction and silently defeats the public/default split behavior.

The systemic review found these additional correctness and lifecycle gaps in earlier revisions:

  1. Multiple unknown-size batches could be admitted from one stale estimate, oversubscribing CN memory.
  2. Partial target commits could retry from a newer source snapshot. REPLACE cannot remove a row deleted or re-keyed between the two snapshots.
  3. Task creation time was used as a source epoch even for wildcard/database tables discovered much later.
  4. A stable epoch was loaded only while the watermark was empty. After restart, a non-empty pre-epoch watermark could lose generation/recreation protection.
  5. The epoch candidate was persisted before applying EndTs; a completed bounded task could therefore look permanently incomplete after restart.
  6. Old in-process pipelines could read a mutable, newer Resume/Restart claim and act as the replacement generation.
  7. A taskservice check alone could not serialize target SQL already in flight, while holding a target advisory lock for the entire pipeline could block takeover forever when the old owner was idle or partitioned.
  8. An old CN could pass its claim check, stall in watermark SQL, and later overwrite a newer owner's durable watermark.
  9. Empty polling rounds synchronously checked taskservice per table, creating work proportional to table_count / 200ms.
  10. Error cleanup could wrap a lone moerr and change its concrete identity; commit-error and scanner-cleanup paths also had incomplete/overly coupled cleanup behavior.

Implemented protocol and invariants

  • New split tasks use the internal stable-epoch-v1 capability marker and the distinct TaskCode_InitCdcStableEpoch. Legacy CNs cannot claim them; unmarked tasks retain the atomic compatibility path.
  • Persist one immutable source epoch per logical table and source table ID in mo_catalog.mo_cdc_snapshot before any partial target commit. Reload it on every stable pipeline start, including restart with a non-empty watermark.
  • Cap the persisted epoch by EndTs. A missing epoch beside a non-empty stable watermark fails closed instead of guessing. A retired source table ID plus an incomplete current generation resets the target under ownership serialization.
  • Intermediate target groups contain at most eight engine batches and rotate before crossing 512 MiB of measured allocations. Intermediate commits never advance the watermark; only complete snapshot success publishes the epoch. One indivisible engine batch may itself exceed 512 MiB.
  • Retry reads the same epoch and uses idempotent REPLACE; source changes after that epoch are applied by the incremental interval (S, next].
  • One CN-wide FIFO limiter admits initial-snapshot batches in [1,8] from cgroup/host available memory, a learned batch estimate, and a one-quarter headroom target. Only one admitted batch may be unobserved. Memory discovery failure falls back to concurrency 2.
  • Each daemon Start/Resume/Restart generation publishes one immutable OwnerFence. Existing pipelines retain their old token and cannot borrow a later generation's claim.
  • Target effects for the same account/task/table are serialized with a MySQL-compatible advisory lock. The lock covers initialization DDL or one transaction, is released after every successful intermediate/final commit and every error/rollback, and is reacquired before the next BEGIN. This serializes active effects without letting an idle old owner pin takeover.
  • The asynchronous watermark writer checks one shared fence per task generation per flush. Stable watermark upserts retain the durable maximum physical/logical timestamp, closing the cross-CN check-then-SQL window. Legacy updates remain separate because legacy stale-read recovery can intentionally rewind.
  • Empty rounds only enqueue a fenced watermark; they no longer synchronously heartbeat taskservice once per table.
  • Snapshot-epoch and watermark orphan cleanup use independent bounded contexts. Cleanup preserves a lone error's concrete identity and joins errors only when both the primary operation and cleanup fail.

The exact ownership graph, wait graph, failure matrix, alternatives, and validation contract are in docs/design/cdc_bounded_initial_snapshot.md. pkg/cdc/CDC_USER_GUIDE.md documents the user-visible behavior and recovery boundary.

Failure and recovery behavior

  • Read/SQL failure or crash before final completion: keep an empty/pre-epoch durable watermark and replay the same source epoch.
  • Ambiguous intermediate commit: replay is idempotent; no premature watermark is published.
  • Source DELETE or primary-key update during retry: replay the immutable snapshot, then apply its tail mutations.
  • Old owner actively writing target SQL: the replacement waits for the advisory lock, then revalidates its newer claim before acting.
  • Old owner idle, collecting, paused, or partitioned: it owns no target lock, so takeover is not indefinitely blocked.
  • Old watermark writer delayed across takeover: monotonic stable SQL cannot regress a newer durable watermark.
  • Persisted source history no longer readable: fail closed; an operator must verify/reset the target and recreate the task.
  • Source table drop/recreate: retain the retired epoch, select a new epoch for the new source table ID, and reset an incomplete new generation's target under the lock.

Performance impact

For N initial-snapshot engine batches, target commits are approximately ceil(N/8) unless the 512 MiB threshold creates smaller groups. This is fewer commits than the historical per-batch path while bounding target transaction state.

The tradeoffs are bounded and outside row-level hot loops:

  • one target advisory-lock acquire/release pair and claim checks per non-empty transaction group;
  • two catalog epoch reads per stable table pipeline startup;
  • at most two batched watermark statements in a mixed stable/legacy flush;
  • four small timestamp-component casts per conflicting stable watermark row;
  • SQL VALUES construction is linear via strings.Builder, avoiding quadratic string copying for large table counts.

No target connection remains pinned during pipeline idle/collection time. No-data taskservice checks are reduced from per-table/per-poll to one shared generation check per asynchronous flush.

The #27863 issue-scale run at e0c092ef38c1aa1afb21d46a075e148b1410e91c replicated ten TPCC tables (about 5.09 million rows) in 235 seconds. All source/target counts and final watermarks matched, bidirectional order/order-line consistency differences were 0/0, and peak mo-service RSS was 3,942,996 KiB. A failure-injection run committed 196,608 partial rows with an empty watermark, then applied a source DELETE and primary-key update; same-epoch replay plus catch-up converged to exact key equality.

Deliberate limits

  • The limiter bounds retained batch count using measured estimates; it cannot hard-cap one indivisible engine batch.
  • Intermediate snapshot groups are externally visible before the final watermark. Consumers must use task/watermark readiness, not target row presence, as completion evidence.
  • The advisory-lock identity serializes generations of the same CDC task/table. Two separately configured tasks targeting the same physical table remain unsupported and are outside this issue.
  • This PR does not add staging tables, a global target ownership service, or external-target PITR coordination.

Makefile / SCA decision

Earlier revisions changed Makefile/.golangci.yml to tune SCA memory/concurrency. That is unrelated to the CDC runtime protocol and duplicated the repository-wide portable SCA cache work now present on main. Those changes are removed: this PR has no Makefile or .golangci.yml diff against current main.

QA test plan

Startup-failure control recovery — 9ddd244

Fixes two related terminal-state gaps without adding a new persisted protocol or lifecycle state:

  1. After a factory has failed before Attach, a superseding control request must retain its durable row, not the dead local registration. Completion now retires that exact local claim, prevents old callbacks from reopening it, and stops indefinite heartbeat renewal. Normal lease expiry and reconciliation recover the request.
  2. An attached executor in Failed must still accept Pause. Failed→Pausing→Paused now drains residual readers, fences delayed callbacks, preserves watermark flushing, and handles duplicate Pause without repeated cleanup. The existing pause test no longer creates an unnecessary notification-draining goroutine.

Validation for 9ddd24400d82dfa79a46668cebe945d46ce8e43b:

  • Original eight review-only counterexamples now pass.
  • Committed TestDaemonPreAttachFailureRecoversControlRequests: legacy/stable × normal/fresh restart × PAUSE/CANCEL/Resume/Restart = 16 cases, asserting the complete durable row, no further renewal, old-callback rejection, real dispatcher recovery, and the replacement's heartbeat.
  • TestCdcTask_Pause: running/failed, one residual reader, Close/Wait exactly once, duplicate pause, and callback generation; state-machine coverage includes Failed→Pause→Resume→Running. Existing starting/already-paused/flush-failure-retry cases pass.
  • Full normal taskservice/frontend suites: 25.512s / 12.883s, coverage 90.8% / 65.3%.
  • Full race taskservice/frontend suites: 27.023s / 24.527s. Four focused taskservice lifecycle cases and the frontend Pause case each pass 100 race repetitions.
  • Scoped golangci-lint: 0 new issues; clean diff checks.
  • 55: both focused suites pass under race with matching changed production/test hashes. These are package fault-injection tests, not a new full-service/BVT or performance run. No service or persistent data was created. Evidence: /mnt/nvme/xupeng/mo-cdc-validation/pre-attach-fix-tests.log and failed-pause-fix-tests.log.

Recovery can still consume the existing lease timeout; this change deliberately does not clear a newer durable request or weaken takeover checks. No new per-row work, queue, worker, or extra lease-release SQL. Independent design approval was later recorded in review 5120209126; CI was not awaited for this historical correction.

Generation-owned completion correction — 0735225

Fixes the deterministic stale-startup completion counterexample from review 5117936681. This is implemented code, not just a design proposal.

  • Capture the originating (task_id, task_runner, last_run) once; deferred error/release writes cannot borrow a reused executor's newer token.
  • Use field-specific completion/status CAS operations. Preserve concurrent heartbeats and LastRun; reject superseding PAUSE/CANCEL/Resume/Restart or replacement owners.
  • Attach/factory admission validates the original registration and claim. Generation-checked runner completion owns post-Attach lifetime cleanup, preventing an old Start return from canceling a same-object replacement.
  • Bind timestamp predicates through the SQL driver, avoiding timezone drift with loc=Local. No new persisted schema/protocol or per-row work is added by this correction.

Validation on the production sources in commit 0735225be6d95736ef264b74bc31da6277cc15dd:

  • CGo wrapper normal full packages: ./pkg/taskservice ./pkg/frontend ./pkg/cnservice ./pkg/embed. Coverage: 90.3%, 65.3%, 64.1%, 84.9%, respectively; taskservice storage-adapter assertions also passed after their final addition.
  • Full taskservice and frontend race packages, plus six focused generation/lifecycle tests with 100 race repetitions each (separate invocations). Final taskservice race rerun passed after all test changes.
  • Real embedded SQL: exact microsecond claim round-trip, unchanged matched rows, stale/current completion writes, preserved heartbeat, bound timestamp predicates in update/status/query/delete.
  • Scoped golangci-lint 2.6.2 on the four affected packages, --new-from-rev=8db13a0953e9ffa17d73e65113fd76f8cfa8a394: 0 issues; git diff --check passed.
  • 55 NVMe: make -j12; SHA-256 of all eight changed production files matched local. Exact source/target equality for an existing 10-row task, new 3-row full snapshot, primary-key update/delete/insert, pause/resume, two task restarts, and unreachable sink rejection.
  • Restarted the same service/data on 55: six rows preserved, a seventh new row replicated, zero durable table errors. Owned test service stopped; about 120 GiB NVMe free.

QA reproduction: run the named cases in pkg/taskservice/daemon_completion_test.go, TestLifecyclePublishesClaimBeforeReplacementAndHeartbeat, TestCDCFactoryRejectsSupersededClaim, and TestDaemonClaimSQLRoundTrip via .agents/skills/mo-dev/scripts/mo-cgo-test. The counterexample tests use barriers and an entire-row/registration/heartbeat oracle, not timing sleeps.

55 evidence is retained at /mnt/nvme/xupeng/mo-cdc-validation/completion-{build,verify,after-restart}.log. This run used a single CN with MatrixOne source/sink in the same service; it does not establish live multi-CN ABA, external-MySQL, or throughput results. ABA is covered by deterministic injection. No claim that every possible scenario is proven, and no CI wait/green claim.

Earlier protocol validation

Historical validation at exact head 3e65096510d0ec556cf44b561f148421f0436bbb:

  • git diff --check and clean generated state after full make pb;
  • repository CGo test wrapper, -count=1: ./pkg/cdc ./pkg/frontend ./pkg/sql/compile;
  • repository CGo test wrapper, -count=1: ./pkg/taskservice ./pkg/cnservice ./pkg/bootstrap/versions/v4_0_6;
  • focused CDC race tests, -race -count=3, covering limiter, grouping, ownership, lock lifecycle, and watermark fencing;
  • focused frontend race tests, -race -count=5, covering immutable claim generations and restart classification;
  • deterministic regressions for eight-batch/512 MiB rotation, oversized single batch, exact-once permit release, cancellation, epoch concurrency/ambiguity, EndTs, table recreation, stale-history failure, intermediate/final watermark behavior, advisory-lock takeover, commit/rollback errors, and stable SQL parsing.

Review gate

Implementation and local validation are complete. The repository R3 design gate is traceably closed by XuPeng-SH in review 5120209126, which reviewed exact protocol/code head 7fa37b9d61; documentation-only commit 57055ace9c records that decision without changing the protocol.

Takeover checkpoint correction — 28e2c28

The final counterexample review found two recovery-protocol holes and one upgrade unhappy path:

  1. A previous owner could pass taskservice validation, stall in asynchronous watermark persistence, and later certify target rows changed by its replacement. Stable startup now claims a monotonic owner generation in the same mo_cdc_watermark row that checkpoints update. The guarded upsert advances (source_table_id, watermark) only when the buffered owner generation exactly matches the durable owner. The owner field itself is advanced only by startup admission, never by a checkpoint.
  2. When a stable epoch was missing beside non-empty current-generation progress, the first failed attempt inserted a new epoch and the second attempt trusted it. Admission now validates durable progress before INSERT; repeated retries remain rejected. Progress belonging to a retired source-table generation still follows the intended table-recreation reset path.
  3. A combined two-column catalog ALTER was not retry-safe after partial completion. source_table_id and owner_generation are separate v48 upgrade entries with independent existence checks.

Same-CN takeover also removes obsolete uncommitted/committing cache tiers and publishes the active local fence monotonically. A delayed old admission cannot overwrite a newer local generation. The protocol applies to all stable pipelines, including explicit StartTs and NoFull, without manufacturing snapshot-epoch rows for modes that do not have an initial snapshot.

Performance remains bounded: each stable table startup adds one short owner UPDATE and one ordered owner/progress read. Async checkpoints remain batched; the hot row path adds only integer owner/source comparisons and no snapshot-table JOIN, no per-row RPC, no sleep, and no larger retry timeout. Existing eight-batch/512 MiB transaction bounds and CN concurrency limits are unchanged.

Validation after rebasing latest main: full CGo-backed ./pkg/cdc ./pkg/frontend ./pkg/bootstrap/versions/v4_0_6; full ./pkg/cdc -race; and the three takeover/local-generation regressions under race for 100 repetitions. All passed. SQL parser coverage validates the guarded upsert. The deterministic target fake proves a replacement can commit a partial replay while the delayed old checkpoint is rejected and cannot poison local committed cache. This is package-level fault injection, not a new live multi-CN throughput run; current CI has been triggered by the push and was not awaited.

Restart deletion and source-wait correction — 5489186

This revision closes the two blocking schedules from review 5119413217 and records the secondary deadlock/performance constraints discovered while fixing them.

  1. Stable progress persistence is now update-only. Startup/claim remains responsible for creating and generation-claiming the progress row. If RESTART deletes that row after an old asynchronous writer passed its taskservice preflight, the delayed UPDATE affects zero rows instead of taking an unguarded INSERT branch and resurrecting retired progress.
  2. Stable snapshot batches are staged into the existing bounded group before target BEGIN/advisory-lock acquisition. The target effect interval now contains only owner validation, queued target writes, and commit; collector.Next and other source waits run without target ownership.
  3. Staging retains limiter permits, so a naive implementation could deadlock when several tables each held a partial group. A nonblocking admission path now respects both adaptive capacity and existing FIFO waiters. On backpressure the stream commits its partial group without advancing the watermark, releases its permits, then joins the normal FIFO.
  4. A full eight-batch group commits immediately, avoiding an attempt to wait for a ninth permit while all eight CN-wide permits are retained. The 512 MiB rotation and indivisible oversized-batch behavior remain unchanged.

Correctness and unhappy-path behavior:

  • RESTART deletion versus a prevalidated old checkpoint is deterministic: the deleted row stays absent, so replacement replay is not skipped.
  • An old owner blocked waiting for another source batch owns no target transaction or advisory lock; a replacement can acquire target ownership before that source wait ends.
  • Begin failure leaves staged batches with the processor for exact-once cleanup. Once outputs transfer to the sinker, commit/rollback retains the existing ownership and ambiguous-commit replay contract.
  • Intermediate commits still publish no watermark. Same-epoch REPLACE replay remains the recovery mechanism after partial or ambiguous commits.
  • Manual deletion of stable watermark rows is unsupported. A missing row cannot fabricate forward progress; the safe consequence is replay after restart.

Performance impact:

  • Normal uncongested groups remain up to eight batches / 512 MiB, preserving approximately ceil(N/8) commits rather than regressing to one commit per batch.
  • Staging adds no batch copy and remains inside the existing CN-wide eight-permit bound.
  • Each subsequent source admission performs one nonblocking capacity check in place of the ordinary blocking check. Only backpressure or FIFO fairness can produce a smaller transaction.
  • No source I/O is performed while the target lock is held, reducing takeover latency and target lock duration.

Validation on exact rebased head 5489186:

  • full CGo-backed ./pkg/cdc, normal and race;
  • scoped golangci-lint 2.6.2: 0 issues;
  • 100 race repetitions each for Restart-deleted checkpoint rejection, staged-group backpressure/permit release, nonblocking capacity plus FIFO fairness, and replacement target acquisition while the old source wait remains blocked;
  • MatrixOne MySQL parser coverage for the generated update-only stable checkpoint SQL;
  • clean range-diff: all previous 33 PR commits are patch-equivalent after rebase onto e7bb057; this correction is the only added commit.

This is deterministic package-level fault injection and lifecycle validation. It does not claim a new live multi-CN throughput run, and current CI triggered by the force-push was not awaited.### Batch ownership and observability correction — 1af13a0

The caller-level counterexamples from review 5119500649 exposed one common contract gap rather than two unrelated special cases:

  1. If rotating an already-staged snapshot group failed before the incoming batch was staged, the stream released only its permit. No component owned cleanup of that returned batch, so a failed attempt could retain a large source allocation.
  2. Successful split snapshots cleared ChangeData.InsertBatch during transfer, but stream progress read row counts afterwards. Snapshot rows/estimated bytes therefore became zero, and an asynchronous sink could in principle release the batch before post-call observation.

The correction makes ownership mechanically visible. A non-nil ChangeData batch remains caller-owned; every transfer to a snapshot group, sinker, or AtomicBatch immediately clears the source field. TableChangeStream calls ChangeData.Clean after every processing attempt, so it releases only untransferred batches/permits. This also closes the homologous TailDone path where append succeeds and target BEGIN fails, without double-cleaning processor-owned data. Metrics capture immutable row counts before transfer.

Unhappy-path and performance constraints:

  • pre-transfer rotation/BEGIN/sinker errors leave cleanup with the caller;
  • post-transfer commit/rollback errors leave cleanup with the processor or sink command;
  • empty or unexpected unconsumed data is reclaimed by the same caller rule;
  • no batch copy, row scan, new goroutine, lock, wait, retry, or log is added; the hot path keeps the existing RowCount reads and adds only constant-time nil/cleanup checks;
  • snapshot permit ownership remains coupled to its batch and is released exactly once.

Validation on exact head 1af13a008bf885e309683357fc5befc8ac74f1ae:

  • Both production-call-chain counterexamples pass: a three-row stable snapshot records three rows, and an injected pre-transfer rotation commit failure leaves the mpool at zero after sink-owned output cleanup.
  • Atomic snapshot transfer and TailDone append-before-BEGIN ownership assertions pass; full ./pkg/cdc normal tests pass.
  • Five focused ownership/error tests pass 100 race repetitions; full ./pkg/cdc race passes.
  • Existing source-wait/backpressure/takeover regressions pass 100 race repetitions.
  • Scoped golangci-lint 2.6.2 reports 0 issues; git diff --check passes.

The design document now states the field-level transfer rule and terminal owners so future paths can be reviewed mechanically. CI was triggered by the push and was not awaited or used as evidence for this correction.

Steady-state owner-fence hot-path correction — a722890

This correction closes the performance/design blocker in review 5119575801.

Root cause

The stable ownership protocol remains active after the initial snapshot. Every non-empty tail transaction called the same OwnerFence twice around GET_LOCK and twice around target COMMIT. That fence used HeartbeatDaemonTask, so each call performed BeginTx + UPDATE sys_daemon_task + Commit against one daemon row. At the default 200 ms interval this was approximately 20 task-row write transactions/second per continuously active table (about 2,000/s for 100 active tables), in addition to target lock SQL and DML. Snapshot throughput did not expose this tail amplification because large groups amortized the checks.

Fix and invariant

  • Taskservice now exposes an exact read-only validation for (task_id, task_runner, last_run). MySQL executes one autocommit indexed SELECT; it does not renew the lease, begin an explicit transaction, or mutate the daemon row. The task runner remains the only periodic heartbeat writer.
  • Every target effect performs exactly one fresh claim validation immediately after acquiring its task/table advisory lock. This is the linearization point: a replacement waits behind an old in-flight effect and then replays last; an old waiter waking after replacement fails before target DDL/DML.
  • Lock polling performs only local context/pause/cancel checks. It remains bounded to one-second polls without generating owner reads/writes while waiting.
  • Redundant per-DDL and pre/post-COMMIT validations are removed. The watermark still carries the immutable fence and is guarded by durable owner_generation SQL.
  • Same-CN Resume/Restart invalidates an old fence locally before any taskservice round trip. A delayed old post-commit watermark update is rejected against the active in-process fence, preventing ABA cache repopulation.

A local TTL/lease cache was considered and rejected: without a cross-CN clock-skew bound, an old CN could consider cached ownership valid, wake after the replacement releases the target lock, and write last. One fresh post-acquire read is the minimum safe cross-CN check without adding target-side generation metadata.

Unhappy paths and cleanup

  • stale owner after GET_LOCK: validation fails and releases the lock before target work;
  • pause/cancel/caller cancellation while waiting: exits within one lock poll, with zero remote validations;
  • validation timeout or taskservice backend error: classified as retryable/unknown, never as ownership loss, and lock/session cleanup still runs;
  • same-CN generation ABA: old fence fails locally and cannot reinsert buffered watermark state;
  • cross-CN takeover during target commit: target lock orders effects; durable watermark owner fencing rejects old progress;
  • ambiguous RELEASE_LOCK response: the physical driver connection is marked bad before close, so a possibly lock-owning session cannot return to the SQL pool;
  • commit/watermark/rollback/close failures retain existing idempotent release and replay behavior.

No goroutine, queue, retry loop, cache, or new hot-path logging was added.

Performance and validation

Per non-empty effect, synchronous claim work changes from four daemon-row write transactions to one read-only lookup: 75% fewer claim round trips and zero daemon-row writes from the CDC data path. At 100 continuously active tables and 200 ms intervals, the deterministic operation model changes from about 2,000 task-row writes/s to at most 500 exact reads/s. Empty rounds retain the existing shared asynchronous fence check.

  • Deterministic 100-effect regression: exactly 100 owner validations; SQL mocks prove validation has no Begin/Commit/UPDATE and refreshable storage adds no redundant Ping.
  • Focused stale-owner, wait-cancel, ambiguous-release, same-CN ABA, and takeover-order tests pass.
  • Full normal suites: pkg/cdc 13.208s, pkg/taskservice 26.800s, pkg/frontend 24.444s, pkg/cnservice 9.518s.
  • Full race suites: pkg/cdc 14.996s, pkg/taskservice 27.140s, pkg/frontend 34.886s.
  • Focused concurrency/unhappy set passes 100 race repetitions; the 100-effect call-rate test passes 3 race repetitions.
  • Scoped golangci-lint against the previous head reports 0 issues; git diff --check is clean.

These deterministic tests prove operation count, ownership ordering, and cleanup. No new live multi-CN tail-latency benchmark is claimed. Existing issue-scale snapshot evidence remains unchanged. CI for this pushed head is running and was not awaited.

Status-bound target setup and lifecycle closure (7fa37b9d61)

Root causes found in the counterexample review

  • The prior fence treated (task_id, task_runner, last_run) as both lease identity and effect authority. Pause/cancel/control states can deliberately retain that tuple, so the old Running executor could still pass the durable fence.
  • Sink setup detached from the table-callback lifecycle with context.Background(). Connection setup, advisory-lock acquisition, and target DDL therefore could outlive pause, cancel, restart, or CN shutdown.
  • GET_LOCK checked lifecycle only before the query. A control event racing a successful response could still authorize target effects. NULL and unexpected responses were treated like ordinary contention, allowing a rapid retry/query/log storm.
  • Failed Ping paths and create-time source/sink probe pools were not consistently closed.
  • A hard connection deadline without a typed retry classification would incorrectly persist a temporary network outage as a permanent table error.

Corrected authority and failure model

  • A claim captured as Running authorizes effects only while durable state is Running. ResumeRequested/RestartRequested first publish a new, strictly monotonic microsecond last_run; only that new generation accepts its matching request status and its later promotion to Running. Every other status combination is rejected. Status promotion updates the existing generation fence used by already-created pipelines; a new token installs a new fence and retires the old one.
  • The real callback context now flows through sink creation, connection/Ping, target-lock acquisition, and initialization DDL. Successful connection and lock results are checked again before publication/effect authority. Cancellation or a stale callback generation is cleanup, so it is not persisted as table failure metadata.
  • Each target connection attempt has an independent 10-second ceiling, keeps the existing maximum of three attempts, and uses cancellable retry backoff. Each GET_LOCK(..., 1) query has a 2-second ceiling independent of the configurable DML timeout.
  • Only lock result 0 means contention. NULL, unexpected values, query failure, and poll timeout exit after one query as typed retryable failures. Ambiguous acquisition still performs same-session best-effort release and discards the physical connection if release is ambiguous.
  • Runtime connect/checkout failures are typed retryable; URI/timeout configuration parsing and real DDL/schema errors remain permanent. Failed/cancelled DB handles and probe-only pools are closed.

Performance and operational risk

  • Steady-state effect admission still performs exactly one read-only taskservice lookup and one target lock acquisition per protected DDL/transaction. The lookup remains keyed by task_id; adding status predicates creates no scan, heartbeat write, or hot-row write amplification.
  • The change adds only bounded contexts/timers at connection and lock boundaries; it adds no goroutine, queue, cache, or unbounded retained state. NULL no longer loops, reducing failure-path query/log pressure.
  • The intentional tradeoff is that an endpoint unable to connect within 10 seconds, or answer one lock poll within 2 seconds, fails that setup attempt retryably instead of potentially hanging for the user DML timeout (including disabled timeout). The configured DML execution timeout itself is unchanged.
  • This does not make every error retryable: malformed configuration, unsupported schema, and deterministic target DDL errors still fail directly.

Review corrections and validation

  • A first-pass Running-only rule was rejected because Resume/Restart intentionally initializes the new generation before publishing Running. The final status matrix preserves that startup protocol without re-authorizing the old generation.
  • A first-pass hard connection timeout was incomplete because an untyped timeout would become permanent table metadata. Typed connection/lock failures now preserve bounded retry semantics.
  • CGo-aware full package tests passed for ./pkg/cdc, ./pkg/taskservice, ./pkg/frontend, ./pkg/sql/compile, ./pkg/vm/engine/test, and ./pkg/tests/ddl (the engine package completed in about 145 seconds).
  • Deterministic lifecycle/lock/claim tests passed under -race -count=20, including in-flight cancellation, success/cancel race, NULL/unexpected lock results, exact status-generation validation, connection cleanup, and retry classification. Scoped golangci-lint reports 0 issues.
  • Validation is local and deterministic at this commit; CI and a live external-MySQL multi-CN soak were not awaited. No timeout was lengthened to make tests pass.

R3 design approval closure (57055ace9c)

The independent design approval is now traceable in review 5120209126, performed against exact protocol/code head 7fa37b9d61. Commit 57055ace9c changes only the design-document status and records the decision; it does not change implementation, protocol, risk, or validation evidence.

Retry-state lifecycle correction (f43b3b80e8)

A deterministic counterexample found that terminal reader cleanup persisted a retryable diagnostic and then immediately deleted its in-memory retry metadata. Rebuilding the pipeline under the same daemon-task generation therefore restarted every persistent failure at retry_count=1, so it could retry forever and never cross MaxRetryCount; cleanup also removed the non-retryable gauge.

The correction separates progress retirement from diagnostic ownership. A genuine stream failure retires watermark progress but retains exactly one diagnostic record and its immutable task-generation fence. A replacement pipeline under the same fence advances the existing retry count; activation of a newer owner atomically clears the old record and gauge. Success, pause/cancel, task deletion, orphan cleanup for discovered progress, and explicit full cleanup retain their existing full-removal behavior. Queue-closed fallback follows the same ownership rule.

This adds no SQL, retry, wait, goroutine, scan, row-path branch, or history-proportional allocation. Retained state is bounded to one existing diagnostic record plus one fence pointer per failed table until same-generation recovery, owner replacement, or terminal task cleanup.

Validation on exact head and on a synthetic merge with latest origin/main (4f90107c8c): full CGo-backed ./pkg/cdc; full ./pkg/cdc -race; focused retry/owner/control/fallback regressions under -race -count=20; affected frontend claim/takeover/stable-snapshot tests; go vet ./pkg/cdc; and clean diff checks. The regression proves 1 -> 2 -> 3 -> 4/non-retryable, preserved gauge state, same-generation reuse, newer-owner reset, queue-closed fallback, and terminal full cleanup without timing sleeps. CI was triggered by the push and was not awaited.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found a blocking memory-safety issue in the adaptive admission path. The bounded-transaction and permit-lifecycle changes otherwise look coherent, and the focused committed tests plus race repetitions passed.

Comment thread pkg/cdc/initial_snapshot_limiter.go Resolved

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review at exact head 43c2f9128b2be7aa639c99f2590593d85f6ac543 found a second blocking correctness issue beyond the existing unknown-batch memory oversubscription finding. The new intermediate-commit recovery invariant is not safe for a mutable source: committed groups survive while the watermark stays empty, but a retry reconstructs a newer visible snapshot. REPLACE repairs rows that still exist; it cannot remove a key deleted or changed between attempts, so stale downstream rows can become permanent. The linked TPCC reproducer explicitly runs source writes during initial sync, so this is a reachable unhappy path. This change also introduces a memory resource controller and changes snapshot commit/recovery semantics; the required design closure should define byte reservation before allocation, scope across concurrent CDC tasks, partial-commit recovery for deletes/PK changes, and issue-scale performance/consistency acceptance evidence.

Comment thread pkg/cdc/reader_v2_txn_manager.go Resolved

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review at exact head 07c3383cb3f3aaf1c7c1e342c49e5e88b93d2b67. The earlier unknown-batch oversubscription and partial-commit retry findings are fixed, and the snapshot-permit ownership/cleanup chain is closed. One blocking transaction-design regression remains: the fix silently disables the public/default split-snapshot behavior and puts an unbounded initial snapshot into one target transaction. This needs a bounded, retry-safe protocol or explicit product/design closure with issue-scale endpoint evidence before approval. The PR body and user guide must also describe the implementation that actually ships.

Comment thread pkg/cdc/reader_v2_data_processor.go Outdated
}

// Begin transaction if needed (unless initSnapshotSplitTxn is set)
// Keep the complete initial snapshot in one target transaction. The sinker

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Do not replace the default split-snapshot path with an unbounded target transaction. InitSnapshotSplitTxn is still a public option whose default is true, and the user guide promises lower memory by splitting, but this branch now ignores the option and holds every snapshot batch in one transaction until NoMoreData. For the linked 1.77M-row/216-batch workload that means an arbitrarily long transaction with growing downstream transaction state/lock lifetime and no issue-scale timeout/resource evidence; it can trade the original batch-slot stall for transaction timeout, OOM, or commit amplification. The PR body also still claims bounded groups of eight even though that code was removed. Please define and implement a bounded retry-safe protocol (for example, a stable snapshot epoch/staging-and-publish or compensating cleanup), or explicitly deprecate the split contract with accepted design/resource limits and endpoint evidence for the issue workload. Add a regression that proves both retry equality and the chosen transaction bound.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at ae50751 on top of latest main. The default split path is bounded again, but retries are now anchored to a persisted stable source epoch. Intermediate target groups are limited to 8 engine batches or 512 MiB, commit without watermark, and only the final group advances watermark. A deterministic regression now covers partial commit -> failure/rollback -> same-epoch replay -> source DELETE/PK change through tail -> exact final target keys. New-task metadata also fences old CNs to the safe atomic path during rolling upgrades; unmarked legacy tasks conservatively remain atomic. The design/failure matrix is in docs/design/cdc_bounded_initial_snapshot.md, the user guide and PR body now match, CDC full UT plus targeted race and vet pass locally. Issue-scale TPCC remains the end-to-end performance acceptance run; I have not claimed a wall-clock result from UT.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review of exact head f7a7d689c2f2553767bd670d4abb4e912473eb08 against declared base 7764512a416ee21d9a54d7e446f38406f8b039b2, including the previously approved protocol range, the rebased-main overlap, and every hunk in the new generation-owned diagnostics commit.

REQUEST_CHANGES — one P1 liveness/retry-state blocker remains.

[P1] Preserve retry metadata when retiring a failed stream

The new cleanup order persists the terminal diagnostic at pkg/cdc/table_change_stream.go:739-746, then immediately calls RemoveCachedWM at line 754. That removal reaches removeWatermarkProgressLocked, which deletes errorMetadataCache at pkg/cdc/watermark_updater.go:2090 and removes the corresponding error gauges. The new stable diagnostic path deliberately skips the old progress/cache read, and no path reloads the persisted err_msg into errorMetadataCache before the replacement pipeline reports its next error.

The deterministic sequence is therefore:

  1. A stable stream exhausts its per-stream retries; cleanup persists R:1:... and caches retry count 1.
  2. The same cleanup removes the cache/fence and deletes that metadata.
  3. GetTableErrMsg reads durable R:1, ShouldRetry admits a replacement pipeline under the same live daemon generation.
  4. The same persistent retryable failure is built from a nil local metadata entry and is persisted as R:1 again, not R:2.

I reproduced this on the exact head using the real updater queue and RemoveCachedWM: the first and second terminal writes both logged retry-count: 1; an assertion that the second count was 2 failed deterministically. Consequently a persistent retryable source/sink failure never reaches MaxRetryCount + 1, never converts to non-retryable, and can rebuild/retry the pipeline indefinitely, repeating source/target work and logs. This also contradicts the existing pipeline contract at pkg/frontend/cdc_exector.go:3105-3108, which explicitly requires error state to accumulate 1→2→3→4 across rebuilds. For non-retryable terminal errors, the same ordering removes the just-published gauge until the periodic catalog scan restores it.

Please separate terminal progress/fence retirement from diagnostic retry-state ownership, or restore the prior durable error metadata before building the next stable diagnostic. Owner replacement and task deletion must still clear obsolete metadata. Add a full stream-retire/re-admit regression proving 1→2→3→non-retryable, plus gauge retention/cleanup coverage; updater-only repeated calls do not exercise this bug.

The owner-generation SQL fence itself is sound: stale-owner set/clear is update-only and cannot recreate a deleted row or overwrite a replacement generation. The v48 creation barriers are consistent across frontend/compiler entry points. Base drift overlaps only the independent ISCP SQL-builder changes, and the current-main merge tree is clean.

Audit Result
Q1 ownership Durable diagnostics are generation-fenced, but terminal cleanup currently destroys retry-state ownership needed by the next pipeline.
Q2 termination New claim/SQL waits remain bounded; no new lock, goroutine, or deadlock blocker found.
Q3 growth The reset-to-1 defect creates an unbounded pipeline retry/rebuild cycle under a persistent retryable failure.

Exact-head evidence: all newly added owner-diagnostic tests passed under -race -count=20; the counterexample above failed deterministically; git diff --check is clean. Current CI is fully green, but it does not cover the cross-pipeline retry sequence.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed latest head f43b3b8 from correctness, ownership/lifecycle, unhappy-path, bounded-state, observability, and performance angles.

The previous blocker is fixed: retry metadata now survives same-daemon-generation pipeline rebuilds, so a persistent retryable failure advances 1 -> 2 -> 3 -> 4/non-retryable instead of resetting to 1 forever. The retained task-generation fence preserves ownership: same-generation rebuilds reuse the state, while a newer owner atomically drops stale metadata and its gauge. Success, control shutdown, task deletion, and full cleanup still remove all state; the stopped-queue synchronous fallback has the same semantics.

No extra SQL, retry, wait, goroutine, scan, or hot-row work was added. State remains bounded to one existing diagnostic record and one fence pointer per failed table.

Validation passed on exact head and a synthetic merge with latest origin/main (4f90107): full CGo-backed pkg/cdc, full pkg/cdc race, focused race count=20 counterexamples including queue-closed fallback, affected frontend lifecycle tests, go vet, and diff checks. I found no remaining blocking issue.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST_CHANGES — exact head f43b3b80e8f780916ae9fd8cb2af8f12fdea91e2。

整体 stable-epoch / bounded grouping / limiter / owner-generation / target-lock 设计方向合理,原始 #27863 的批次阻塞问题基本覆盖;但以下两个生命周期反例仍阻塞合入。

1. [P1] taskservice 长故障恢复后,本 CN 可能抢占自己,导致 CDC 再停一个 lease 周期

startTasks 会把本机仍在运行、但 durable heartbeat 已过期的任务重新加入候选(daemon_task.go#L1128-L1170)。startDaemonTask 的 durable CAS 成功后,addDaemonTask 在发现相同 task ID 已存在时静默返回(daemon_task.go#L1412-L1460, daemon_task.go#L1554-L1562)。随后新 executor 在 Attach 的 owner/pointer 校验处失败(task_runner.go#L338-L352),旧 generation 又会因 heartbeat 的 generation 不匹配被清理,导致新 durable claim 没有本地执行者,只能等下一次 lease timeout 才能再次启动。

可复现调度:本地 stable CDC 正常运行 → taskservice 故障超过 heartbeat timeout → 恢复后让 poll 先于 heartbeat 执行。现有 TestStableCDCHeartbeatFailureRecoveryAndSupersession 只测试直接恢复 heartbeat,没有覆盖该 dispatcher 窗口。

请把 durable claim 与本地 map/generation 安装做成原子 admission:同一 CN 已有健康 local generation 时不得自抢占;或在 claim 成功后必须原子替换并正确停止旧 generation,不能静默丢弃新对象。补 deterministic regression,断言单 executor、单 routine、LastRun/pointer 一致且不额外等待 lease。

2. [P1] sinker consumer 退出后,producer 可能永久阻塞并泄漏 batch/permit/事务资源

mysqlSinker2.Run 会在 context/pause/cancel 时退出(sinker_v2.go#L363-L404),但 sendCommand 只等待 cmdCh receiver 或 closeCh,不观察 context、ActiveRoutine 或 consumer-done(sinker_v2.go#L954-L977)。

反例:consumer 因 parent context 取消先退出;producer 随后发送 snapshot batch / SendDummy。此时 closed == false 且 closeCh 未关闭,producer 永久卡在无缓冲 cmdCh <- cmd,reader 无法进入 cleanup,cleanup 也无法调用 sinker.Close(table_change_stream.go#L694-L787)。在本 PR 中,卡住的 command 还可能持有 CN-global snapshot permit、目标事务或 advisory lock。CDCTaskExecutor.Start 在 root context 取消时直接返回,没有保证关闭这些 raw reader/sinker goroutine(cdc_exector.go#L992-L999)。

管理面的 Pause/Cancel 通常会额外 Close(reader),但 parent-context/CN shutdown 路径没有这个保证。请统一生命周期所有权:要么 consumer 只由 Close 结束,要么所有 command send 都 context/consumer-done aware 并返回错误,由上层释放 batch/permit/事务/锁。补 Begin、batch、Commit、Dummy 各边界的 cancellation regression,并断言 bounded exit、permit 归零和 target lock 释放。

评审结论

精确 head 的 Linux UT、coverage、arm64 SCA、build、proxy/pessimistic BVT 均通过;本地已有 focused race tests 也通过,但没有覆盖以上两个调度顺序。PR 落后于当前 main,不过 synthetic merge clean,main 未修改上述关键文件,因此不会自然消除问题。

@XuPeng-SH

Copy link
Copy Markdown
Contributor

Systematic follow-up pushed in 620d91e5abe.

This closes both deterministic blockers from review 5123481765:

  1. Same-CN self-takeover after taskservice outage

    • Added a task-ID local admission reservation before the durable claim CAS.
    • A successful CAS atomically transfers that reservation into the local heartbeat/executor map; storage errors and all other returns release it.
    • Concurrent poll handlers now serialize before storage, and a stale heartbeat can no longer let the same CN advance its own durable generation while the preceding local execution is still registered.
    • Cross-CN takeover remains unchanged.
    • During package validation, the existing RestartRequested + empty runner case exposed a boundary regression. Dispatch now correctly prefers an existing local ActiveRoutine for this explicit restart request; only a task without a local owner takes the fresh-claim path.
  2. Sink consumer exits before producer send/cleanup

    • Added an explicit consumerDone lifecycle signal. Run publishes a terminal error before closing it.
    • Blocked and later senders wake, close transferred command/batch/permit ownership exactly once, and return.
    • The send path republishes a terminal error after ClearError(), covering the rollback path so dropped ROLLBACK/Dummy commands cannot be mistaken for success.
    • Existing producer error handling then releases target transaction/advisory-lock ownership during cleanup.

The design invariants, ownership/wait table, failure matrix, and performance model were updated. There is no new per-row/per-batch work, queue, timer, polling loop, or goroutine; local admission is claim-only, and consumerDone adds one select arm only on command send.

Validation on the pushed production code:

  • deterministic focused tests for stale-heartbeat recovery, concurrent admission, storage-error cleanup, and context/pause/cancel consumer exit: pass;
  • each new/changed concurrency case: -race -count=100, independently: pass;
  • existing unassigned-runner Restart case: -race -count=100: pass;
  • full normal packages: taskservice 26.384s, CDC 12.003s, frontend 25.778s: pass;
  • full race packages: taskservice 27.236s, CDC 14.028s, frontend 34.195s: pass;
  • scoped go vet for all three packages and git diff --check: pass.

No service/BVT or throughput claim is added because this follow-up changes lifecycle/admission behavior only, not SQL, wire protocol, row processing, or target statement semantics. Ready for independent re-review.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST_CHANGES — exact head 620d91e5abe72bc1a727313d5d21d2928a01a4f8.

The two previous P1 blockers are closed. The task-ID admission reservation prevents same-CN self-takeover without holding the map lock across storage or executor work, and every non-publish path releases the reservation. The consumerDone edge makes context/pause/cancel terminal for blocked and later senders; dropped commands close batch/permit ownership once and rollback cannot mistake a dropped recovery command for success. I found no additional correctness, deadlock, leak, unbounded-growth, or hot-path performance blocker in those changes.

[P2] Restore the repository error-construction contract so SCA can execute

The new lifecycle branches introduce fmt.Errorf at pkg/cdc/sinker_v2.go:400, :403, and :992. MatrixOne production code requires moerr; the current arm64 SCA stops in make err-check at the first occurrence with Use moerr instead, before the analyzers run. I reproduced the same failure locally on this exact head.

Please replace all three new constructors with the appropriate moerr constructor while preserving the pause/cancel classification strings, then rerun SCA. This is the only remaining requested change.

Evidence: the four focused taskservice regressions and the sinker context/pause/cancel regression passed -count=20; both focused sets passed independently with -race -count=20; full CGo-backed pkg/taskservice and pkg/cdc passed in 25.606s and 12.590s. The PR is three commits behind current main; synthetic merge is conflict-free and its only overlapping path is the unrelated information_schema.result. Remaining CI was not awaited.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head 92fce96938b499cb223e28dcaf25dc66a3e92d67.

The remaining SCA blocker is fixed. All three new sinker lifecycle errors now use package-level immutable moerr sentinels, preserving the existing pause/cancel classification strings while avoiding repeated error construction after consumer shutdown. No channel, state-machine, ownership, retry, or hot-path behavior changed.

Validation on the final revision: make err-check passes; the focused consumer-exit regression passed -count=20 and -race -count=20; full CGo-backed pkg/cdc passed in 12.366s; scoped golangci-lint 2.6.2 reported 0 issues; final diff and git diff --check are clean. No remaining blocker found. New CI was not awaited.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction to the SHA written in the preceding review body: the reviewed and pushed exact head is 92fce96938212ef9de85e6f63c267f42cb56c6fc. The abbreviated commit 92fce96938, validation evidence, and APPROVE decision are unchanged.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/enhancement kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: CDC 大表首次全量同步长期等待 initial snapshot batch slot

6 participants