Skip to content

fix(cdc): persist no-full creation watermark - #28506

Merged
XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/28268
Sep 24, 2026
Merged

XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/28268

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Test and CI

Which issue(s) this PR fixes:

Fixes #28268

What this PR does / why we need it:

Persist the CREATE CDC transaction snapshot as the automatic NoFull start, including both physical and logical HLC components. This closes the gap between successful CREATE and asynchronous reader admission without replacing an explicit user StartTs.

  • Fence the new persisted format with protocol v92 and dedicated executor code 15. Preserve main's v89–v91 capabilities; shared, frontend, and compile tests reject v91 and accept v92.
  • Resume legacy NoFull tasks from existing durable progress; fail closed when neither a durable start nor progress exists, rather than silently skipping data.
  • Preserve durable watermarks on claim-loss cancellation while retaining terminal cancellation cleanup.
  • Exercise the public CREATE/admission boundary and CN restart; require a durable watermark covering a snapshot that contains the delivered source row before restarting. This proves progress and final data, not exactly-once delivery.
  • Cover runner-selected non-destructive cancellation for both stable-epoch and lossless-start executor codes.

Rebased onto bc523def3b55de2b305c14ee9fafb61dfec24126, consolidating the existing effective patch and preserving its behavior.

Validation

Local macOS arm64, Go 1.26.4, native libraries rebuilt for the rebased source.

  • Protobuf task descriptor package: passed.
  • Claim-loss dispatcher: race passed; 100 focused race repetitions passed.
  • Full taskservice package with race: passed (34.259s).
  • Focused CDC, frontend, and compile protocol/admission/watermark tests: passed (19.078s / 1.548s / 2.174s).
  • Public TestCDCNoFullPublicLifecycle: passed (57.643s), including durable-progress and real CN restart assertions.
  • Legacy durable-progress and lossless HLC format tests: passed (2.652s).

GPT-6 medium design and overall code review completed with no code blockers. No performance improvement is claimed. New CI will run after push and is not represented as already passed.

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

@mergify mergify Bot added the kind/bug Something isn't working label Sep 9, 2026
@matrix-meow matrix-meow added the size/S Denotes a PR that changes [10,99] lines label Sep 9, 2026

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

Review 结论:REQUEST_CHANGES。Exact head: a9cab7a

Confirmed blocker

P2 — NoFull 创建起点持久化时丢失 HLC logical 分量。位置:pkg/frontend/cdc_options.go:93-94、pkg/sql/compile/ddl.go:6624-6625。

具体反例:源表有一行提交时间 (P,3),CREATE CDC 的快照为 (P,5);NoFull=true、未显式指定 StartTs、目标为空且无 watermark。该行在快照前已可见,不应作为增量复制。新 helper 使用 ToStdTime(),只保留物理时间;读取端 CDCStrToTS 用 logical=0 重建为 (P,0)。executor 以此初始化 watermark,reader 的范围筛选因此重新包含 (P,3),导致快照前数据被复制。timestampWaiter.GetTimestamp 返回 latest.Next(),非零 logical 是可达状态。

修复建议:自动生成的创建起点必须无损保存 physical/logical,并同步处理读取及旧格式兼容;保留显式用户时间字符串的既有语义。增加非零 logical 的持久化往返测试,以及“起点前不复制、起点后复制”的 reader/SQL 验证。

测试证据不足

新增 UT 只覆盖 LogicalTime=0、格式化及 nil/empty snapshot,未覆盖 catalog 往返、executor 初始化、延迟启动期间提交、故障重启和续传。现有 CDC BVT 未覆盖 NoFull 数据捕获。

尚未验证的风险

未执行本地 Go UT/race、实际反例、现场 SQL/BVT、取消/重试故障注入、性能及升级降级矩阵。混合版本下旧 executor 可能忽略持久化起点;该风险未作为新增 blocker。

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

Review of exact head a9cab7a1b473317bfa26abcec3f7e8e46d940d0d against cd04bb4c1af5bc595e2147dc645dfa754f4c395b: REQUEST_CHANGES.

P2 — Persist the complete NoFull creation timestamp

Both frontend helper and compile/ddl.go's helper serialize SnapshotTS().ToStdTime() as RFC3339Nano. ToStdTime deliberately discards LogicalTime; CDCStrToTS reconstructs BuildTS(physical, 0).

With creation snapshot (P,5) and a row already committed at (P,3), the durable start becomes (P,0). On initial startup without an existing watermark, addExecPipelineForTable initializes progress from that value, so incremental CollectChanges includes the pre-start row (P,3). Nonzero logical snapshots are reachable: timestampWaiter returns latest.Next(). NoFull consequently copies data that was already visible before its intended activation boundary.

Persist physical and logical components losslessly for the automatically captured timestamp, while retaining compatibility with existing and user-supplied time strings. Add a nonzero-logical catalog roundtrip and reader controls proving pre-start rows are excluded and post-start rows included. The new helper tests use LogicalTime=0 only. Existing committed progress correctly wins on resume, but does not protect this initial case.

This independently confirms the current-head finding by tracing producer, encoding, decoder, initial watermark and reader. Five-file diff and relevant consumers reviewed; exact-head CI reused and rechecked. No live CDC reproduction or new local tests are claimed.

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

P1 — MORPC protocol version collision with current main

Location: pkg/defines/const.go:127-128 at head 429c5c5a9ae324dc429ec25054cb674a3b93f5ac.

This head assigns MORPCVersion89 to lossless physical/logical NoFull CDC and makes it the latest version. The live origin/main at cd5feff242744557448cd107c6744fb9fd5df088 already assigns version 89 to exact decimal-literal/coercion semantics and version 90 to geodetic-distance/length-unit semantics. The PR is therefore currently conflicting with main; resolving the conflict while retaining 89 for CDC would reuse a global capability number for an unrelated feature.

pkg/cdc/types.go:339-342 accepts any protocol version >= MORPCVersion89. During a mixed-version rollout whose common protocol is 89, a producer containing this PR can pass that fence and create InitCdcLosslessStart (task code 15), while nodes implementing main's version 89 do not implement this CDC protocol. The task can then be scheduled to an incompatible CN and remain unclaimable or fail task handling.

Please rebase onto current main, allocate the next coordinated MORPC version after the live main range, and update MORPCLatestVersion, the frontend/compile gates, and boundary tests accordingly.

@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 at exact head 761c36872aa4fa4a9202812ec74ecd814db6f70d.

The HLC, v92/code-15 capability fence, generated descriptor, stale-read handling and non-destructive claim-loss dispatch are addressed. Exact-head CI is green, and the public lifecycle test runs unskipped under race.

Two P2 validation gaps remain:

  1. pkg/tests/sqlintegration/ddl_test.go:635-709: the pre-restart checkpoint is only logged; no assertion establishes the replacement reader's starting boundary. Replaying from the original CREATE boundary can pass because sink upserts preserve row counts. Add a discriminating persisted-progress recovery oracle and an unprocessed inter-generation commit.
  2. pkg/frontend/cdc_test.go:3691-3771: takeover uses modeled storage, always-successful fences and manually initialized executors; recovery is a direct field assignment. Add deterministic real A/B takeover with delayed A shutdown, durable B owner/checkpoint assertions, and fresh-executor recovery.

Provide named terminal execution and focused race evidence for those scenarios. The design gate is exempt for this ordinary bug fix. Coverage percentage was not used as a gate.

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

Approved at fb83cb1, including the test-only update since my review of 761c368.

The persisted physical/logical CREATE snapshot closes the NoFull admission gap without replacing an explicit StartTs. Legacy tasks require durable progress, stale retained ranges fail closed, and the protocol/executor fence prevents older workers from interpreting the new format. Ownership-loss cancellation preserves shared checkpoints while terminal cancellation retains cleanup.

I reviewed the additional takeover and restart assertions in the new commit. Existing CI is green on this revision; no local cluster tests were rerun. No blocking issue found.

@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 at exact head fb83cb1.\n\nTwo P2 validation blockers remain:\n\n1. pkg/tests/sqlintegration/ddl_test.go:705-722 — observe the replacement reader's recovery boundary. The new equality assertion reads the catalog while admission is blocked before watermark loading and reader creation. It proves checkpoint survival, not checkpoint consumption. A replacement that incorrectly reads from the original CREATE boundary can still pass: the catalog retains W, row 2 is replayed through an upsert, and row 3 is delivered. Assert the replacement's first actual collection boundary against a quiesced durable checkpoint, or add an equivalent replay-discriminating oracle.\n\n2. pkg/frontend/cdc_test.go:3691-3812 — complete the real takeover/recovery validation. The updated test constructs executors and exercises their claim fences, but still uses modeled storage, manually transitions executors to Running, directly invokes non-destructive cancellation, and ends recovery at ClaimWatermarkOwner. No executor starts or reader consumes the recovered checkpoint. The model even creates a missing row during an UPDATE, unlike the real catalog. Add deterministic real-storage A/B takeover with delayed A shutdown, durable B owner/checkpoint assertions, and fresh-executor reader recovery; provide named terminal and focused race results.\n\nThe HLC encoding, v92/code-15 fence, generated descriptor, stale-read handling, heartbeat claim-loss cancellation, and paused reconciliation fixes are present. Exact-head CI is green and the public lifecycle test passed. These requests concern discriminating lifecycle evidence, not coverage percentage.\n\nReviewed exact head: fb83cb1

@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 at exact head 905ddb3.\n\n[P1] Failed-start completion can still delete the replacement owner's checkpoint.\n\nAt pkg/taskservice/daemon_task.go:224-245, a code-15 restart attempt can initialize its watermark updater, fail the required startup catalog transition at pkg/frontend/cdc_exector.go:981, and then successfully release its restart claim. CN B can claim the task and persist checkpoint W, while CN A's delayed completion still calls ordinary Cancel(), reaching DeleteTaskWatermarks at cdc_exector.go:1720. That DELETE is scoped only by account/task and checks neither terminal task ownership nor owner_generation, so A can delete B's live checkpoint. Recovery can then replay from the original CREATE boundary or fail against expired history.\n\nUse non-destructive cleanup for failed execution completion while the logical task remains retryable; reserve destructive cleanup for authorized terminal removal. Add a barrier-controlled regression where A releases its claim, B persists W, A completes delayed cleanup, and a fresh reader recovers from W.\n\n[P2] Real A/B takeover and reader recovery remain unvalidated.\n\nTestCdcTaskClaimLossDelayedCancelPreservesReplacementWatermark at pkg/frontend/cdc_test.go:3694 still uses a shared in-memory catalog and modeled daemon claim. Executors have nil engine/transaction dependencies, are manually transitioned to Running, never call Start, and C recovery ends at ClaimWatermarkOwner. Broken executor admission or checkpoint consumption can therefore leave the test passing. Complete the real-storage A/B scenario with durable owner generations, delayed A cleanup after B persists progress, fresh-reader recovery from the actual checkpoint, and focused race evidence.\n\nThe public restart checkpoint boundary is now covered; HLC encoding, v92/code-15 fencing, descriptor consistency, stale-read handling, heartbeat cancellation, and paused reconciliation remain sound. Coverage percentage is not a gate.\n\nReviewed exact head: 905ddb3

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

Codex automated review

Reviewed exact head 905ddb3 against origin/main, including all 19 reviews and 6 inline threads. The previously reported defects are genuinely closed on this head: start_ts now round-trips both HLC components via Timestamp.DebugString()/timestamp.ParseTimestamp (pkg/frontend/cdc_util.go:348), the format is fenced by MORPCVersion92 plus executor code 15 with matching producer/consumer enumeration (pkg/defines/const.go:130, pkg/cnservice/server_task.go:360, pkg/taskservice/daemon_task.go:68), pkg/pb/task/task.pb.go is a real regeneration (the embedded gzipped descriptor now carries InitCdcLosslessStart=15; go test ./pkg/pb/task/... passes locally), handleStaleRead fails closed for any durable start (pkg/cdc/table_change_stream.go:1746), and claim loss dispatches CancelWithoutWatermarkCleanup so a superseded owner cannot delete the replacement's progress. I did not re-raise XuPeng-SH's two still-open test-evidence requests on pkg/tests/sqlintegration/ddl_test.go and pkg/frontend/cdc_test.go; the newest commit adds a real CollectChanges boundary oracle for the first of them, and the author has not yet replied to the second.

One new blocking regression remains, on the upgrade path for pre-existing NoFull tasks: because legacyNoFull now fails closed per watermark key rather than per task, the first source table discovered after an upgrade turns a healthy running task permanently Failed. Two minor dead-branch/comment defects are reported as non-blocking.

Native CGo libraries are not built in this worktree (cgo/libmo.dylib, thirdparties/install absent and the primary worktree has none), so only the CGo-free pkg/pb/task suite was executed locally; the remaining conclusions are traced statically through producer, catalog SQL, and consumer code.

P1 - Legacy NoFull task permanently fails when a new source table is discovered after upgrade (pkg/frontend/cdc_exector.go:3090)

legacyNoFull is computed per table key (exec.noFull && exec.startTs.IsEmpty() && !exec.stableInitialSnapshot, pkg/frontend/cdc_exector.go:3080), so it is true for every pre-existing NoFull task row: those were created with an empty start_ts and no _InitialSnapshotProtocol marker, and pre-PR BuildTaskMetadata gave them TaskCode_InitCdc. The new gate at pkg/frontend/cdc_exector.go:3090-3091 then requires a mo_cdc_watermark row for that exact (account, task, db, table) key and otherwise returns a non-retryable moerr.NewNotSupportedf.

That is correct for resuming a task's own tables, but it also fires for a table that first matches the task pattern after the upgrade — the normal dynamic-discovery path (handleNewTables skips only keys already in exec.runningReaders, pkg/frontend/cdc_exector.go:2659). Such a table has no watermark row yet, so on origin/main it was admitted with watermark = types.TimestampToTS(txnOp.SnapshotTS()) and replicated; now it errors. The failure then escalates from one table to the whole task:

  1. moerr.NewNotSupportedf matches none of the four retryable predicates, so errorCtx.IsRetryable is false (pkg/frontend/cdc_exector.go:2772-2777).
  2. For a legacy task stableInitialSnapshot is false, so pipelineOwnerFence stays nil (pkg/frontend/cdc_exector.go:2731-2738); WithWatermarkOwnerFence(ctx, nil, …) returns ctx unchanged (pkg/cdc/watermark_updater.go:1899-1901) and job.OwnerFence is nil (pkg/cdc/watermark_updater.go:272).
  3. The unfenced branch therefore uses GuardedWatermarkErrorUpdateSQL (pkg/cdc/watermark_updater.go:1302-1303), which is INSERT … ON DUPLICATE KEY UPDATE err_msg (pkg/cdc/sql_builder.go:296-303). It creates the missing row, persisting the non-retryable diagnostic even though no progress exists.
  4. ShouldRetry returns false for non-retryable metadata (pkg/cdc/error_handler.go:200-202), so the next detector callback — the 15s scan loop, or the 5s retryTicker that keeps lastMp because the callback returned an aggregate error (pkg/cdc/table_scanner.go:544-552, pkg/frontend/cdc_exector.go:2817) — sees hasError=true at pkg/frontend/cdc_exector.go:2704 and calls failTaskForPermanentTableError (pkg/frontend/cdc_exector.go:2720).

Net effect: an existing, healthy legacy NoFull task is permanently Failed, all of its readers are stopped, and it is unregistered from the detector as soon as any new matching table appears (for a database-level task, any new table in that database). The user-visible symptom is a task that dies on upgrade-triggered schema growth, which is a regression rather than the intended fail-closed resume.

Suggested direction: scope the fail-closed rule to the situation it was written for. Distinguish "this task has no durable activation boundary at all" (fail closed) from "this task is running and this key was never admitted" (admit from the current snapshot, as origin/main does, or from the task's existing durable progress), so dynamic discovery keeps working for legacy rows. If fail-closed is still wanted for new tables, the error must not be persisted as a non-retryable per-table diagnostic that trips failTaskForPermanentTableError for the whole task, and the message should not tell an already-upgraded cluster to wait for protocol version 92.

P2 - BuildTaskMetadata assigns InitCdcStableEpoch on a branch that is always overwritten (pkg/frontend/cdc_options.go:320)

The (opts.NoFull && cdc.UsesLosslessNoFullStart(opts.ExtraOpts)) clause added at pkg/frontend/cdc_options.go:321 can never survive: the very next condition (pkg/frontend/cdc_options.go:324-326) re-tests the identical predicate and unconditionally reassigns executor to TaskCode_InitCdcLosslessStart. The clause is dead, and reading the first if in isolation gives the wrong answer about which executor a lossless NoFull task gets. The same two-step shape is duplicated verbatim at pkg/sql/compile/ddl.go:6486-6492, so the misleading branch exists in both mirrored create paths.

Non-blocking: the final value is correct and TestCDCBuildTaskMetadataSelectsLosslessExecutor covers it. Simplify to a single selection (e.g. switch on NoFull + UsesLosslessNoFullStart / UsesStableEpochInitialSnapshot) in both files so the routing is stated once.

P2 - Unreachable NoFull snapshot fallback carries a comment describing the branch above it (pkg/frontend/cdc_exector.go:3093)

else if exec.noFull && watermark.IsEmpty() at pkg/frontend/cdc_exector.go:3093-3096 cannot be reached. watermark is exec.startTs here, so entering the branch requires exec.noFull && exec.startTs.IsEmpty() while legacyNoFull at pkg/frontend/cdc_exector.go:3080 was false — i.e. exec.stableInitialSnapshot must be true. For a NoFull task that flag is set only from the no-full-hlc-v1 marker (pkg/frontend/cdc_exector.go:3411-3413), and the producers write that marker only together with a non-empty snapshot-derived StartTs (pkg/frontend/cdc_options.go:280-282, pkg/sql/compile/ddl.go:6874-6876). It therefore requires a catalog row whose additional_config and start_ts disagree.

The comment ("Keep the fallback for legacy task rows that have no durable start watermark") also describes the opposite of the code: legacy rows are handled by the legacyNoFull branch immediately above, and this one silently reinstates the exact txnOp.SnapshotTS() behavior the PR set out to remove. Non-blocking because it is inert today, but it is a latent silent-skip path if the marker and start_ts ever diverge. Either drop the branch or make it fail closed like its neighbour.

@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 905ddb3(PR base 57c280e)的审查结果如下。29 个 CI/check 均已完成且通过。

P1:启动失败的重试完成路径仍会删除替代 owner 的 durable watermark

位置:pkg/taskservice/daemon_task.go:224-245;相关调用为 pkg/frontend/cdc_exector.go:105-179、970-987、1605、1717-1728。

restart claim 在 startTask.Handle 的 defer 中先通过 releaseRestartClaim 变为可重试/未分配状态;如果 startDaemonTask 已经 attach active routine,随后却因必需的 catalog transition 失败返回,completeDaemonTask 仍会调用普通 Cancel()。普通 Cancel() 会执行 DeleteTaskWatermarks,而删除范围只有 account/task,没有 owner/generation fencing。

触发场景:CN A 领取 lossless NoFull task,attach 成功后启动阶段失败并释放 claim;CN B 随后领取同一 task 并持久化 checkpoint W;A 的延迟 completion 再执行普通 Cancel(),删除 B 的 watermark。新 executor 可能从原始 creation 起点重放,或因 stale history 失败,导致重复/丢数据风险。

建议:启动失败且任务仍可重试时使用 CancelWithoutWatermarkCleanup 等非破坏性清理;只有明确的终态删除才允许 DeleteTaskWatermarks,并补充带真实 A/B takeover 与 fresh reader 的回归测试。

P1:legacy NoFull task 在动态发现新表时会被永久失败

位置:pkg/frontend/cdc_exector.go:3071-3097、2658-2740、2772-2781、2704-2721。

legacyNoFull 由 empty start_ts 且非 stable initial snapshot 判定。对数据库级或 wildcard task 动态发现的新 source table,首次没有 watermark row;代码在 GetWatermarkProgressIfExists 返回 found=false 后直接返回 non-retryable NotSupported。调用方随后写入非 retryable table error,下一轮 detector 将其视为 permanent table error 并 fail 整个 task。

触发场景:PR 前创建的 legacy NoFull task 运行正常;升级后出现一个匹配过滤条件的新表。该新表本应按当前语义被纳入,但 task 会永久失败,而不是安全初始化该表的进度。

建议:区分“恢复已有 legacy key”与“首次纳入动态发现的新 key”;后者应按当前 snapshot/现有兼容语义安全初始化,不能把缺少 durable progress 直接固化成 task-fatal 的 non-retryable error。

P2:关键 A/B takeover 与 reader recovery 场景仍缺少真实回归

位置:pkg/frontend/cdc_test.go:3694-3815。

该测试使用 nil engine/txn 依赖、手工推进状态,并直接调用 ClaimWatermarkOwner/UpdateWatermarkOnly;所谓 recovery 仍是再次直接 claim,没有调用 Start、真实 detector pipeline、CollectChanges 或 fresh reader 消费替代 owner 的 checkpoint。最新 SQL integration 测试覆盖了公开重启边界,但没有覆盖上面启动失败后 A/B takeover 的路径,因此该类回归仍可能漏检。

P2:NoFull lossless executor 分支存在不可达/被覆盖逻辑

位置:pkg/frontend/cdc_options.go:320-326;镜像逻辑位于 pkg/sql/compile/ddl.go:6486-6492。

第一个条件已在 NoFull 且 lossless 时选择 InitCdcStableEpoch,紧接着相同条件又无条件覆盖为 InitCdcLosslessStart;最终选择目前是正确的,但前一分支不可达,容易掩盖 executor 选择错误,建议删除或重构并补分支断言。

@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 (gpt-6-astra medium, exact head e208250).\n\nREQUEST_CHANGES.\n\nP2 — Required R3 takeover/recovery evidence is still missing.\n\nTestCdcTaskClaimLossDelayedCancelPreservesReplacementWatermark uses an in-memory catalog, manually changes daemon ownership, constructs executors with nil engine/transaction dependencies, and ends its oracle at ClaimWatermarkOwner; no replacement reader consumes the checkpoint. The failed-completion test uses a mock routine and restart=false, so it does not exercise restart-claim release followed by competing acquisition. The public lifecycle test has real storage and a replacement reader, but restarts one CN sequentially; the obsolete and replacement owners never overlap.\n\nPlease provide a deterministic real-storage scenario proving:\n1. A loses/releases its claim while cleanup is held.\n2. B acquires a newer durable generation and persists checkpoint W.\n3. A's delayed runner-selected cleanup executes.\n4. W survives, obsolete writes are rejected, and a fresh reader's first collection starts at W.\n\nExact-head CI and the public single-CN lifecycle evidence were reviewed; no additional confirmed production-code blocker was found.

@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 — P2 lifecycle evidence is still nondiscriminating in pkg/tests/sqlintegration/ddl_test.go.

TestCDCNoFullPublicTakeoverLifecycle now uses real A/B task runners and catalog storage, and B's first CollectChanges is checked against A's checkpoint. However, the test does not observe A's runner-selected cancellation completing after releaseCancel(): the cancellation hook fires before the destructive cleanup site (pkg/frontend/cdc_exector.go around line 1755), and the test immediately polls the existing row. A regression that deletes the watermark after the hook can race past the assertion. It also accepts checkpointB == checkpointBeforeB, so it does not prove B advanced durable progress past the inserted row or that a fresh reader recovers from B's new checkpoint.

Please join/observe completion of A's delayed cleanup, require durable B progress to advance over the post-takeover row, then start a fresh reader and assert its first collection begins at the surviving checkpoint. CI passes the new takeover/restart tests, but those assertions do not yet close the earlier exact-head recovery requirement. This is a validation blocker, not a newly confirmed production-code defect.

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

GPT-6 High deep review at exact head 0f29b74: REQUEST_CHANGES — P2 lifecycle evidence gap in pkg/tests/sqlintegration/ddl_test.go:1066-1081. The latest test now waits for A’s delayed post-cleanup completion and verifies a fresh reader’s first actual CollectChanges boundary against persisted progress. However, it only asserts that B’s checkpoint advanced beyond its prior value; it does not prove that the durable checkpoint covers the post-takeover row 3. This still permits a sink-delivered row with a checkpoint before that row’s committed snapshot, after which the fresh reader can pass its boundary assertion while replay/data-loss behavior remains untested. Capture a transaction snapshot that demonstrably contains row 3 and require checkpointB >= that snapshot before releasing A; keep the cleanup-survival and fresh-reader assertions. Exact-head CI is green. This is a validation blocker, not a newly confirmed production defect.

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

Deep review of exact head 0f29b74cdbb260311a7fc34715ad969e859fc080 against current origin/main 220e10110b15d431446cb2f694f2b25bade63ae7 (merge base f6d4cf4aa7683aa77e8a4edbdce570580f1b0a18). The PR is open and mergeable. All 29 check runs are complete; none failed, and CI Required succeeded.

No P0/P1 findings. Two P2 findings are attached inline: old-CN updater cache retention after non-destructive claim-loss cancellation, and the takeover integration test not tying B's checkpoint to the committed row 3 snapshot.

I read the prior reviews, inline threads, and PR conversation. The PR author has not replied to the prior P2; later commits do not count as a reply. Per the event policy, this review is COMMENT.

Comment thread pkg/frontend/cdc_exector.go Resolved
Comment thread pkg/tests/sqlintegration/ddl_test.go Resolved

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

Codex automated review

Follow-up at exact head 0f29b74. New review surface since 905ddb3: merge 0f29b74 has an empty --remerge-diff (clean merge), and a06bc09's only conflict resolution is renumbering the CDC protocol fence from the upstream-collided v92 to MORPCVersion94. The remaining authored delta is e208250 plus four test commits.

My prior blockers:

  • P1 (FIXED) legacy NoFull task permanently Failed once a new source table was discovered after upgrade. e208250 replaces the per-key fail-closed error with legacyNoFullStartTS (pkg/frontend/cdc_exector.go:3122, call site :3170): durable progress wins when present, otherwise the key starts at its admission snapshot, which is origin/main's unconditional NoFull behavior (origin/main pkg/frontend/cdc_exector.go:3016-3018). Dynamic discovery no longer errors, so it can no longer persist a non-retryable per-table diagnostic that trips failTaskForPermanentTableError. Covered at pkg/frontend/cdc_test.go:6096-6100.
  • P2 (FIXED) dead InitCdcStableEpoch branch in BuildTaskMetadata: both mirrored create paths now use one switch (pkg/frontend/cdc_options.go:317-325, pkg/sql/compile/ddl.go:6576-6582).
  • P2 (FIXED) unreachable NoFull snapshot fallback carrying an inverted comment: now fails closed with an accurate message (pkg/frontend/cdc_exector.go:3171-3176), and is unreachable because the no-full-hlc-v1 marker is only written together with a snapshot-derived StartTs (pkg/frontend/cdc_options.go:280-282, pkg/sql/compile/ddl.go:6965-6967).

New surface verified, no blockers:

  • Executor code 15 is still unclaimed upstream (proto/task.proto:90). The v94 fence equals MORPCLatestVersion, so a fully upgraded cluster admits NoFull CREATE, a mixed cluster defers it, and old CNs cannot claim code 15.
  • completeDaemonTask switching to CancelWithoutWatermarkCleanup (pkg/taskservice/daemon_task.go:245-252) cannot orphan durable rows: DROP CDC deletes mo_cdc_watermark in the frontend (pkg/frontend/cdc_handle.go:467-470) and terminal cancellation still uses destructive Cancel (pkg/taskservice/daemon_task.go:816). The attached ActiveRoutine is the *CDCTaskExecutor itself (pkg/frontend/cdc_exector.go:234), which implements CancelWithoutWatermarkCleanup (:1676), so the optional-interface assertion cannot silently fall back to a destructive delete. Preserving progress on a failed Start is also what makes stable-epoch retry meaningful.
  • bee9824 relaxing Equal(checkpointB, freshStart) to GE is legitimate rather than a weakened oracle: B remains the rightful owner between the post-A-cleanup equality oracle and the phase-4 claim transfer, so forward progress is expected, while the assertion still forbids the backward movement an obsolete write would cause.

Recorded as context only, not duplicated: XuPeng-SH's still-open validation blocker that checkpointB is not tied to a snapshot provably containing row 3 (pkg/tests/sqlintegration/ddl_test.go:1066-1081), and iamlinjunhong's two open inline P2s at the same location and at pkg/frontend/cdc_exector.go:1676 (old-CN updater cache retention after non-destructive claim-loss cancellation). The author has not replied to either; both are validation/cache-hygiene items rather than confirmed production defects.

One non-blocking finding remains: the comment left above the legacy branch now states the inverse of the code it documents.

Native CGo libraries are absent in this worktree (xxhash.h, roaring.h, usearch.h, jemalloc.h all missing), so no local build or test run was possible; every conclusion above is traced statically through producer, catalog SQL, and consumer code.

P2 - Legacy NoFull comment states the inverse of the code it documents (pkg/frontend/cdc_exector.go:3162)

e208250 correctly closed my prior P1 by letting a never-admitted legacy NoFull key start from its admission snapshot, but it left the comment above that branch describing the removed fail-closed rule.

pkg/frontend/cdc_exector.go:3162-3164 still reads: "A legacy NoFull task is safe to resume only when it already has a durable progress point. Never invent a new snapshot here: that would silently skip commits between CREATE CDC and executor admission." Three statements later, pkg/frontend/cdc_exector.go:3170 does exactly what the comment forbids: watermark = legacyNoFullStartTS(watermark, found, types.TimestampToTS(txnOp.SnapshotTS())), and legacyNoFullStartTS (pkg/frontend/cdc_exector.go:3122-3127) returns that admission snapshot whenever no durable progress exists. The new assertions in pkg/frontend/cdc_test.go:6097-6100 pin this intended behavior, including the message "a legacy table discovered after upgrade starts at its admission snapshot".

Non-blocking, because the code is correct: it matches origin/main's unconditional NoFull behavior (origin/main pkg/frontend/cdc_exector.go:3016-3018) for keys with no durable progress, and additionally prefers durable progress when a row exists, which main did not do. Only the comment is wrong.

Why it is still worth fixing: this is the comment that documents the exact invariant behind the P1 regression. A future reader following it would reintroduce the fail-closed error that permanently failed healthy legacy tasks as soon as any new table matched the pattern, and the neighbouring branch (pkg/frontend/cdc_exector.go:3171-3176) now legitimately does fail closed, so the two comments read as one consistent-but-false rule. Suggested direction: state that a legacy row with durable progress resumes from it, while a key never admitted before falls back to the admission snapshot as origin/main did, because a pre-upgrade task has no durable activation boundary left to preserve.

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

GPT-6 high review — APPROVE at exact head 91c0416.

Reviewed the HLC/checkpoint lifecycle test, including snapshot coverage, delayed cancel completion, and fresh-reader behavior. No blocking findings.

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

Reviewed exact head 91c0416 against base f6d4cf4.

I inspected the complete 26-file diff and traced the NoFull start-watermark path from transaction snapshot capture through persisted task metadata, protocol/task-code routing, watermark ownership, reader start boundaries, failed-start cleanup, and cross-CN takeover. The prior P2 concerns from review 5290758417 are closed at this head:

  • claim-loss cleanup now removes stale in-flight ownership state without deleting committed replacement progress;
  • the takeover regression now ties the durable checkpoint to a committed row-3 snapshot and verifies the fresh-reader boundary.

I found no current P0, P1, P2, or P3 findings. All 29 checks are complete and the required checks pass.

@mergify

mergify Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-24 10:33 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-24 11:27 UTC · at e0095b5b5e2c8976c0678519d2c647cd2f9edc3e

This pull request spent 54 minutes 22 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated
> This pull request seems to come from a fork, and Mergify needs the author's permission to update its branch.
The author needs to enable ["Allow edits from maintainers"](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) on this pull request, or update the branch manually.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

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

  • Requeue 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/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 NoFull may skip changes committed immediately after task creation

8 participants