Skip to content

fix(tae): filter TN rewrites by row commit time - #26163

Merged
XuPeng-SH merged 12 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/tae-delete-reinsert-dedup
Jul 26, 2026
Merged

XuPeng-SH merged 12 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/tae-delete-reinsert-dedup

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes

CheckIncremental selects committed objects in a timestamp window. For a TN flush or merge output, however, ObjectEntry.CreatedAt is the physical rewrite time, not the logical commit time of every row inside it. Old rows rewritten after a transaction snapshot could therefore be treated as new candidates and produce a false duplicate.

Fixes #26162.

The original flaky symptom was exposed by TestDelete3. Dedicated deterministic tests now cover both sides of the rewrite window: old rows must be ignored, while a row committed after the transaction snapshot must still cause a WW conflict even if TN flushes it before pre-prepare.

Design

For a TN-created nonappendable candidate:

  1. Keep the existing object/zonemap/BF pruning.
  2. Compare the primary key exactly.
  3. Only after an exact match, lazily load the existing hidden row commit-TS column.
  4. Ignore rows before the inclusive dedup interval and retain rows inside it.

The commit-TS vector is block-scoped, loaded at most once, and released on success and error. incrementalGetRowsByPK now also closes and nils its result vector when an error occurs, so ownership transfers to the caller only on success.

Direct CN-created objects retain the existing object-level conservative check because they do not carry TN row commit timestamps.

Explicit fallback boundary

Incremental dedup on TN is a best-effort fallback, not the primary correctness boundary for normal production DML. Pessimistic-RC primary/unique-key locks serialize same-key writers, and LockOp calls PrimaryKeysMayBeModified when the lock timestamp advances; LOAD DATA uses a table lock.

Some legacy objects, and TN rewrites containing CN-created rows, have missing/null row commit timestamps:

  • CheckIncremental skips an unverifiable row to avoid upgrade/rewrite false positives.
  • Strict policies (CheckAll and FullSkipWorkspaceDedup) remain conservative and report it as a duplicate.

This is deliberate. Making that rare incremental fallback independently exact would require CN-origin lineage, merge propagation, protobuf/opcode changes, and a rolling-upgrade protocol. This PR adds none of those steady-state costs or format changes.

Performance

  • No commit-TS storage read occurs without an exact primary-key match; this is covered by a regression test for fixed and varlen keys.
  • A candidate block performs at most one commit-TS read.
  • No extra column is written or propagated by flush/merge, and no on-disk or wire format changes.
  • Compared with current main, ordinary nonmatching scans keep the same zonemap/BF/PK path. The extra read is limited to an exact matching candidate where logical-time disambiguation is required.

Validation

  • TestDelete3 plus all fix(tae): align late aobject visibility with parent txn #26180 appendable-object visibility/rollback tests.
  • Incremental old-row rewrite, incremental concurrent-row rewrite, direct CN-created object, and strict old/concurrent rewrite tests.
  • Fixed and varlen PK tests for missing, short, null, lower-bound, lazy-load, cached-error, and ownership behavior.
  • Full tests for pkg/objectio, pkg/vm/engine/tae/tables, pkg/vm/engine/tae/txn/txnimpl, and pkg/vm/engine/tae/db/test.
  • Focused policy matrix passes -race -count=10; all four packages pass full -race.
  • CI-equivalent go vet -mod=readonly -tags matrixone_test -unsafeptr=false ./pkg/... passes.
  • git diff --check passes.

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

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Jul 25, 2026
@XuPeng-SH
XuPeng-SH force-pushed the fix/tae-delete-reinsert-dedup branch from c901a83 to 875588b Compare July 25, 2026 01:20
@XuPeng-SH XuPeng-SH changed the title fix(tae): preserve logical commit time in incremental dedup fix(tae): skip physical rewrites in incremental dedup Jul 25, 2026
@XuPeng-SH
XuPeng-SH force-pushed the fix/tae-delete-reinsert-dedup branch from 8b5c2df to 35b5180 Compare July 25, 2026 01:48
@XuPeng-SH XuPeng-SH changed the title fix(tae): skip physical rewrites in incremental dedup fix(tae): handle physical rewrites by dedup policy Jul 25, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

这轮 unhappy-path review 有 1 个高置信 blocker:

CheckIncremental 现在会直接跳过所有 当前 stats 显示 CNCreated=false 的 non-appendable object(pkg/vm/engine/tae/txn/txnimpl/base_table.go:251-263)。这个前提对“TN 原生 rewrite”成立,但对 CN-created object 被 TN merge/compaction 物理重写之后 不成立:

  • merge 选择会接受任意 active committed non-appendable object(pkg/vm/engine/tae/catalog/tableForMerge.go:253-266);
  • merge 产出的 replacement object 重新构造 stats 时先用 NewObjectStatsWithObjectID(..., false, sorted, false),再 SetObjectStats(pkg/vm/engine/tae/tables/jobs/mergeobjects.go:563-566);
  • SetObjectStats 只复制到 reservedOffset 之前,不会复制 reserved flag byte,而 CNCreated 就存在这个保留位里(pkg/objectio/object_stats.go:300-301);
  • 所以一个原本 CN-created 的 object 在 TN rewrite 之后会失去 CNCreated 标记,随后在 incremental dedup 里被 continue 掉,根本到不了后面的 GetDuplicatedRows 检查。

这不是理论路径:你新加的 TestIncrementalDedupChecksCNCreatedObject 已经证明 incremental dedup 对 CN-created object 本来就必须报 duplicate(pkg/vm/engine/tae/db/test/db_test.go:3859-3901)。当前缺的是“CN-created -> TN merge rewrite -> incremental dedup” 这条组合路径;现有新测试只覆盖了 TN-native rewrite 和 CN-created before rewrite,没覆盖这个 blocker。

建议修法:不要只根据 replacement object 当前的 CNCreated bit 决定 incremental fast path。要么在物理 rewrite 后保留逻辑上的 CN-origin,要么对这类 rewritten non-appendable object 在 CheckIncremental 下回退到按 row commit TS 过滤的严格检查;同时补一个针对 CN-created object after TN merge/compaction 的回归测试。

因为这是你的 PR,GitHub 不允许我直接 request changes,所以这里用 comment 代替阻塞 review。

@XuPeng-SH
XuPeng-SH force-pushed the fix/tae-delete-reinsert-dedup branch from 35b5180 to 2ec7844 Compare July 25, 2026 02:41
@XuPeng-SH
XuPeng-SH requested a review from LeftHandCold as a code owner July 25, 2026 02:41
@XuPeng-SH XuPeng-SH changed the title fix(tae): handle physical rewrites by dedup policy fix(tae): preserve logical origin across dedup rewrites Jul 25, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

已合理采纳 blocker comment,并补了能够在修复前稳定失败的真实组合测试。

确认的问题:direct CN-created object 被 TN mixed merge 后会失去 CNCreated,原 fast path 会把 replacement 当纯 TN rewrite 跳过,导致并发 CN 同 PK 被放过。

修复没有简单传播 CNCreated(那会让 mixed object 中的旧 TN 行重新误报),而是:

  • 新增持久化 CNOrigin lineage bit;
  • merge 从 direct CNCreated 或已有 CNOrigin 传播到 replacement;
  • CheckIncremental 仅对带 lineage 的 rewrite 使用行级 commit TS,纯 TN rewrite 仍直接跳过;
  • mixed merge 的所有输出保守带 lineage,但只有精确 PK 命中才懒加载 TS,每 block 最多一次。

新增测试使用真实 CN object + TN flush + mixed multi-output merge,修复前并发 CN case 稳定返回 nil;修复后验证:旧 TN PK 不误报、并发 CN PK 返回 WW、WAL restart 后标记仍在、第二次 merge 继续传播且旧 CN PK 不误报。

验证:边界矩阵 -race -count=10、相关包完整 race、build/vet、TestDelete3 -race -count=1000(315.051s)全部通过。修复提交:2ec78448be。

@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

The prior rolling-upgrade blocker is fixed: producers advertise the append-only lineage contract at the shared merge boundary, while TN validates authoritative catalog lineage before any catalog mutation and rejects legacy CN results. Earlier CN-merge metadata/commit-TS, legacy-null compatibility, and per-row output-lineage blockers remain fixed; the stale blanket-marking concern is withdrawn. No blocking or non-blocking defect remains. Protobuf compilation and diff checks passed; CGo tests could not run because libmo.dylib is absent.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Latest-head re-review on 24c25f23054197f99cc984be2c2d2a1832fedd03: I re-read the updated lineage fence path and rechecked the surrounding CN/TN merge, commit-ts, and incremental-dedup flow beyond the previously reported issues.

What I specifically rechecked this round:

  • latest legacy-CN lineage fencing in TN apply (MergeCommitEntry.lineage_version + validateMergeEntrySource)
  • CN merge producer lineage contract (DoMergeAndWrite / commit entry population)
  • mixed TN/CN rewrite behavior across restart and second-generation merges
  • legacy TN object commit-ts compatibility and the conservative null-commit-ts dedup path
  • cleanup / unhappy-path behavior when TN rejects a merge result

I also reran focused regressions covering:

  • TestCNMergeMaterializesAndPreservesRowCommitTS
  • TestCNMergeLegacyTNCommitTSCompatibility
  • TestCNMergeMarksOnlyOutputsContainingCNOriginRows
  • TestCNMergeSecondGenerationKeepsPureLegacyOutputUnmarked
  • TestValidateMergeEntrySourceLineageCompatibility
  • TestRejectLegacyCNMergeOfLineageSource
  • TestIncrementalDedupChecksCNRowsAfterMixedTNMerge

On the current head, I did not find a new high-confidence correctness / robustness / unhappy-path blocker. LGTM on this latest head from my side.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Latest-head correction: after cross-checking the new lineage fence against mixed-version behavior and the row-level incremental-dedup path, I do see two production-correctness blockers on the current head.

  1. The new lineage fence does not protect a rollout where CN upgrades before TN. A patched CN now emits MergeCommitEntry.lineage_version=1, but an old TN still accepts that payload and reconstructs created object stats via SetObjectStats, which does not preserve the reserved lineage flag byte. So a mixed-source merge sent from a new CN to an old TN can still silently drop CNOrigin, reintroducing the lineage-loss bug during a mixed-version rollout.

  2. CheckIncremental now false-rejects old TN rows once they live inside a CNOrigin object. The new path intentionally allows a mixed output object to contain legacy TN rows with null commit-ts and CN-origin rows with non-null commit-ts. But tables/obj.go routes every CNOrigin object through row-level commit-ts filtering, and tables/functions.go treats a missing commit-ts as an unconditional duplicate. That means an old TN row that should be skipped by DedupPolicy_CheckIncremental is now rejected simply because it shares a rewritten object with a CN-origin row.

So I would move this latest head back to blocked on correctness.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Latest re-review on the same head 24c25f23054197f99cc984be2c2d2a1832fedd03: I still see one same-version correctness blocker, plus one conditional rollout-compatibility concern.

  1. Same-version blocker: CheckIncremental can still false-reject an old TN row once that row lives inside a CNOrigin object. The current codebase itself now demonstrates both halves of this path:

    • disttae/merge_test.go proves a CN merge output can be a single CNOrigin object containing both a legacy TN row with null commit-ts and a CN-origin row with non-null commit-ts.
    • tables/functions_test.go codifies that missingCommitTS is treated as a conservative duplicate in the exact-PK path.
    • tables/obj.go routes every CNOrigin object through that row-level commit-ts filter under CheckIncremental.
      Put together, an old TN PK that should be skipped by DedupPolicy_CheckIncremental can still be rejected if it shares a mixed CNOrigin output with a CN row.
  2. Rollout-only concern: the lineage_version fence still matters only if a newer CN can send merge output to an older TN during a mixed-version rollout. If your deployment guarantees TN upgrades first (or otherwise prevents new-CN -> old-TN merge apply), then I would not count that one as a steady-state production blocker.

So my current latest-head conclusion is: still blocked on one deterministic same-version correctness issue; no new steady-state performance hotspot found in this pass.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Requesting changes on exact head 24c25f23 for two reachable data-correctness blockers.

  1. The lineage-version fence only closes old-CN -> new-TN. MatrixOne Operator reconciles DNSet and CNSet independently, so new-CN -> old-TN is reachable; the old TN ignores field 11 and strips CNOrigin through SetObjectStats, silently committing an unlineaged replacement.
  2. A patched CN intentionally preserves null commit TS for legacy TN rows in a mixed CNOrigin output, while incremental dedup treats any matching null-TS row as a duplicate. I reproduced the terminal deterministically: a row committed before txn start was physically rewritten afterward and Freeze returned Duplicate entry instead of ignoring it.

The prior same-version CN metadata/commit-TS paths and old-CN/new-TN pre-mutation rejection are fixed. I rechecked object/wire compatibility, per-output lineage across generations, restart behavior, hidden-column detection, validation ordering, vector ownership, and error cleanup; no third blocker found. Clean-head affected-package tests, focused DB regressions, focused race, vet, and diff-check pass, and the current GitHub required CI is green.

Comment thread pkg/vm/engine/tae/mergesort/task.go Resolved
Comment thread pkg/vm/engine/tae/tables/functions.go Resolved
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Reasonably adopted both latest blockers in 382b258470 and pushed the original PR branch.

  1. Same-version mixed CNOrigin false reject

    • CheckIncremental now skips only the canonical, correctly sized null commit-TS row representing legacy TN data.
    • strict dedup remains conservative; nil/short vectors remain conservative; non-null CN rows retain window/WW checks.
    • the DB regression now selects a legacy row physically co-located with the CN row in the same mixed output, so it failed before the fix instead of accidentally testing a pure-TN output.
  2. new-CN -> old-TN rolling upgrade

    • added protocol v5 as the TN merge-lineage capability; CN queries the actual target TN via the backward-compatible protocol-version endpoint.
    • shard and QueryAddress are selected from the same TN. Old/missing/malformed/unreachable TN capability fails closed.
    • capability is checked both before object generation and immediately before TN apply; a failed post-check cleans generated files. The old-CN -> new-TN pre-mutation lineage_version fence remains unchanged.

Performance/risk: no new DML hot-path I/O or allocation. Dedup adds one policy/null check only after an exact PK match. CN merge adds two small control-plane RPCs around a storage-heavy, low-frequency merge and deliberately does not cache rollout state.

Validation on final head:

  • full UT: queryservice/client, ctl, objectio, disttae, mergesort, tables, tables/jobs, txnimpl, DB integration
  • focused new regressions: -race -count=10
  • full affected-package vet/build and git diff --check
  • new capability helpers: 100% statement coverage; null-TS helper: 100%

I also re-read every prior issue/review thread: the earlier CN metadata, legacy hidden-column, per-output/per-row lineage, restart, and old-CN -> new-TN blockers remain covered on this head.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

One point I am still confident about on the latest head: there is one same-version, steady-state correctness blocker left in the CheckIncremental path.

The problematic combination is:

  • a rewritten output object is marked CNOrigin,
  • that object still contains some legacy TN rows whose row commit-ts is null,
  • CheckIncremental routes every CNOrigin object through row-level commit-ts filtering (pkg/vm/engine/tae/tables/obj.go),
  • and the exact-PK path treats missing commit-ts conservatively as a duplicate (pkg/vm/engine/tae/tables/functions.go).

So an old TN row that should be skipped by DedupPolicy_CheckIncremental can still be rejected once it shares a mixed CNOrigin output object with a CN-origin row. The mixed-object shape itself is already exercised by the current tests (TestCNMergeMaterializesAndPreservesRowCommitTS / TestCNMergeSecondGenerationKeepsPureLegacyOutputUnmarked / TestIncrementalDedupChecksCNRowsAfterMixedTNMerge), so this is not just a hypothetical shape mismatch.

Separately: the earlier lineage_version concern is only a rollout-compatibility issue if a newer CN can send merge output to an older TN during a mixed-version window. I would not treat that one as a steady-state blocker if deployment guarantees TN-first upgrade.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Rechecked this latest comment against exact head 382b258470; its key premise is stale on the current code, so no additional production change is appropriate.

The exact-PK paths no longer treat a valid legacy null commit TS as an unconditional duplicate:

  • varlen: functions.go:333-336 calls skipLegacyTNRow before constructing a duplicate row ID;
  • fixed-size: functions.go:387-390 does the same;
  • skipLegacyTNRow requires all three conditions: SkipTargetOldCommitted, a present/in-range TS vector, and a null row. Thus CheckIncremental skips the legacy TN row, while strict policy and malformed nil/short vectors remain conservative.

The DB regression is also the exact mixed-object terminal, not merely a shape test: TestIncrementalDedupChecksCNRowsAfterMixedTNMerge now chooses legacy TN row 30 because it lands in the same mixed CNOrigin output as the CN row. It then asserts:

  • old legacy key: oldTxn.GetStore().Freeze(ctx) succeeds (db_test.go:4087-4089);
  • concurrent CN key: Freeze returns ErrTxnWWConflict (db_test.go:4091-4094).

I reran the fixed/varlen policy matrix, malformed-vector boundary, and this real mixed-object DB regression at -count=10 on exact head; all pass. Adding another provenance field or guard here would duplicate the implemented policy split and increase risk without closing a remaining path.

The rollout direction mentioned separately is also already closed on this head by the TN-advertised protocol-v5 pre/post capability checks; it is independent of this same-version conclusion.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

You were right to push on “latest”. I re-reviewed the actual current head 382b258470738e1f98c21094bdcd35b7667f5787 together with the latest reply thread, not the older 24c25f23 head.

On this current head, the two latest concerns I raised look closed:

  1. Same-version mixed CNOrigin false reject

    • exact-PK dedup no longer treats a canonical legacy null commit-ts row as an unconditional duplicate;
    • skipLegacyTNRow now skips that row only under SkipTargetOldCommitted / CheckIncremental, while strict and malformed nil/short-vector states remain conservative;
    • the DB regression was also corrected to choose a TN row physically colocated with the CN row inside the mixed CNOrigin output, and it now asserts the intended split: old TN key passes, concurrent CN key conflicts.
  2. new-CN -> old-TN rollout direction

    • CN now checks the target TN's protocol capability before object generation and again immediately before TN apply;
    • old/missing/malformed/unreachable TN capability fails closed, and the second check cleans generated files before returning.

I also reran the focused new tests and the full affected package set on this exact head (queryservice/client, ctl, disttae, tae/mergesort, tae/tables, tae/tables/jobs, tae/txn/txnimpl, tae/db/test). I do not currently see a remaining high-confidence correctness / robustness / unhappy-path blocker on the latest head.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

One more latest-head note after reading the full current head 382b258470738e1f98c21094bdcd35b7667f5787 and the newest reply thread carefully: the earlier same-version mixed-CNOrigin blocker does look fixed now, but I still see one rollout-only compatibility gap left.

The current fix is still probe-only, not bound to the apply contract itself:

  • handleCNMerge checks TN capability before object generation and again right before txnWrite (pkg/sql/plan/function/ctl/cmd_merge.go:210-245);
  • but the actual OpCommitMerge request sent by txnWrite carries no enforced minimum capability/version (pkg/sql/plan/function/ctl/cmd_merge.go:459-469);
  • and the TN apply path HandleCommitMerge still applies the merge directly without rechecking protocol capability on the receiver side (pkg/vm/engine/tae/rpc/handle_debug.go:1022-1068).

That leaves a TOCTOU window during rollout: if the probed TN is replaced/rolled back after the second probe but before the write is actually applied, an older TN can still accept the merge. The transport path itself also documents that the TN address may need refresh when sending (pkg/txn/rpc/sender.go:259-261), so the probe result is not a receiver-enforced guarantee.

So my latest read is:

  • same-version steady-state path: looks good on this head;
  • rolling-upgrade / rollback window: still safer to close by making compatibility part of the apply contract itself (for example, receiver-side gating in OpCommitMerge / HandleCommitMerge, not only separate preflight probes).

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

Blocking review

[P1] Bind the TN lineage capability to the actual OpCommitMerge apply.

The two capability probes in handleCNMerge are separate from the write they authorize. After the second probe and before txnWrite is applied, the selected TN can be replaced or rolled back. The request itself still uses the legacy OpCommitMerge contract and carries no receiver-enforced minimum protocol version. An old TN therefore accepts it, ignores the unknown lineage_version field, and reconstructs output catalog stats through the old SetObjectStats path, which drops the reserved-byte CNOrigin flag. The replacement is then indistinguishable from a pure TN rewrite and can be skipped by CheckIncremental, reintroducing a duplicate false negative.

Please make compatibility part of the apply contract itself—for example, a v5-only command/opcode, transport-level minimum version, or an epoch/capability token atomically validated by the receiver. Add a deterministic regression that swaps the target to an old TN between the final probe and apply, and verifies both no catalog mutation and cleanup of generated files.

The same-version mixed-lineage, legacy-null commit-TS, per-output propagation, and old-CN -> new-TN paths otherwise look closed on head 382b258470738e1f98c21094bdcd35b7667f5787. Focused race tests, full affected-package tests, and git diff --check passed locally. The failed Compose job is an unrelated Docker Hub image-pull timeout.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Deep review on exact head 382b258470738e1f98c21094bdcd35b7667f5787: still blocked.

The newest aptend review is valid, and the current CI exposes a stronger same-version failure in the same design:

  1. Same-version standalone CN merge is disabled.

    • tnservice.initQueryService(true) deliberately sets the TN query service to nil.
    • The TN heartbeat consequently advertises an empty QueryAddress.
    • validateTNMergeTarget rejects that normal topology before merge generation.
    • Both standalone BVT jobs reproduce this deterministically: every mo_ctl_merge.test merge returns not supported: CN merge requires a TN with row-lineage capability (14 failed assertions in each job).
  2. The separate probes still do not bind capability to the actual apply.
    The final probe and OpCommitMerge can reach different TN generations. The legacy opcode carries no receiver-enforced minimum capability, so an old TN can still accept the result after a replacement or rollback. This is the TOCTOU gap identified by aptend.

A minimal systemic closure is to make the apply operation itself versioned:

  • introduce a new OpCommitMergeV2 opcode for the lineage-preserving contract;
  • make new CNs send V2 and new TNs handle V2 through the current pre-mutation lineage validation;
  • old TNs already fail closed on unknown write opcodes, so no QueryAddress probe, extra control-plane RPC, cache, or race window is needed;
  • retain V1 only for old-CN -> new-TN compatibility, where the existing lineage_version source validation rejects unsafe CN-origin rewrites before catalog mutation.

Please add integration coverage for same-version standalone success, new-CN -> old-TN V2 rejection, target replacement between generation and apply, zero catalog mutation, and generated-file cleanup after a definitive compatibility rejection. The helper-only ctl tests currently miss all of these terminals.

The core lineage/dedup path otherwise looks sound in this pass: per-output/per-row propagation, legacy null commit TS, strict/incremental behavior, second-generation rewrite, vector ownership, and pre-mutation old-CN rejection all passed fresh affected-package tests, focused race, and DB regressions. The Compose failure is unrelated (Docker Hub image metadata timeout).

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Requesting changes on exact head 382b258470 for one reachable data-correctness blocker.

The two GetProtocolVersion probes are not the apply-time fence. After the second probe, rpc.sender.doSend retries ErrNoAvailableBackend, ErrBackendCannotConnect, and ErrBackendClosed against the same TN address for up to 30 seconds. During a normal TN replacement/rollback, the v5 TN can answer the probe, the first write can hit the closed backend, and the retry can reach the old TN after it comes up at that stable address. The request still uses legacy OpCommitMerge; the old receiver accepts it, ignores lineage_version, and reconstructs stats through old SetObjectStats, dropping CNOrigin. CheckIncremental can then skip the replacement and miss a real duplicate.

Please make the actual apply self-fencing, e.g. use a v5-only merge opcode that an old TN rejects. Keep the probe if desired for early failure and generated-file cleanup, and add a deterministic backend-replacement regression around the final probe/apply boundary.

The legacy-null row handling, old-CN -> new-TN validation, same-version mixed lineage, per-output propagation, restart persistence, and cleanup on the second-probe failure are otherwise closed. Affected-package tests, focused DB correctness regressions, vet, and git diff --check pass; I found no second blocker.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Updated original branch at fc5c1dc to adopt the latest P1 without retaining the probe workaround.

Key outcome: compatibility is enforced atomically by OpCommitMergeV2 at TN apply. Old TNs fail before mutation; current TNs accept V1/V2; standalone no longer needs TN QueryAddress. MORPCVersion5 and both capability RPCs are removed. Definitive compatibility rejection cleans generated files; ambiguous transport failures preserve them.

Production scope checked: automatic background merge currently runs TN-local; CN merge remains a real mo_ctl/task-executor operational path, but there is no current in-repo production creator for TaskCode_MergeObject. Operator CNSet/DNSet rollout is independent, so the short new-CN -> old-TN window is real even though the trigger is low frequency. This patch protects exactly that correctness boundary without adding global state, tables, caches, or hot-path I/O.

Fresh validation: all 10 affected packages, 90s DB integration suite, focused race, affected build/vet, mo-service build, protobuf regeneration, and git diff --check.

Resolve the db_test overlap with matrixorigin#26180 and harden incremental dedup to filter TN rewrites lazily by row commit timestamp, preserve the best-effort legacy fallback, and release result vectors on error.
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Updated the existing branch to latest main and resolved the db_test.go overlap with #26180 in commit acfca9c05c.

The deep review changed the implementation direction from a blanket TN-object skip to lazy row-time filtering:

  • TN rewrites with commit-TS metadata now ignore old rows but still detect a genuinely concurrent row after TN flush. Both CheckIncremental and strict policies have deterministic coverage.
  • Commit-TS is loaded only after zonemap/BF pruning and an exact PK match, at most once per candidate block. A dedicated fixed/varlen test asserts that a nonmatching PK performs zero commit-TS loads.
  • Missing/null metadata is policy-aware: incremental remains best-effort and skips the unverifiable row; strict policies remain conservative.
  • Errors from the lazy metadata read now close and nil the pooled rowIDs result before returning; a regression test checks that no vector-pool slot remains in use.

Intentional boundary for reviewers: a TN rewrite containing CN-created rows can inherit null row timestamps. Making CheckIncremental independently exact for that rare path would require the lineage/protobuf/opcode/upgrade protocol that this PR intentionally avoids. Production correctness for incremental mode remains the PK-lock + PrimaryKeysMayBeModified recheck contract; callers requiring standalone strict TN dedup must use CheckAll.

Local final evidence: related package tests PASS, focused -race -count=10 PASS, full related-package -race PASS, CI-equivalent full go vet PASS, and git diff --check PASS.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

@LeftHandCold @aptend @gouhongshen please help to review

@jiangxinmeng1 jiangxinmeng1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I found one blocker in the current head:

[P1] Release the LoadColumns2 result after reading commit timestamps

loadPersistedCommitTS discards the release callback returned by
ioutil.LoadColumns2:

vectors, _, err := ioutil.LoadColumns2(...)

With needCopy=false, the returned vectors reference IOVector.CachedData; calling
containers.Vector.Close() does not release that cached-data reference.
Consequently, every exact-PK candidate block can leak file-service cache data.
This PR expands the loader from appendable objects to incremental dedup over TN-
rewritten non-appendable objects, making the leak reachable repeatedly in the
normal precommit path and potentially causing unbounded memory growth.

Please retain the callback and invoke it when commitTSLoader.close() runs,
including validation-error paths, or load an owned copy and release the IOVector
immediately. The current mpool-based ownership tests do not detect this leak
because the retained memory belongs to the file-service cache allocation, not the
vector mpool.

Location: pkg/vm/engine/tae/tables/base.go:176 at head
acfca9c.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Thanks for calling out the ownership boundary. I double-checked the full lifecycle.

The current call passes needCopy=true (not false). In that mode, LoadColumnsData2:

  1. clones the decoded column into the transient vector pool;
  2. releases the source IOVector, including its CachedData, in the return defer;
  3. intentionally returns a nil release callback because the caller owns the cloned vector.

The cloned commit-TS vector is closed by commitTSLoader.close; malformed layouts are also closed by validatePersistedCommitTSVectors.

I adopted the actionable part of the review in commit 29e7b0e040:

  • replaced the ambiguous comment with the explicit ownership contract;
  • added TestLoadColumns2NeedCopyReleasesSourceCachedData, which wraps every returned CachedData, tracks retain/release balance, proves the tracking hook ran, and asserts that the source balance is already zero when LoadColumns2(..., needCopy=true, ...) returns.

This does not add another callback or any production-path work, so there is no runtime performance change.

Validation:

  • focused test: pass
  • ./pkg/objectio/ioutil ./pkg/vm/engine/tae/tables: pass
  • the same packages with -race: pass
  • full make static-check: pass (0 issues)

@ck89119

ck89119 commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Deep review completed on exact head 29e7b0e040d35e4233cfdda21511bdf6b50943ad against base d372ca22dd9eeb90ac7928bbdd450a30aac6085f.

Verdict: I found no new code-level blocker on this head.

I rechecked the full current diff and the relevant end-to-end contracts: hidden commit-TS detection, user T_TS column disambiguation, inclusive timestamp-window boundaries, fixed and varlen PK paths, TN-rewritten versus direct CN-created objects, missing/null metadata policy, legacy compatibility, error ownership, CachedData/vector lifetime, and the one-load-per-candidate-block bound.

The latest P1 review is based on needCopy=false, but the actual loadPersistedCommitTS call uses needCopy=true. In that mode, LoadColumnsData2 clones the decoded vector into the transient pool and releases the source IOVector, including its CachedData, before returning. The cloned vector is then owned and closed by commitTSLoader.close(); malformed layouts are also closed by validation. The new CachedData retain/release regression and my independent race run both pass, so I could not reproduce the reported leak.

I also traced the explicit missing/null commit-TS fallback through the production policy/configuration path. Incremental dedup's skip is a deliberate best-effort fallback under the default pessimistic PK-lock plus PrimaryKeysMayBeModified recheck contract, while strict policies remain conservative. I found no new unprotected production path within the stated scope.

Independent validation completed successfully:

  • Full tests for pkg/objectio, pkg/objectio/ioutil, pkg/vm/engine/tae/tables, and pkg/vm/engine/tae/txn/txnimpl.
  • Targeted DB tests covering old-row TN rewrites, direct CN-created objects, strict policy behavior, concurrent rows after TN rewrite, and TestDelete3.
  • Targeted -race tests covering commit-TS loading/caching/bounds, missing metadata policy, source CachedData release, validation cleanup, and error-result ownership.
  • git diff --check.

Code verdict for this exact head: no blocker found. CI completion and stale historical CHANGES_REQUESTED reviews remain separate merge-state concerns.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Requesting changes on exact head 29e7b0e040 for one reachable data-correctness regression.

CheckIncremental now skips an exact-PK match whenever the rewritten object has no row commit timestamp. The PR description treats the TN check as lock-backed best effort, which is valid for the default pessimistic path, but MatrixOne explicitly accepts txn.mode=Optimistic with incremental-dedup=true; that path has no LockOp/PrimaryKeysMayBeModified boundary and TN still selects DedupPolicy_CheckIncremental. CN merge produces exactly the problematic object shape: its writer uses only the table user seqnums, while the applied replacement is non-appendable and no longer CNCreated.

I reproduced this with the real object/catalog/Freeze path and compared the same test across commits: base d372ca22dd rejects the post-snapshot duplicate (DuplicateEntry), while head 29e7b0e040 returns nil and permits it. Please either keep missing commit-TS rows conservative outside a proven lock-backed mode, reject the optimistic+incremental configuration, or make CN merge outputs carry a trustworthy row timestamp.

The latest needCopy=true ownership path is correct: the source IOVector/CachedData is released before return, and the copied vector is closed by the block-scoped loader. Full affected-package UTs, focused race -count=3, build, vet, and diff checks pass. I found no second blocker.

// upgrades. Strict policies stay conservative. This avoids
// adding lineage or an upgrade protocol to every merge.
if missingCommitTS(tsVec, row) {
if txn.GetDedupType().SkipTargetOldCommitted() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] Do not skip missing commit-TS rows for every CheckIncremental transaction. This assumes a pessimistic LockOp always provides the correctness boundary, but txn.mode=Optimistic plus explicit incremental-dedup=true is accepted by config; that mode has no LockOp, while HandleWrite still selects DedupPolicy_CheckIncremental. CN merge writes only user host.seqnums, so its replacement is non-appendable, CNCreated=false, and lacks this hidden column, making an exact post-snapshot duplicate reach this return nil.

I reproduced this on exact head through real object/catalog/Freeze code. With a transaction started first and a matching CN-merge-shaped object committed afterward, base d372ca22dd returns DuplicateEntry, but head 29e7b0e040 returns nil. Keep missing timestamps conservative unless lock/recheck protection is proven, reject optimistic+incremental at configuration time, or persist a trustworthy timestamp in CN merge output. The fixed-size branch below needs the same correction.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the concrete reproduction. The reproduced behavior is technically valid for the constructed configuration, but it is outside the supported production scope of this PR.

The Optimistic BVT/path has been deprecated. Current production uses the pessimistic transaction path, where incremental dedup is protected by the PK LockOp plus PrimaryKeysMayBeModified recheck contract. In addition, TN configuration already defaults incremental-dedup to false when txn.mode=Optimistic; the reproduction therefore requires explicitly enabling a non-default combination on a deprecated mode.

We should not add lineage/object-format/upgrade machinery, nor make every missing commit-TS row conservative, solely to support that deprecated combination. Either change would add complexity or cost to the supported production path and work against the deliberate best-effort scope of incremental dedup.

So I agree that the test demonstrates a formal hole in the still-accepted legacy configuration surface, but I do not consider it a production P1 or a blocker for this PR. Cleanup of the deprecated Optimistic configuration surface can be handled separately if needed.

@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

The previous approval is no longer valid because the implementation changed after 24c25f2. The earlier lineage/rolling-upgrade and mixed-CNOrigin blockers were fixed in intermediate commits, then made obsolete when that design was removed. The reported CachedData leak is withdrawn: needCopy=true releases the source IOVector and the copied vector is closed correctly. One current P1 remains unresolved: optimistic mode with incremental dedup can skip a post-snapshot duplicate when commit-TS is missing. LeftHandCold already raised it on this exact head, so it is not duplicated below. I found no additional defects in the new review surface. The merge conflict resolution was test-only; upstream merge changes were excluded. git diff --check passed; focused tests could not start because cgo/libmo.dylib is absent.

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

size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: TAE incremental dedup treats rewritten rows as concurrent inserts

7 participants