Skip to content

fix table clone visibility for repeated alter - #24987

Merged
mergify[bot] merged 15 commits into
matrixorigin:mainfrom
gouhongshen:codex/issue-24762-main
Jun 25, 2026
Merged

mergify[bot] merged 15 commits into
matrixorigin:mainfrom
gouhongshen:codex/issue-24762-main

Conversation

@gouhongshen

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

fixes #24762

What this PR does / why we need it:

Repeated ALTER TABLE statements in one transaction can clone from a table or hidden index table that was produced by an earlier ALTER in the same transaction. The old TableMetaReader only read the committed partition snapshot and constructed the local reader without the current transaction write offset, so the second clone could miss uncommitted object stats from the first clone. The base table data remained visible, but secondary index data could be missing after commit.

This PR keeps the clone path and makes the clone source reader transaction-visible:

  • capture the TableMetaReader transaction write offset
  • include uncommitted data and tombstone object stats when collecting clone metadata
  • use NewLocalDataSource with the same txnOffset for appendable/in-memory clone reads
  • include row-level uncommitted tombstones when collecting tombstone rows
  • reuse a common helper for collecting uncommitted data/tombstone object stats

It also extends git4data clone BVT coverage with repeated ALTER cases, including a stress case with secondary, unique, fulltext, and ivfflat vector indexes plus multiple ALTER operations in one transaction.

Validation:

  • make build
  • clone_in_alter_table_2: 81/81 passed
  • git4data/clone: 1177/1177 passed
  • full git4data: 4403/4403 passed
  • git diff --check

@gouhongshen
gouhongshen requested a review from XuPeng-SH June 18, 2026 07:00

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

I re-checked the latest head. The original rollback-GC leak I raised is fixed, but there is still one remaining high-severity cleanup window in the commit path.

pkg/vm/engine/disttae/txn.go:2005-2008 now defers txn.delTransaction() only when txn.Commit() returns err == nil. That preserves the workspace for failures inside CN-side commit preparation. But once workspace.Commit() succeeds, the outer txn operator has not actually committed yet — it still has to validate, build/send the commit request, and process the response.

In pkg/txn/client/operator.go:1113-1180, after workspace.Commit() succeeds, later failures from validate, doSend, or commit response handling just bubble out of the commit path. They do not call workspace.Rollback(). At that point txn.delTransaction() has already run, which deletes the clone txn cache in pkg/vm/engine/disttae/txn.go:2188-2190.

That means clone-related txn-local source/data/tombstone files can still lose their local GC/bookkeeping path if commit fails after workspace.Commit() but before the outer commit actually succeeds. So the leak window is narrower than before, but not closed.

Concrete suggestions

  1. Keep clone/workspace cleanup state alive until the txn operator knows the commit RPC has definitively succeeded, not merely until workspace.Commit() finishes building payload.
  2. If you want to keep Transaction.Commit() as a pure "prepare payload" step, then move the clone-cache deletion / final workspace teardown to the operator’s post-commit-success path instead of the workspace commit path.
  3. Alternatively, add an explicit post-workspace.Commit() failure cleanup path in the operator for any later commit failure (validate, doSend, response handling), so the clone GC logic still runs on those failures.
  4. Add one focused regression test for the exact window: inject a failure after workspace.Commit() succeeds but before commit RPC completion, then assert clone source/data/tombstone files are still cleaned up.

Non-blocking remaining coverage gap

  • I still do not see a direct test for same-txn row-level DELETE tombstone propagation across repeated ALTER/clone (BEGIN; DELETE; ALTER; ALTER; COMMIT; plus base-table and index-backed visibility checks).

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

I re-checked the latest head. The previous post-workspace-commit cleanup window is fixed now, but I still see one remaining high-severity issue in the snapshot-clone path.

TableMetaReader.addCloneSharedFile() still records clone source/object protection under r.table.db.getTxn().op.Txn().ID, i.e. the source reader's transaction ID.

That is fine when source and destination share the same txn, but not in the snapshot-clone flow:

  • table_clone marks only proc.GetTxnOperator().GetWorkspace() as clone-aware
  • when ScanSnapshot.TS is set, it opens the source side on proc.GetCloneTxnOperator()
  • rollback GC later consults cloneTxnCache using the destination workspace txn ID

So in snapshot-based clone, shared/txn-local shared files can be recorded under the source snapshot txn ID while rollback GC checks the destination txn ID. In that case the clone cache protection is invisible to GC, and source objects referenced by the cloned metadata can still be deleted on rollback.

Concrete suggestions

  1. Record clone shared / txn-local-shared files against the destination clone-workspace txn ID that rollback GC actually uses, not the source snapshot reader txn ID.
  2. If that ID is not directly reachable from TableMetaReader, thread it in explicitly when building the reader for clone flows.
  3. Add one focused regression test for snapshot clone specifically (not same-txn clone): source opened through CloneSnapshotOp, destination clone txn rolls back, and shared source objects are still protected from GC.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH I checked this against current head 2417e64e8ca1d9690462bb7f78354003d859125b, and I don't think the snapshot-clone cache-key mismatch exists.

The key point is that CloneSnapshotOp creates a separate snapshot workspace, but it does not create a separate txn ID:

  • pkg/txn/client/operator.go:578-588: the child snapshot operator sets op.mu.txn.ID = tc.mu.txn.ID, then op.reset.txnID = op.mu.txn.ID.
  • pkg/sql/colexec/table_clone/table_clone.go:230-231: table_clone marks the destination workspace clone-aware under proc.GetTxnOperator().Txn().ID via SetCloneTxn.
  • pkg/sql/colexec/table_clone/table_clone.go:263-265: the snapshot source reader is opened through proc.GetTxnOperator().CloneSnapshotOp(...), whose txn ID is copied from that same parent txn.
  • pkg/vm/engine/disttae/table_meta_reader.go:78-88: addCloneSharedFile() records under the source reader txn ID, which is therefore the same byte ID as the destination workspace txn ID.
  • pkg/vm/engine/disttae/types.go:834-843: rollback GC checks cloneTxnCache using txn.op.Txn().ID, so it consults the same cache key.

So the source snapshot operator has a separate snapshot timestamp/workspace, but not a distinct transaction ID. The shared-file protection is recorded and later checked under the same txn ID in this path.

I also reran the focused clone-GC tests after initializing the local MO env:

go test ./pkg/vm/engine/disttae -run 'TestTableMetaReaderRecordsCloneObjectOwnership|TestCloneTxnIntermediateGCKeepsTxnLocalSharedObjects|TestCloneTxnRollbackGCDeletesTxnLocalSharedObjects' -count=1
ok  github.com/matrixorigin/matrixone/pkg/vm/engine/disttae  1.357s

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

I re-checked this PR from a correctness / unhappy-path angle. The repeated-ALTER visibility fix looks reasonable, but I think there is still one real resource-management regression in the clone/txn-local shared-file lifecycle.

Blocker: txn-local shared clone files can leak after later in-transaction DELETE/compaction

Once a clone step marks a txn-local object as shared, that object name stays in txnLocalSharedFiles for the rest of the transaction.

That becomes a problem in this mixed path:

  1. clone/alter reads a txn-local persisted object and marks it via AddTxnLocalSharedFile(...)
  2. the same transaction later deletes rows from that flushed object (deletedBlocks path)
  3. pre-commit compaction rewrites the object and tries to GC the old file
  4. intermediate clone GC now skips that old file because it is still marked txn-local-shared
  5. the original write entry is then nulled out, and successful commit never revisits the skipped file

So the superseded object is orphaned permanently in object storage.

Evidence

  • TableMetaReader marks txn-local source objects with AddTxnLocalSharedFile(...).
  • gcFiles(... cloneGCIntermediate ...) filters out any txnLocalSharedFile.
  • delete-on-txn-uncommitted-persisted objects are tracked in deletedBlocks.
  • compactDeletionOnObjsLocked rewrites dirty objects, clears the original write batch (txn.writes[i].bat = nil), then calls GCObjsByStats(dirtyObject...).
  • FinalizeCommit only drops txn state/cache; it does not do a second GC pass for those skipped old files.

Suggested fix

  • Remove a file from txnLocalSharedFiles once a later step rewrites/supersedes it (for example in compactDeletionOnObjsLocked before GCObjsByStats), or
  • replace the current add-only flag with a more precise liveness/reference model.

Please also add a regression test for a mixed transaction like:
INSERT (force flush) -> DELETE -> ALTER TABLE ... -> COMMIT

Because this can leak superseded CN-created objects on a valid transaction path, I think this should be changes requested before merge.

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

I re-checked the latest head. The snapshot-clone shared-file ownership issue I raised last time looks addressed, but I still see one remaining GC hole in the dropped-table cleanup path.

When tablesInVain is processed in txn.mergeTxnWorkspaceLocked(), each affected write entry is GC'd through GCObjsByIdxRange(i, i) before the batch is cleared. But that path still uses the intermediate clone-GC rules, which explicitly preserve any object still marked as txnLocalShared.

The problem is that the new unprotectUnreferencedTxnLocalSharedFilesLocked(...) helper only runs from the compaction path. It is not run before this tablesInVain cleanup. So if a clone/ALTER chain has marked an older workspace object as txnLocalShared, and then the table is dropped/truncated in the same transaction, GCObjsByIdxRange(i, i) can skip deleting that object, the write gets nulled, and the file becomes orphaned.

You can see the pieces in the current head:

  • txn.go:1548-1557 GC's tablesInVain entries via GCObjsByIdxRange(i, i) and then clears the batch
  • types.go:834-843 preserves txnLocalSharedFiles during cloneGCIntermediate
  • txn.go:1881-1904 only removes unreferenced txn-local shared protection in the compaction path
  • txn.delTransaction() later just drops the cache entry; it does not come back and delete any skipped object files

Concrete suggestions

  1. Before GC-ing tablesInVain entries, remove txn-local shared protection for files that no longer have any live object-stats references.
  2. Or, run this dropped-table cleanup with a final-GC scope that does not preserve txnLocalSharedFiles.
  3. Add one focused regression test for: clone/ALTER creates txn-local shared object -> table is dropped/truncated in the same txn -> object file is actually deleted and not orphaned.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked the newest head. The latest delta does fix the dropped-table tablesInVain txn-local-shared cleanup path, but the earlier ErrTxnUnknown blocker I raised is still unresolved.

pkg/txn/client/operator.go still routes ambiguous commit outcomes to workspace.FinalizeCommitWithUnknownResult(...), and disttae.Transaction still implements that as delTransaction(). That means an ambiguous commit result can still discard the workspace/object-stat metadata before any later abort/rollback cleanup has a chance to inspect it and GC flushed CN-created objects.

So my review status stays at request changes until the ErrTxnUnknown path preserves enough state for a later abort/rollback cleanup (or is otherwise made safe).

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Fixed in 1302a1389378a77aeac40767ac171384baf21a92.

I re-checked the ErrTxnUnknown path and agree the ambiguous commit outcome must not discard clone workspace/object-stat state. The fix changes the prepared-workspace unknown-result finalization to preserve that state: if the txn is later determined aborted, rollback cleanup can still GC txn-local CN-created objects; if it actually committed, we also avoid running normal rollback GC against committed objects.

Also synced the same fix to 4.0-dev in c12b21bfcbd35eab6198bd6856b95de9f2002227.

Verified with:

  • go test ./pkg/txn/client -run 'TestCommitKeepsPreparedWorkspaceAfterTxnUnknown|TestCommitFinalizesPreparedWorkspaceAfterCommitSuccess|TestCommitRollsBackPreparedWorkspaceAfterCommitSendError' -count=1
  • go test ./pkg/vm/engine/disttae -run 'TestCloneTxnUnknownCommitPreservesRollbackCleanup|TestCloneTxn|TestTableMetaReader' -count=1

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

I re-checked the newest head. The operator-local ErrTxnUnknown handling is improved now, but the end-to-end frontend commit path still drops the only live txnOp reference before any later abort/rollback cleanup can use the preserved workspace metadata.

Concretely:

  • txnOperator.doWrite() now preserves workspace state for ErrTxnUnknown by calling FinalizeCommitWithUnknownResult(...) instead of rollback.
  • But TxnHandler.commitUnsafe() still calls th.invalidateTxnUnsafe() on any commit error.
  • The normal error path above it then goes through rollbackTxnFunc(), but rollbackUnsafe() immediately returns when there is no active txn / no live txnOp.

So if a commit returns ErrTxnUnknown, the metadata is preserved inside the workspace, but the frontend has already discarded the txn operator before any later rollback/abort decision can actually invoke cleanup. In practice that strands the preserved object-stat metadata and leaves the original ambiguous-commit GC issue unresolved in the real frontend flow.

Concrete suggestions

  1. Keep the txn operator reachable across ErrTxnUnknown until a later status resolution / rollback decision is made.
  2. Or add an explicit ambiguous-commit resolution path in frontend txn handling that can invoke cleanup only after the txn is confirmed aborted.
  3. Add one focused regression test at the frontend/TxnHandler layer for ErrTxnUnknown: commit returns unknown, later path decides to abort, and flushed CN objects are still discoverable for cleanup through the real lifecycle.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Fixed in 29a58d71feffdf87028f56da243b6f2938f4f5f8.

I re-checked the frontend lifecycle and this was a valid gap: commitUnsafe() invalidated txnOp on ErrTxnUnknown, and the subsequent error path could no longer reach the preserved workspace metadata. The fix treats ErrTxnUnknown as an ambiguous commit outcome instead of a normal rollback error:

  • commitUnsafe() keeps the txn operator reachable on ErrTxnUnknown.
  • rollbackTxnFunc() does not run the normal rollback path for ErrTxnUnknown, so we do not reintroduce the unsafe rollback-GC path while the commit may already have succeeded.
  • Added frontend coverage for finishTxnFunc -> commit ErrTxnUnknown -> rollbackTxnFunc, asserting rollback is not called and the txn operator remains reachable.

Synced the same fix to the 4.0-dev PR in a006b953fbad191e10b4119d8fb6f83ee6496d3b.

Verified with:

  • go test ./pkg/frontend -run 'TestCommitTxnUnknownPreservesTxnOperatorForLaterCleanup|Test_commit|Test_isErrorRollbackWholeTxn' -count=1
  • go test ./pkg/txn/client -run 'TestCommitKeepsPreparedWorkspaceAfterTxnUnknown|TestCommitFinalizesPreparedWorkspaceAfterCommitSuccess|TestCommitRollsBackPreparedWorkspaceAfterCommitSendError' -count=1
  • go test ./pkg/vm/engine/disttae -run 'TestCloneTxnUnknownCommitPreservesRollbackCleanup|TestCloneTxn|TestTableMetaReader' -count=1

@XuPeng-SH

Copy link
Copy Markdown
Contributor

Another high-signal issue I confirmed on the newest head:

FinalizeCommitWithUnknownResult() is currently a complete no-op for CCPR transactions. That means an ErrTxnUnknown commit path never calls either ccprTxnCache.OnTxnCommit() or ccprTxnCache.OnTxnRollback(), so the txn ID is never removed from ccprTxnCache.

You can see the lifecycle mismatch here:

  • txn.go:2143-2147 calls OnTxnCommit() only on the definite-success path
  • txn.go:2150-2154 does nothing on the unknown-result path
  • ccpr_txn_cache.go:180-205 / 211-246 show OnTxnCommit() / OnTxnRollback() are the only places that remove the txn from txnIndex / items
  • CCPR is a real production path (pkg/publication/iteration.go:1208-1212)

So an ambiguous commit can leave stale CCPR cache entries behind indefinitely. Later transactions that touch the same shared object name can then see extra txnIDs and incorrectly skip rollback GC.

Suggested fix: add an "unknown-result" CCPR cleanup path that removes the txn ID from ccprTxnCache without deleting the object, and invoke it from FinalizeCommitWithUnknownResult().

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Fixed the CCPR unknown-result cleanup issue in 4ec9cbac3486e381ec2e0bce539c5ebd57889b85.

This was a valid lifecycle gap. FinalizeCommitWithUnknownResult() intentionally must not run normal rollback cleanup or delTransaction(), because the commit may already have succeeded and rollback GC could delete committed objects. But CCPR also needs to remove its txn cache tracking on the unknown-result path.

The fix adds CCPRTxnCache.OnTxnUnknownResult(...) and calls it from Transaction.FinalizeCommitWithUnknownResult() for CCPR txns. That path removes the affected CCPR cache tracking and txn indexes without deleting object files, so it does not violate the ambiguous-commit safety rule and does not leave stale CCPR txn IDs behind.

Synced to 4.0-dev in 7a339d16152851f9e3c03fe4cb26eb274278d48e.

Verified with:

  • go test ./pkg/vm/engine/disttae -run 'TestCCPRTxnCache_OnTxnUnknownResultRemovesTrackingWithoutGC|TestTransactionFinalizeCommitUnknownCleansCCPRCache|TestCCPRTxnCache_OnTxnRollback_NonExistent|TestCCPRTxnCache_Rollback_MultiTxn|TestCloneTxnUnknownCommitPreservesRollbackCleanup|TestCloneTxn|TestTableMetaReader' -count=1
  • go test ./pkg/txn/client -run 'TestCommitKeepsPreparedWorkspaceAfterTxnUnknown|TestCommitFinalizesPreparedWorkspaceAfterCommitSuccess|TestCommitRollsBackPreparedWorkspaceAfterCommitSendError' -count=1
  • go test ./pkg/frontend -run 'TestCommitTxnUnknownPreservesTxnOperatorForLaterCleanup|Test_commit|Test_isErrorRollbackWholeTxn' -count=1

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked the newest head. The previous blockers are now closed: the frontend commit path keeps the txn operator reachable across ErrTxnUnknown, and the CCPR unknown-result path now removes cache tracking without wrongly GCing objects. With those lifecycle fixes plus the earlier clone/rollback/shared-file cleanup work, I do not see a remaining correctness issue that should keep this blocked.

@mergify

mergify Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-06-25 09:09 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-06-25 10:35 UTC · at fc0250a15ff01bf7fc93018e45ab24fad40ea609 · squash

This pull request spent 1 hour 26 minutes 44 seconds in the queue, including 1 hour 18 minutes 15 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: 一些ddl操作之后,字符串列进行字符串比较失效。只能通过binary方式比较

5 participants