Skip to content

fix(cdc): prevent watermark recreation after drop - #27989

Merged
XuPeng-SH merged 41 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-27666-drop-cdc-watermark
Sep 4, 2026
Merged

XuPeng-SH merged 41 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-27666-drop-cdc-watermark

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented Sep 2, 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 #27666.

Root cause

DROP CDC TASK deletes the task row and its watermarks while the owner CN is stopped asynchronously. A watermark INSERT/UPSERT that was already running on that CN (or another CN during ownership change) could commit after the DELETE and recreate an orphan row. CN-local pause/deleted flags cannot establish a cluster-wide ordering.

There was also a subtler queue-ordering variant: safeQueue may coalesce a flush barrier and an error-watermark UPSERT into one callback batch. Completing the barrier after the normal-watermark phase but before the error phase lets DROP overtake the already-admitted UPSERT and recreate the orphan.

Design and implementation

  • Treat the (account_id, task_id) row in mo_catalog.mo_cdc_task as the durable write authority.
  • Every watermark INSERT/UPSERT locks that task row with SELECT ... FOR UPDATE in the same transaction as the write:
    • writer wins the lock: DROP waits, then deletes the task and all watermarks;
    • DROP wins the lock: the writer resumes, sees no task row, and inserts zero rows.
  • Complete a flush barrier only after every persistence phase in its full queue callback batch, including error-watermark UPSERTs.
  • Fence table-detector callback generations before Pause/Cancel/Restart, drain admitted callbacks, and retain aggregate reader-completion ownership across Paused/Failed/timeout paths.
  • Reject Resume/Restart while a previous Paused/Failed reader generation still owns work. A Restart callback-drain timeout fences that generation and restores local Failed, so durable RestartRequested retries remain admissible.
  • If Cancel's bounded callback wait expires, take one final reader snapshot after all old callbacks exit before releasing the local terminal tombstone.
  • Keep failed terminal deletion retryable. Taskservice restores CancelRequested only if both the terminal state and original runner still match, so an old failure cannot overwrite a new owner/state.
  • Remove the stateless stale-owner cleanup path: generic daemon cancellation is not equivalent to DROP, and its process-local tombstone had no safe release/CAS ownership contract.
  • Bound guarded flushes to 200 rows / a 256-KiB target, deduplicate task predicates, render deterministically, and use compact UNION ALL rows. Error metadata, including the max-retry prefix, is bounded to the catalog's 256-character contract.
  • Avoid waiter-goroutine chains on repeated cleanup retries when one side of the aggregate completion is already closed.
  • Reader shutdown atomically transfers only captured instances from the map to one aggregate completion owner; late successors remain visible, and repeated cleanup does not start duplicate waiters.
  • No catalog schema or wire-protocol change. See docs/design/20260904-cdc-watermark-drop-fence.md for invariants, ownership, rejected alternatives, and rolling-upgrade behavior.

Risk and compatibility

  • The normal CDC data path is unchanged; only periodic watermark persistence takes the task-row lock.
  • Statements are bounded and idempotent. Partial multi-batch success is safe to retry, preserving the newer cached watermark.
  • A deadlock/timeout aborts the statement and follows the existing retry/circuit-breaker path; it cannot bypass the task-row fence.
  • During a mixed-version rollout, an old binary can still issue an unguarded write. The existing orphan scanner remains the eventual-repair fallback until all writers are upgraded.
  • Local tombstones are reclaimed after the actual callback/reader completion proof; a genuinely stuck producer retains one fence rather than trading correctness for cleanup.

QA test plan

Validated on exact head 65f67c2891e2f0143f56c4000c914ec63248e94f, after merging main at fa829e5c505520e4bd429d283c78157781b4de72:

  • ./.agents/skills/mo-dev/scripts/mo-cgo-test ./pkg/cdc ./pkg/frontend -count=1
  • ./.agents/skills/mo-dev/scripts/mo-cgo-test ./pkg/tests/issues -run '^TestIssue27666CDCWatermarkWriteSerializesWithDrop$' -count=1
    • real two-CN embedded cluster;
    • forces both writer-first and DROP-first task-row lock orderings;
    • uses two compact derived rows and asserts final task count = 0 and watermark count = 0.
  • Focused callback/reader/updater unhappy paths passed under -race -count=20:
    • same-batch error-watermark writer versus flush barrier;
    • Paused/Failed recovery while an old reader still owns work;
    • Restart callback-drain timeout retryability;
    • reader published after Cancel's first snapshot.
    • reader published/replaced between shutdown snapshot and exact-instance cleanup.
  • Exact-head full pkg/cdc and pkg/frontend normal tests passed.
  • Exact-head full pkg/frontend race passed; full pkg/cdc race passed on the preceding semantic revision, and the final commits touch only frontend reader ownership plus its tests/design note.
  • The reader publication/detachment counterexample passed under -race -count=100.
  • golangci-lint 2.6.2 --new-from-rev=origin/main for pkg/cdc/... and pkg/frontend/...: 0 issues.
  • git diff --check: pass.

Performance benchmark on Apple M4 (BenchmarkCDCWatermarkUpdaterConstructGuardedBatch, 5,000 tables):

  • previous reviewed head: about 167 ms, 3.38 GB allocated, 913 KB SQL;
  • current batching implementation: 1.66-1.67 ms, 2.85 MB allocated, 25 batches, max statement about 16 KB, total SQL about 401 KB;
  • approximately 100x lower construction time, 1,188x lower allocation, and 56% less SQL text.

Follow-up: transaction race fixture failure protocol (2026-09-05)

Fixed review #27989 (review) in 5920aba39fb4d7cedfecae29f3b80bce9b903e0e.

Root cause / first-principles correction: callback readiness is not transaction completion. ExecTxn can fail before entering its callback; the old helper sent that error only to holderDone while the test waited indefinitely on holderReady. A context deadline does not unblock an unconditional channel receive. Duplicating this protocol in both ordering helpers duplicated the omission.

Fix and scope:

  • Both writer-first and DROP-first scenarios now share one race driver and test-only transaction owner. Positive readiness is separate from broadcast completion, which publishes the terminal error even when the callback never runs.
  • Readiness and completion waits observe the caller context. Assertions and cleanup can both join completion without consuming each other's result.
  • Register cancel/join cleanup before launching each transaction; catalog teardown is registered first and therefore runs after transaction cleanups. Abandoning a scenario or hitting FailNow no longer leaves a held transaction waiting only for normal-path release.
  • One 30-second finish budget covers holder and contender; cleanup uses independent bounded contexts and reports failure if cancellation cannot drain the executor. This does not pretend Go can forcibly terminate an executor that ignores cancellation.
  • All existing two-CN task-lock-waiter and final zero-task/zero-watermark assertions are preserved. No assertion weakening, sleeps, retries, additional cluster, production code, schema, or build-rule change.
  • Lightweight injected executors cover startup-without-callback failure, first/later SQL failure, commit failure, cancellation before readiness/while holding, expired waiter contexts, normal holder/contender completion, repeated joins, and transaction-before-fixture cleanup.

Final revision validation (macOS arm64, Go 1.26.4; matching native artifacts rebuilt with make -j8 cgo):

  • mo-cgo-test -json -count=1 -timeout=600s ./pkg/tests/issues: PASS, whole owning package 52.836 s. Both real two-CN orderings passed; the issue test took 0.18 s within the shared cluster.
  • mo-cgo-test -json -race -count=100 -timeout=120s -run '^TestCDCRaceTxn$' ./pkg/tests/issues: PASS, 100 named test completions. New lightweight scenarios measure below the test timer's 0.01 s resolution.
  • mo-cgo-test -json -race -count=1 -timeout=180s -run '^TestIssue27666CDCWatermarkWriteSerializesWithDrop$' ./pkg/tests/issues: PASS; first test measurement 12.55 s including lazy cluster startup.
  • Adaptive same-process race repetition: -race -count=2 of that exact two-CN test: PASS, 12.63 s then 0.14 s (N=floor(30/12.55)=2). Both repetitions retain both ordering scenarios and final catalog oracles.
  • Affected-package golangci-lint 2.6.2 --new-from-rev=65f67c2891e2: 0 issues; staged git diff --check: PASS.
  • Earlier production CDC/frontend/taskservice and BVT evidence is reused: this follow-up changes only the race-test fixture, its focused tests, and the design validation note. No additional mo-tester BVT is needed for a test-only synchronization contract.
Audit Closure
Q1 ownership Each test transaction owns one context and worker; cleanup cancels/joins before catalog teardown.
Q2 waits Readiness observes terminal error/cancellation; completion and cleanup are bounded.
Q3 bounds / performance Same two workers per race, fixed-size signals, no retry queues or production overhead.

Self-review: no remaining blocker found in the follow-up. Existing mixed-version rollout limitations of the production fence remain unchanged.

@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 →

@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 of exact head 86510c8 against base/merge-base c46d897. I traced DROP dispatch, executor cancellation, callback generation, reader shutdown, the shared watermark queue/caches, durable deletion, retry ownership, Q1-Q3, and exact-head CI. Substantive CI is green, but the cancellation/delete contract is not closed.

  1. [P1][liveness] Cancel can block forever before it reaches the cancellation path. At cdc_exector.go:1389-1396 it increments the generation and then takes callbackMu exclusively before cancelLifecycleContext, unregistering the detector, or closing readers. handleNewTablesForGeneration holds callbackMu.RLock for its whole callback (2239-2240), including engine/transaction work on context.Background and an unbounded reader.Wait at 2321-2326. Therefore an old callback blocked in any of those operations prevents DROP cancellation from delivering the signal that could make progress. The new test only proves that Cancel waits until a test manually releases RLock; it does not prove a termination edge. Fence admission first, deliver cancellation independently, and drain the old generation with a context-aware completion mechanism; do not hold the generation lock across blocking callback work.

  2. [P1][correctness] The terminal watermark fence is released even when a reader has not terminated, so this can recreate the exact orphan the PR is intended to eliminate. Cancel relies on stopAllReaders before the final DELETE (1440-1468), but stopAllReaders gives each reader only 10 seconds, logs and continues on timeout, and then deletes every reader reference (1563-1635). Cancel subsequently deletes the rows and defer-unmarks pausedTasks (1402-1404). A reader still blocked in sink/transaction I/O can finish later and call UpdateWatermarkOnly; after the unmark, 1140-1157 accepts the write and the shared cron recreates the durable row. Error-watermark jobs are not fenced by pausedTasks either. Keep the terminal generation fenced until every producer has actually exited, or make the updater enforce a durable/generation-aware task tombstone. Add a deterministic slow-reader case that crosses the shutdown timeout and proves no cache or durable write is admitted afterward.

  3. [P1][unhappy path] A failed final DELETE leaves an orphan with no retry owner. DeleteTaskWatermarks removes all in-memory state before executing the authoritative DELETE (watermark_updater.go:1305-1367). If that Exec fails, Cancel returns the error, but its unconditional defer still moves the local executor to Cancelled and removes the pause fence (cdc_exector.go:1414-1435). More importantly, taskservice marks the daemon task Canceled before invoking activeRoutine.Cancel, so the failed cleanup is not selected again from CancelRequested. This is a concrete delete failure -> durable orphan terminal state. Make durable deletion successful/retriable before publishing terminal cancellation, or transfer cleanup to a durable retry owner; test final-delete failure followed by retry/recovery and assert the watermark is eventually absent.

The 30-second cleanup context also does not currently bound ForceFlush: ForceFlush calls Job.WaitDone without selecting ctx.Done (watermark_updater.go:1272-1279), so queue/handler delay can exceed the advertised cancellation deadline. Please close this Q2 edge as part of the lifecycle fix.

This reverts commit b3db16c348ebeb336a31e713bcdfe408b1eb58e4.
This reverts commit d718c29d6259c12f4ff91b8cf8701e6a40407bd1.

@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.

Deep re-review of exact head 10719bba8be44b2a3cb4991fc98294593653a3ba against base/merge-base c46d897e9645b80178568ef0783dd8e99e527222. I read all 12 historical reviews, all 9 inline threads and their current resolved/outdated state, the PR conversation, the complete 11-file diff, and the full increment since my previous review at 044085b54185646d0bc76020d4a2c81f5700e97b. The new taskservice cleanup registration does provide a retry actor after owner loss, and the earlier queue barrier, local producer drain, DELETE-error propagation, and retry-ownership fixes remain intact. Two terminal-fence gaps still allow a watermark write after the final DELETE, so I am requesting changes.

Validation on this exact head: git diff --check; full go test for pkg/cdc, pkg/frontend, pkg/taskservice, pkg/cnservice, and pkg/lockservice; focused new cancellation/watermark/taskservice tests under -race; and go vet for all affected packages passed with the required CGO/thirdparties setup. Two review-only deterministic counterexamples failed as described inline and were removed afterward. Exact-head GitHub UT, coverage, SCA, compose, and standalone checks are green.

Comment thread pkg/frontend/cdc_exector.go Resolved
Comment thread pkg/frontend/cdc_exector.go Resolved

@iamlinjunhong iamlinjunhong 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.

审查基准:当前 head 10719bba8be44b2a3cb4991fc98294593653a3ba,PR merge-base c46d897e9645b80178568ef0783dd8e99e527222。已核对完整 11 文件 diff、DROP → Cancel → watermark updater → taskservice 接管调用链、所有历史 review threads/PR conversation,以及当前 28 个 check(均已结束、无失败)。我上轮提出的 P1 已阅读;PR conversation 和 review threads 中没有作者对其 P2/P3 的对应回复。本轮仍有两个可验证的 P1,因此请求修改。

  1. [P1][跨 CN DROP 正确性] 接管清理只围栏了接管 CN 自己的 updater,不能使旧 owner 的已准入持久化写失效。 pkg/frontend/cdc_exector.go:153-158 在接管 CN 上用该 CN 的 UUID 新建/取得 CDCWatermarkUpdater 并执行 DELETE;而 tombstone 和 persistMu 都是 updater 实例内的进程本地状态(pkg/cdc/watermark_updater.go:334-336)。触发序列:CN-A 的 writer 已在 execAddWM/批量更新中准入并停在 SQL 前后;其 heartbeat 过期后 CN-B 走此 cleanup,CN-B 的本地 tombstone、queue barrier 和 mutex 都无法观察或等待 CN-A 的 writer,DELETE 成功并将 daemon task 置为 Canceled;随后 CN-A 的 writer 完成并写回 watermark。此时没有可重试 owner,正好重新产生 DROP 要消除的 orphan。需要跨 CN 可见的租约/代际围栏,或在发布 Canceled 前证明旧 owner 的所有 writer 都已失效;请添加两个 updater/旧 writer 延迟的确定性接管回归。

  2. [P1][paused DROP 正确性] Pause 丢弃超时 reader 的 completion owner,后续 Cancel 会过早 ForgetTaskDeleted。 pkg/frontend/cdc_exector.go:1381 忽略 stopAllReaders 返回的 readersDone;该 helper 在 10 秒超时后仍删除 runningReaders(pkg/frontend/cdc_exector.go:1698-1704)。之后从 Paused 进入 Cancel 时 wasActive 为 false,readerShutdownCompletion() 仍为 nil(pkg/frontend/cdc_exector.go:1533-1545),于是 readersStopped 保持 true,成功 DELETE 后立即调用 ForgetTaskDeleted(pkg/frontend/cdc_exector.go:1575-1582)。MarkTaskDeleted 同时删除 pause 标记(pkg/cdc/watermark_updater.go:1479-1483),故此前因 Close/Wait 超时而仍存活的 reader 随后调用 UpdateWatermarkOnly 时不再被 pause 或 tombstone 拦截(pkg/cdc/watermark_updater.go:1214-1235),可将刚删除的行重新写入。请跨 Pause/Cancel(及重试)保存该 completion channel,并在它真正关闭前保留 tombstone;补充 paused + slow reader + DROP 的确定性回归。

@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 dff34d41a46a46c6d275ee13307cac2ab4ada52f against base/merge-base c46d897e9645b80178568ef0783dd8e99e527222. I re-read the complete 13-file diff, all historical reviews/threads, the 10719b..dff34d4 fix increment, and the DROP -> task takeover -> updater persistence ownership graph. The Pause completion fix is sound, and the latest commit updates the stale SQL-shape assertions, but the cross-CN fix is not a transactionally valid fence.

  1. [P1][DROP correctness] The guarded INSERT ... SELECT ... JOIN mo_cdc_task is only a snapshot predicate, not a serialization point with DROP. The production internal executor creates an ordinary autocommit session for each Exec, and the txn client defaults to RC/pessimistic. A plain source JOIN does not lock the task row; insert planning locks the watermark target key, not an unrelated source row. The concrete no-conflict schedule is: CN-A starts the first watermark INSERT for a newly detected table and reads/materializes the existing task row; the watermark row does not yet exist; DROP deletes mo_cdc_task and all watermark rows and commits; CN-A then inserts that previously materialized row and commits. DROP wrote the task row while CN-A wrote a previously absent watermark key, so there is no write-write conflict that must abort CN-A. The orphan is recreated after the authoritative DELETE. The same issue applies to update/error UPSERT when their target key is absent. See the inline comment for the required invariant.

  2. [P1][lifecycle] The permanent-table-error shutdown still loses completion ownership. failTaskForPermanentTableError calls stopAllReaders() at pkg/frontend/cdc_exector.go:2616 and discards its completion channel. That helper clears runningReaders even after its 10-second timeout. A later DROP from StateFailed has wasActive == false and no saved readerShutdownDone, so it can finish DELETE and immediately ForgetTaskDeleted while the old reader is still alive. Once that reader resumes, it is again admitted to watermark/cache work (and may still complete sink work) after terminal cancellation. Make stopAllReaders register completion centrally, or preserve it at every production caller, and add Failed + blocked reader + DROP coverage.

Validation and performance: git diff --check passes. Exact-head focused local UT could not start because the repository's macOS CGo wrapper correctly rejected an incompatible primary-worktree libmo.dylib; this is an environment precondition, not a code failure, and I did not wait for the newly queued CI. The updated tests only assert that generated text contains INNER JOIN; the mock parser does not model task-row visibility, locking, or the interleaving above. Add a deterministic two-session test where the writer observes the task, DROP commits, then the first watermark insert attempts to commit. Also measure the new hot path at representative table counts: every 3 seconds all uncommitted keys are rendered via repeated string concatenation into a scalar UNION ALL tree plus a catalog JOIN, with no batch bound from the 200-job queue; this can materially increase parse/plan time and statement size for large CDC tasks.

Q1 fails on the two producer/cleanup ownership edges above. Q2 is otherwise bounded by the existing callback, reader, queue, and SQL deadlines. Q3 remains conditional on retaining the tombstone until every producer completion is owned.

Comment thread pkg/cdc/sql_builder.go Resolved

@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.

Deep re-review of exact head 0233d70 against merge-base c46d897 and current main bf63172. I re-read all 15 historical reviews, every inline thread and PR comment, the full 13-file diff, and the complete increment since my prior review at 10719bb.

The two remaining blockers are closed. Every watermark INSERT/UPSERT now evaluates a task-row SELECT FOR UPDATE in the same autocommit transaction, so a producer that reaches the lock first commits before DROP deletes the task and watermarks, while a producer that loses the lock race retries/observes the missing task and emits no row. A review-only parser check accepted all three generated SQL forms, and a planner counterexample confirmed that INSERT ... SELECT preserves the nested source lock operator in addition to the normal target lock. The permanent-table-error path now also retains the timed-out reader completion channel; a deterministic blocked-reader counterexample confirmed that the completion owner remains available for a later DROP.

Validation on this exact head: git diff --check; clean merge-tree with current main; full go test for pkg/cdc, pkg/frontend, pkg/taskservice, pkg/cnservice, and pkg/lockservice; focused race tests for the new watermark deletion/fence, callback/reader cancellation, and stale-owner cleanup paths; and go vet for all affected packages passed with the required CGO/thirdparties setup. Generated guarded SQL also parsed successfully. The current SCA check failed during actions/checkout before analysis began, so it is infrastructure-only. 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.

Deep review on exact head 7c3757413eb3e3e2096ff37e55c0c3642933ac00.

The architectural direction is correct: the cross-CN invariant must be enforced by a durable task-row fence, and the guarded SELECT ... FOR UPDATE closes the previously reported plain-JOIN race. I am still requesting changes because the current implementation leaves production counterexamples open:

  1. [P1][performance/availability] Bound and de-amplify guarded watermark batches.
    constructBatchUpdateWMSQL / constructAddWMSQL / error update still build SQL with repeated string concatenation, and now append the same (account_id, task_id) task predicate once per table. cacheUncommitted is not bounded by the queue batch size, so a many-table CDC task can enter this path every 3 seconds. A review-only benchmark on this exact head measured:

    • 1,000 tables: guarded 7.26 ms / 139 MB allocated / 181 KB SQL vs legacy 3.69 ms / 58.6 MB / 54 KB.
    • 5,000 tables: guarded 167 ms / 3.38 GB allocated / 913 KB SQL vs legacy 65 ms / 1.43 GB / 278 KB.

    This is about 2.6x construction CPU, 2.4x allocation, and 3.3x statement size at 5,000 tables. It can create periodic GC/CPU spikes and oversized internal SQL. Please use a pre-sized builder, deduplicate predicates by (account_id, task_id), and enforce a bounded row/byte batch while preserving the task-row lock in every statement. Add a size/allocation benchmark or regression bound.

  2. [P1][lifecycle ownership] The stale-owner cleanup path leaks terminal tombstones and has no cleanup/CAS ownership contract.
    CDCTaskWatermarkCleanupFactory calls DeleteTaskWatermarks, which unconditionally stores the task in the process-global updater deletedTasks; only a local CDCTaskExecutor later calls ForgetTaskDeleted. The stateless cleanup path has no release owner, so every such cancellation leaves one entry for the CN lifetime. Also, cleanup runs before the conditional transition to Canceled; if the lease/status/owner changes and UpdateDaemonTaskStatus returns 0, the handler returns with the local tombstone still installed. This matters especially because generic daemon cancellation can leave mo_cdc_task present, unlike DROP CDC. Please make tombstone ownership explicit for stateless cleanup and close both success and CAS-miss/superseding-state paths without reopening the late-writer race. Add deterministic tests for repeated stale cleanup and cleanup-success-plus-terminal-CAS-miss.

  3. [P1][validation gap] The concurrency test does not exercise the implementation it claims to prove.
    TestCdcTaskCancelDrainsInFlightTableCallback manually holds callbackMu.RLock, but production callbacks now take callbackMu.Lock only for admission and are drained through callbackCount/callbackDone. The test can pass while the actual registration/drain protocol is broken. The durable fence is likewise verified only as SQL text; there is no committed two-session lock-order test showing that DROP/delete and a concurrent guarded write cannot leave a watermark behind. Please test the real callback admission/completion path and the real transaction ordering, including blocked reader/timeout and paused/failed task variants.

Non-blocking scope note: Makefile is not in the current base-to-head diff; it appeared only when comparing against an old base. The pkg/lockservice/service_test.go timeout change is in the effective diff but unrelated to CDC and should be split or explicitly justified.

Validation performed without waiting for CI: affected packages passed normally and under targeted -race; full pkg/cdc, pkg/frontend, pkg/taskservice, pkg/cnservice, and pkg/lockservice package tests passed; git diff --check passed. These green tests do not cover the counterexamples above.

@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 a62bfaf3613de320b93719992592d7c3cf4608c8 after merging current main 26d008dbd04ad40bdb1676dc8f6f1ee420eae0f6.

The prior blockers are closed:

  • Cross-CN correctness is serialized by a real task-row SELECT ... FOR UPDATE in the same transaction as every watermark INSERT/UPSERT. A two-CN embedded-cluster regression forces both writer-first and DROP-first orderings, observes the task-table waiter, and ends with zero task and watermark rows.
  • Guarded batching is deterministic and bounded; task predicates are deduplicated, rows are compact, partial success is idempotently retryable, and newer cached watermarks are preserved. The 5,000-table construction benchmark improved from roughly 167 ms / 3.38 GB / 913 KB SQL on the reviewed old head to 1.66-1.67 ms / 2.85 MB / 401 KB total SQL (25 batches, about 16 KB maximum statement).
  • Pause/Cancel now fence callback admission, drain the admitted generation, aggregate reader completion across Paused/Failed/retry paths, and rescan after a timed-out callback before releasing the tombstone. Deterministic tests cover a reader published after the first Cancel snapshot.
  • Failed cleanup restores CancelRequested only under both status and original-runner CAS. The unsafe stateless stale-owner cleanup and unrelated lockservice timeout change are absent from the effective diff.
  • Error metadata is bounded to the catalog contract, and no schema/wire change is introduced.

Exact-head validation: full pkg/cdc, pkg/frontend, and pkg/taskservice tests; real two-CN issue regression; focused unhappy-path/race cases at -race -count=10; affected-package golangci-lint 2.6.2 with 0 issues; and git diff --check. I found no remaining blocking correctness, liveness, performance, compatibility, or cleanup-ownership 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.

Deep re-review of exact head 65f67c2891e2f0143f56c4000c914ec63248e94f against base fa829e5c505520e4bd429d283c78157781b4de72.

I re-audited the complete change map, all historical blockers/threads, every production watermark writer, the task-row lock ordering, queue completion ordering, callback/reader ownership, retry paths, Q1-Q3 resource bounds, and performance/compatibility.

This round found and fixed one additional lifecycle race: the old shutdown code snapshotted readers and then blindly cleared the whole map. A reader published between those operations could be detached without Close and become invisible to the final cancellation scan. Shutdown now transfers only exact captured instances with CompareAndDelete to one aggregate completion owner. An empty retry completes synchronously, so repeated cleanup neither hides a successor nor creates duplicate Close/Wait waiter chains.

The end-to-end invariant is now closed:

  • every watermark INSERT/UPSERT takes the durable task-row FOR UPDATE fence in the same transaction;
  • the terminal queue barrier completes after every persistence phase in the callback batch;
  • Pause/Failed/Restart/Cancel retain callback and reader-generation ownership until actual completion;
  • DELETE failure remains durably retryable under status+runner CAS;
  • guarded batches remain deterministic, bounded, and substantially cheaper than the earlier implementation.

Exact-head evidence: full pkg/frontend under race; the reader snapshot/publication counterexample under race x100; real two-CN embedded-cluster writer-first and DROP-first ordering; affected normal package tests; incremental golangci-lint with 0 issues; git diff --check. I found no remaining blocking correctness, liveness, unhappy-path, performance, Q3, compatibility, or test-quality issue. CI is still running and was not used as a prerequisite for this decision.

@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 65f67c2891e2f0143f56c4000c914ec63248e94f against base fa829e5c505520e4bd429d283c78157781b4de72.

One new P2 test-liveness defect remains (inline). This changes my previous approval on the same head based on a newly traced failure path, not a new production regression. Transaction creation can fail before the holder callback runs, leaving both new concurrency-test helpers permanently waiting on a readiness channel. The test's 180-second context cannot release that raw channel receive.

The production fix's direction remains sound: all updater INSERT/UPSERT paths use a durable task-row FOR UPDATE fence, the flush barrier includes error persistence, callback/reader generations retain cleanup ownership across timeout/retry, and taskservice cancellation compensation is guarded by status and runner. I found no additional blocking production correctness or performance issue in this pass. Batching is capped by rows/SQL size with deduplicated task predicates; the documented benchmark concerns SQL construction, not an end-to-end CDC throughput guarantee. Mixed-version clusters still need the documented rollout caveat because old writers do not acquire the new fence.

Q1-Q3 summary:

Closure Result
Reader/callback cleanup ownership (Q1) No new blocker found; retained completion and exact-instance transfer cover the reviewed retry paths.
Production wait/barrier paths (Q2) No new blocker found in the reviewed cancellation and persistence paths.
New two-CN test readiness (Q2) Fails when ExecTxn returns before invoking its callback; see inline finding.
Batch/cleanup accumulation (Q3) No new blocker found in the changed bounds and reclamation paths.

Evidence: inspected every changed hunk and the relevant historical reviews; verified current-head UT/BVT/SCA success and the UT log showing both TestIssue27666CDCWatermarkWriteSerializesWithDrop orderings actually passed; git diff --check passed. This pass reused existing exact-head validation rather than rerunning the full suite. The new finding is established by source tracing through sqlExecutor.ExecTxn -> newTxnExecutor -> adjustOptions/txnClient.New (or engine.New); I have not claimed a runtime fault-injection reproduction. Please fix the bounded failure handshake in both helpers and add a cheap deterministic pre-callback-error/cancellation regression; no redesign of the CDC fence is requested.

Comment thread pkg/tests/issues/issue_27666_test.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.

Re-reviewed final head 5920aba39fb4d7cedfecae29f3b80bce9b903e0e, including the complete follow-up diff and its interaction with the previously reviewed CDC design.

The P2 from my previous review is resolved at the common protocol boundary: both orderings share one test transaction owner; readiness observes pre-callback terminal errors and cancellation; broadcast completion supports assertion and cleanup joins; cancellation/join is registered before launch and runs before catalog teardown. The existing two-CN lock-waiter and zero-residual-row oracles remain intact.

Validation passed on the final code: full owning pkg/tests/issues normal suite; new deterministic failure/cleanup cases under race x100; real two-CN ordering test under race once and then x2 in one process; golangci-lint 2.6.2 with 0 issues; staged diff check. The PR body records exact commands, results, adaptive repetition sizing, and evidence reuse.

Q1 ownership, Q2 bounded waits, Q3 fixed resource cost, error propagation, failure cleanup, test oracle preservation, and platform validation are closed for this follow-up. It adds no production-path overhead and does not change the durable CDC fence or its documented mixed-version limitation. No remaining blocker found; approving this head. New remote CI is not represented as completed by this 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.

Deep re-review of 5920aba39fb4d7cedfecae29f3b80bce9b903e0e against fa829e5c505520e4bd429d283c78157781b4de72: no new blocking finding; APPROVE.

I rechecked the complete follow-up implementation and tests, then revisited the high-risk closures in the existing change map: durable writer/DROP serialization, full-batch flush completion, cancellation and reader ownership, cleanup retry CAS, batch bounds, and rollout limitations. Production CDC/frontend/taskservice code is unchanged since the prior reviewed revision; prior coverage of the unchanged hunks remains applicable.

Counterexamples checked in this pass:

  • ExecTxn returns before invoking its callback: the worker still publishes its error and closes done; waitReady observes completion or caller cancellation rather than waiting forever for readiness.
  • Readiness and terminal completion are both observable: readiness alone does not assert commit success; the real race driver still checks both terminal results and final catalog counts. All reads of the shared terminal error follow the done-channel synchronization edge.
  • An assertion abandons the scenario: transaction cleanup is registered before launch; subtest cleanup cancels/joins contender and holder before catalog teardown. The synchronous subtests finish cleanup inside the shared-cluster callback, so the change does not move catalog mutation outside that fixture's ownership interval.
  • Duplicate result consumers: completion is broadcast, not a single consumed error value; normal assertions and cleanup cannot steal each other's completion signal.
  • Timeout/late worker: caller waits and cleanup have independent bounds; a cancellation-unresponsive executor is reported as a test failure, not falsely claimed to be forcibly terminated.
Audit Result
Q1 ownership No new gap in transaction/reader cleanup ownership or publication found.
Q2 liveness Previous readiness deadlock is closed; reviewed barrier and cancellation paths retain their release/bound conditions.
Q3 boundedness / performance Fixed test worker/signal count; no added production-path cost. Existing row/SQL batch bounds and concise failure diagnostics remain intact.

Revalidated the retained exact-code evidence: full issues package normal PASS (52.836 s), 100 named TestCDCRaceTxn race passes with zero failure events, both two-CN race repetitions PASS (12.63 s including initialization, then 0.14 s), affected-package lint 0 issues, clean worktree and diff check. These results are reused, not represented as newly rerun in this pass. No code edits were made.

Remaining documented limits are unchanged: strict distributed protection requires all writers to use the new fence during rolling upgrades; SQL-construction benchmarks do not establish end-to-end CDC throughput. Latest remote CI was still pending when inspected and is not claimed green. Neither limitation supplies a new blocking counterexample to this head.

@mergify

mergify Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

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]: DROP CDC leaves orphan mo_cdc_watermark rows due to worker shutdown race

5 participants