Repository navigation
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
aptend
left a comment
There was a problem hiding this comment.
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.
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
| } | ||
|
|
||
| // Begin transaction if needed (unless initSnapshotSplitTxn is set) | ||
| // Keep the complete initial snapshot in one target transaction. The sinker |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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:
- A stable stream exhausts its per-stream retries; cleanup persists
R:1:...and caches retry count 1. - The same cleanup removes the cache/fence and deletes that metadata.
GetTableErrMsgreads durableR:1,ShouldRetryadmits a replacement pipeline under the same live daemon generation.- The same persistent retryable failure is built from a nil local metadata entry and is persisted as
R:1again, notR: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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 未修改上述关键文件,因此不会自然消除问题。
|
Systematic follow-up pushed in This closes both deterministic blockers from review 5123481765:
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 Validation on the pushed production code:
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
What type of PR is this?
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:
REPLACEcannot remove a row deleted or re-keyed between the two snapshots.EndTs; a completed bounded task could therefore look permanently incomplete after restart.table_count / 200ms.moerrand change its concrete identity; commit-error and scanner-cleanup paths also had incomplete/overly coupled cleanup behavior.Implemented protocol and invariants
stable-epoch-v1capability marker and the distinctTaskCode_InitCdcStableEpoch. Legacy CNs cannot claim them; unmarked tasks retain the atomic compatibility path.mo_catalog.mo_cdc_snapshotbefore any partial target commit. Reload it on every stable pipeline start, including restart with a non-empty watermark.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.REPLACE; source changes after that epoch are applied by the incremental interval(S, next].[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.OwnerFence. Existing pipelines retain their old token and cannot borrow a later generation's claim.BEGIN. This serializes active effects without letting an idle old owner pin takeover.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.mddocuments the user-visible behavior and recovery boundary.Failure and recovery behavior
Performance impact
For
Ninitial-snapshot engine batches, target commits are approximatelyceil(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:
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
e0c092ef38c1aa1afb21d46a075e148b1410e91creplicated 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 peakmo-serviceRSS 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
Makefile / SCA decision
Earlier revisions changed
Makefile/.golangci.ymlto tune SCA memory/concurrency. That is unrelated to the CDC runtime protocol and duplicated the repository-wide portable SCA cache work now present onmain. Those changes are removed: this PR has noMakefileor.golangci.ymldiff against currentmain.QA test plan
Startup-failure control recovery — 9ddd244
Fixes two related terminal-state gaps without adding a new persisted protocol or lifecycle state:
Validation for
9ddd24400d82dfa79a46668cebe945d46ce8e43b: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./mnt/nvme/xupeng/mo-cdc-validation/pre-attach-fix-tests.logandfailed-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.
(task_id, task_runner, last_run)once; deferred error/release writes cannot borrow a reused executor's newer token.loc=Local. No new persisted schema/protocol or per-row work is added by this correction.Validation on the production sources in commit
0735225be6d95736ef264b74bc31da6277cc15dd:./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.taskserviceandfrontendrace packages, plus six focused generation/lifecycle tests with 100 race repetitions each (separate invocations). Final taskservice race rerun passed after all test changes.--new-from-rev=8db13a0953e9ffa17d73e65113fd76f8cfa8a394: 0 issues;git diff --checkpassed.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.QA reproduction: run the named cases in
pkg/taskservice/daemon_completion_test.go,TestLifecyclePublishesClaimBeforeReplacementAndHeartbeat,TestCDCFactoryRejectsSupersededClaim, andTestDaemonClaimSQLRoundTripvia.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 --checkand clean generated state after fullmake pb;-count=1:./pkg/cdc ./pkg/frontend ./pkg/sql/compile;-count=1:./pkg/taskservice ./pkg/cnservice ./pkg/bootstrap/versions/v4_0_6;-race -count=3, covering limiter, grouping, ownership, lock lifecycle, and watermark fencing;-race -count=5, covering immutable claim generations and restart classification;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 commit57055ace9crecords that decision without changing the protocol.Takeover checkpoint correction — 28e2c28
The final counterexample review found two recovery-protocol holes and one upgrade unhappy path:
mo_cdc_watermarkrow 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.source_table_idandowner_generationare 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
StartTsandNoFull, 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.
Correctness and unhappy-path behavior:
Performance impact:
Validation on exact rebased head 5489186:
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:
ChangeData.InsertBatchduring 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
ChangeDatabatch remains caller-owned; every transfer to a snapshot group, sinker, orAtomicBatchimmediately clears the source field.TableChangeStreamcallsChangeData.Cleanafter 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:
RowCountreads and adds only constant-time nil/cleanup checks;Validation on exact head
1af13a008bf885e309683357fc5befc8ac74f1ae:./pkg/cdcnormal tests pass../pkg/cdcrace passes.0 issues;git diff --checkpasses.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
OwnerFencetwice aroundGET_LOCKand twice around targetCOMMIT. That fence usedHeartbeatDaemonTask, so each call performedBeginTx + UPDATE sys_daemon_task + Commitagainst 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
(task_id, task_runner, last_run). MySQL executes one autocommit indexedSELECT; it does not renew the lease, begin an explicit transaction, or mutate the daemon row. The task runner remains the only periodic heartbeat writer.owner_generationSQL.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
GET_LOCK: validation fails and releases the lock before target work;RELEASE_LOCKresponse: the physical driver connection is marked bad before close, so a possibly lock-owning session cannot return to the SQL pool;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.
pkg/cdc13.208s,pkg/taskservice26.800s,pkg/frontend24.444s,pkg/cnservice9.518s.pkg/cdc14.996s,pkg/taskservice27.140s,pkg/frontend34.886s.git diff --checkis 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
(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.context.Background(). Connection setup, advisory-lock acquisition, and target DDL therefore could outlive pause, cancel, restart, or CN shutdown.GET_LOCKchecked 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.Corrected authority and failure model
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.GET_LOCK(..., 1)query has a 2-second ceiling independent of the configurable DML timeout.Performance and operational risk
task_id; adding status predicates creates no scan, heartbeat write, or hot-row write amplification.Review corrections and validation
./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).-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.R3 design approval closure (
57055ace9c)The independent design approval is now traceable in review 5120209126, performed against exact protocol/code head
7fa37b9d61. Commit57055ace9cchanges 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 crossMaxRetryCount; 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 proves1 -> 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.