Skip to content

fix(tae): fail closed on transferred tombstone writes - #26905

Merged
XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/issue-26804-add-unique-atomicity
Aug 11, 2026
Merged

XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/issue-26804-add-unique-atomicity

Conversation

@XuPeng-SH

Copy link
Copy Markdown
Contributor

What changed

  • propagate write and sync failures while remapping S3 tombstones
  • clean persisted tombstone objects that have not crossed the transaction publication boundary
  • close transfer batches and pinned transfer pages on every exit path
  • add ownership and failure-path regression coverage

Why

An UPDATE is committed as a new row version plus a tombstone for the old version. When a source object has been merged, TN remaps that tombstone to the current object generation during transaction preparation. This path previously ignored sink write and sync failures, so the new row and index maintenance could commit without the remapped base-table delete. A later ADD UNIQUE scan exposed the resulting duplicate base rows; the DDL itself was not the corruption source.

The fix makes the remap fail closed and gives unpublished sink output explicit ownership until its object stats are registered in the transaction workspace.

Testing

  • txnimpl package tests
  • txnimpl package race tests
  • each transferred tombstone sink failure test with race and count 100
  • TestTryDeleteByDeltaloc2 with race and count 100
  • go vet and go build for txnimpl

Fixes #26804

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep self-review: changes are required before merge. GitHub does not allow the PR author to formally request changes on their own PR, so this is submitted as a blocking COMMENT review.

  1. [P1] Preserve the top-level moerr across cleanup. transferredTombstoneSink.close always returns errors.Join(priorErr, Close()), and errors.Join returns a joinError even when Close is nil. MatrixOne moerr.IsMoErrCode and txn.WrapError use direct *moerr.Error assertions rather than errors.As, so a retryable RW/WW conflict after the sink has been created is serialized as a generic internal error. Concrete path: object A creates transferSink; object B hits a transfer conflict; cleanup succeeds; the defer wraps the conflict and CN loses its error code. Return the original error unchanged when there is no secondary error, and add a moerr classification regression.

  2. [P1, adjacent existing unhappy path] Do not invoke closeFunc after LoadColumns2 returns an error. LoadColumnsData2 returns release == nil for FastLoadObjectMeta, ReadOneBlock, and decode failures and already releases its IOVector on the latter path. The current closeFunc() call therefore turns an object-store read error into a nil-function panic during transaction prepare. This sits inside the refactored processObject closure and needs fail-closed error propagation.

  3. [P2] Give unpublished-object cleanup an operation-level bound. context.WithoutCancel removes both cancellation and deadline; DeleteUnpublishedObjects then permits up to 10 minutes per 1000-key batch. A sink failure during object-store degradation can therefore keep a cancelled commit worker blocked for 10 minutes or longer, and multiple failures can exhaust workers. Detach request cancellation if required for safety, but install a dedicated total cleanup deadline or explicitly hand cleanup to bounded background GC.

  4. [Blocking coverage gap] Add a deterministic transaction-boundary regression, not only a fake sink-owner test. Inject Write/Sync failure after a real persisted tombstone has to be remapped and assert: commit aborts, base row count/PK uniqueness remain unchanged, no object stats are published, retries/restart remain clean, and the original moerr class survives. The current tests prove the helper state machine but do not prove the claimed issue path from TransferDeletes through txn rollback; the existing DB tests cover success only.

Positive findings: publication after Sync is the correct linearization point; input batches and transfer-page pins now have exactly one cleanup owner; rollback uses the existing tableSpace/catalog lifecycle; no wire, catalog, or on-disk format changes; normal-path cost is one small owner object plus interface dispatch per source object and is dominated by existing copy/sort/I/O. The memoized pins reduce repeated Pin calls and eliminate the previous retained references.

Validation performed: all six focused tests were enumerated; each passed -race -count=100 (adaptive 30s budget, measured 0/0.21s/0.22s); full txnimpl normal and race tests, go vet, and go build passed. These successes do not cover findings 1-4.

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

In transferred_tombstone_sink.go:98-111
(

count, cleanupErr := s.sinker.DeletePersisted(cleanupCtx)
if cleanupErr != nil {
priorErr = errors.Join(
priorErr,
moerr.NewInternalErrorf(
cleanupCtx,
"delete %d unpublished transferred tombstone objects",
count,
),
cleanupErr,
)
}
}
return errors.Join(priorErr, s.sinker.Close())
),
when DeletePersisted fails, the underlying Sinker intentionally retains the
object references so they can be retried. However, Close() is called immediately
afterward. Close() clears these references without deleting the objects, and the
caller does not retry the cleanup.

This can leave unpublished tombstone files orphaned in object storage. Please
retry cleanup before closing the sinker, or preserve/transfer the failed object
references so that a later GC pass can remove them.

@XuPeng-SH XuPeng-SH left a comment

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.

Follow-up deep self-review after 12c89fc: all previously reported blockers are resolved.

  1. Primary transaction errors are now returned unchanged. Cleanup and sink-close failures remain observable as structured secondary logs, so moerr classification and TN RPC serialization preserve retryable/error semantics.
  2. TransferDeletes no longer invokes a nil LoadColumns2 release callback on read failure, and the read now observes the commit context.
  3. Unpublished-object cleanup keeps context values while using an independent one-minute operation deadline; request cancellation cannot skip cleanup and degraded object storage cannot block a commit worker indefinitely.
  4. Added a real transaction-boundary regression: a persisted tombstone is remapped after data-object merge, the rewritten tombstone Sync write is deterministically rejected, commit aborts, the original object-store moerr survives, no stats or new physical file are published, base rows remain unchanged, restart is clean, and retrying the same persisted delete succeeds.
  5. Added white-box coverage for pre/post-publication ownership, cleanup/close failures, exact moerr RPC encoding, and published-close rollback ownership.

Final validation after the last semantic edit: all 7 focused tests passed race count=100 (T=0 for owner tests and T=0.21s for the transaction test, 30s budget, N=100); txnimpl full normal/race passed; tae/db/test full normal passed in 83.875s and full race passed in 105.535s; go build, go vet, and diff checks passed. Full Q1-Q3 and performance review found no remaining blocker: cleanup ownership is exactly once, all touched waits are context-bound, retained maps/batches are transaction/object bounded, and the success path adds no I/O, lock, goroutine, or allocation.

@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Aug 10, 2026

@XuPeng-SH XuPeng-SH left a comment

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.

Deep review conclusion for 12c89fc: no remaining code-level blocker found.\n\nThe repaired invariant is closed: transferred tombstone objects remain owned by the sink until Sync succeeds and stats are registered; every pre-publication exit deletes persisted output; after registration the existing transaction/tableSpace/catalog rollback owns it. The primary transaction moerr is returned unchanged, so TN RPC preserves its error class. Input batches, transfer-page pins, and sink resources each have one cleanup owner.\n\nWhite-box coverage proves publication/cleanup ownership, fail-closed write and Sync errors, cancelled-context cleanup with a total bound, and moerr RPC encoding. The transaction-boundary regression injects a real rewritten-tombstone Sync failure after an object merge and proves: commit aborts with ErrFileNotFound, no new physical file/stats are published, base rows remain unchanged, restart is clean, and retry succeeds. This is the correct deterministic witness for the causal transfer path; the reported ADD UNIQUE operation exposed existing corruption rather than creating it.\n\nQ1/Q2/Q3: no leak/double-cleanup, unbounded wait, or unbounded new accumulation found. The normal non-transfer path is unchanged. On the transfer path the added owner state, interface call, and branch are negligible beside existing copy/sort/object I/O; pin memoization removes repeated Pin calls and closes retained pins.\n\nFresh local evidence: the focused real Sync-failure transaction test and all transferred-tombstone sink tests pass. Previous full txnimpl/db-test normal+race evidence remains on this unchanged head.\n\nMerge condition (not a code finding): GitHub reports BEHIND. PR base is 6042ca6 while current origin/main is 3c7392a (two commits ahead); the current three-way merge has no conflicts and neither upstream commit touches this transfer/sinker path, but rebase onto latest main and CI refresh are still required before merge. GitHub cannot approve a PR authored by the reviewer, so this is recorded as a COMMENT review.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of 12c89fc after reading every PR comment and re-tracing the complete ownership/GC closure: changes are still required before merge. GitHub does not allow the PR author to request changes on their own PR, so this is a blocking COMMENT review.

[P1] Do not destroy the only retry owner when unpublished-object deletion fails.

At transferred_tombstone_sink.go:111-123, DeletePersisted is called once; when it fails, the code only logs the error and then unconditionally calls Close. This directly violates the contract in objectio/ioutil/sinker.go:485-488: DeletePersisted deliberately retains persisted object references on failure so the caller can retry. Close then releases the file service/executor and the local transferredTombstoneSink goes out of scope, so no owner can perform that retry.

Concrete reachable path: a large tombstone transfer spills at least one object; processing a later object fails (read/conflict/later spill); the cleanup Delete call times out or returns a storage error. The transaction error is correctly preserved, but the already-persisted and never-published tombstone object remains in object storage across restart. TAE GC cannot recover it: normal GC derives candidates from checkpoint/catalog metadata, which this object never entered; gcChecker.Verify only reports unknown physical files and does not delete them. Repeating this failure creates unbounded persistent object-storage growth.

The existing TestTransferredTombstoneSinkPreservesPrimaryError actually fixes the broken sequence in place: delete returns an error, exactly one delete is attempted, and Close immediately follows. It proves error precedence but has no eventual-cleanup oracle.

Fix at the ownership boundary: before Close, either complete deletion while the retained references are still owned, or transfer those exact object names to a bounded retry owner that survives this function/restart. A bounded synchronous attempt that can still expire also needs a terminal handoff; logging is not ownership. Preserve the primary moerr unchanged, and add a deterministic regression where an already-persisted spill's first Delete fails and a later cleanup succeeds, asserting no physical orphan remains.

Comment audit:

  • The earlier self-review findings for moerr classification, nil LoadColumns2 release, total cleanup timeout, and transaction-boundary coverage are resolved.
  • The Qodo comment contains no code review.
  • There are no inline review threads.
  • jiangxinmeng1's orphan-file review remains valid and unresolved. The two later self-reviews saying there is no blocker overlooked this ownership loss.

Q1/Q2/Q3 result: Q2 is bounded by the one-minute cleanup context; batches and pin memoization are transaction-bounded; Q1 fails at DeletePersisted error -> Close, and repeated failures therefore also fail Q3. Normal-path performance remains acceptable and no format/wire compatibility issue was found.

Separate merge condition: the PR is still BEHIND current main (PR base 6042ca6, origin/main 3c7392a). The current three-way merge is conflict-free and upstream does not touch this path, but rebase and fresh CI are required after fixing the blocker.

@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

Previous blockers for error precedence, nil release, cleanup deadlines, transaction coverage, active-name retention, and the publication caller's normal cleanup path are fixed. LeftHandCold's unresolved stale-marker, marker-admission, and volatile-owner findings are not duplicated. A separate GC availability blocker remains.

P1 - Do not fail-stop ordinary GC on cleanup-marker replay errors (pkg/vm/engine/tae/db/gc/v3/checkpoint.go:1688)

Process now returns immediately when replayUnpublishedObjectCleanup fails, before tryScanLocked/tryGCLocked. Replay intentionally retains a marker when object or marker deletion fails; for example, the object delete can succeed while marker deletion is denied, causing every scheduled cycle to retry the marker and permanently skip ordinary checkpoint GC. This can make unrelated physical objects accumulate. Isolate marker retry failures from normal GC (or quarantine malformed/permanently undeletable markers) and add coverage proving normal GC continues. This is distinct from the unresolved owner-loss and stale-generation findings already raised by LeftHandCold.

Propagate sink write and sync failures while remapping S3 tombstones, clean unpublished objects, and close all transient transfer resources so UPDATE cannot commit without its base-table deletes.

Fixes matrixorigin#26804
Retain failed unpublished sinks for transaction-level retries, clean up published transfer objects on rollback, and preserve the primary transaction error under a shared cleanup deadline.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of exact pushed head 057b96e64d against rebased main@310fa3f50d: all active request-changes findings are closed, and I found no remaining code-level blocker.

The repeated rework came from fixing deletion retries after persistence without first closing the ownership invariant. The final design makes ownership write-ahead: an object may be written only after a cleanup owner accepts its exact, attempt-unique name.

  • TN transfer: Prepare writes a versioned local cleanup marker before Sync; failed marker admission prevents the object write. The active-writer set fences in-flight objects, catalog lookup distinguishes committed ownership from rollback cleanup, and marker identity prevents replay/Finish double-decrement races. Restart reconstructs marker ownership before admission.
  • Generation safety: every TN and publication spill uses a fresh object name. A stale marker therefore cannot delete a later successful retry, and a pre-persist error cannot capture an older object with the same name.
  • Terminal ownership: transaction cleanup retains exact sink/object names until deletion succeeds. If the transaction deadline expires, it abandons only after proving the durable marker set exactly covers the files; cleaner replay then owns them across transaction removal and restart.
  • Bounded failure behavior: admission is capped at 10,000 markers, replay is capped at 1,000 per cycle and one minute, startup overflow remains fail-closed until a complete replay proves capacity, and all transaction cleanup shares one earliest one-minute deadline.
  • GC availability: ordinary checkpoint GC runs before auxiliary marker replay. Marker/object failures are logged once per cycle and retained for later retry, but cannot starve unrelated GC.
  • Publication: unique names are registered in CCPRTxnCache before Sync, all multi-spill stats are returned/submitted, and failure performs bounded direct deletion while transaction rollback retains the registered exact names. Unique admission avoids the previous remote StatFile probe.

Q1/Q2/Q3: every unpublished object has one effective owner through write, publish/rollback, transaction removal, and restart; every new wait is deadline-bound; retained state and per-cycle work are capacity-bounded. File-not-found is idempotent cleanup success, ambiguous marker deletion is verified by absence, and the primary transaction moerr is never replaced by secondary cleanup errors.

Performance/compatibility: the normal non-transfer path is unchanged. The rare transferred-spill path adds one small local marker write before object I/O and bounded in-memory identity state; publication removes one remote stat per unique output. No goroutine, hot-path scan, SQL/wire/catalog, or object-file format change was added; cleanup metadata is versioned and private to the cleaner.

Fresh post-rebase evidence:

  • full normal tests passed for objectio/ioutil, publication, disttae, tae/db, gc/v3, logtail, txnbase, and txnimpl
  • full race tests passed for those packages plus the complete tae/db/test suite (116.385s)
  • high-repeat race regressions passed: marker accounting x100, real persisted-object retry x100, publication multi-spill ownership x100, real DB Sync-failure rollback x46, and publish-before-conflict rollback x20
  • exact make static-check passed: license 0 invalid and golangci-lint 0 issues
  • production package build and git diff --check passed

Remote head and local head both equal 057b96e64d; the PR base is current main@310fa3f50d. GitHub does not allow the PR author to approve their own PR, so the existing external CHANGES_REQUESTED reviews still need re-review or dismissal.

@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

Earlier blockers are fixed: primary-error precedence, nil LoadColumns2 cleanup, transaction-wide cleanup deadlines, transaction-boundary coverage, publication name retention, and ordinary-GC ordering. Other reviewers’ stale-name and terminal-owner concerns are addressed by unique names, write-ahead ownership markers, bounded replay, and shared deadlines; I do not duplicate them. One distinct blocker remains: ambiguous pre-write marker failures can permanently exhaust the admission budget. Diff checks passed; focused tests could not execute locally because required C headers were unavailable.

P2 - Release phantom marker reservations after an ambiguous pre-write failure (pkg/vm/engine/tae/db/gc/v3/checkpoint.go:1892)

pending is incremented before RecordUnpublishedObjectCleanup. If recording fails, this branch handles only ErrFileNotFound by releasing the reservation; any other StatFile error inserts the marker path into the in-memory markers map while leaving pending incremented. A canceled or transiently failing local filesystem can return errors from both write and stat before creating any marker, so replay—which enumerates durable marker files—can never observe or release this phantom entry. Repeating this reachable failure 10,000 times trips the admission check at lines 1841-1847 and rejects subsequent transferred-tombstone writes until restart, even after storage recovers. This is distinct from the previously raised post-delete owner-handoff issue: it leaks capacity before any object write and without a durable marker. Reconcile/retry this exact ambiguous state or otherwise provide a release path for reservations that have no durable marker, and add a test covering write error plus non-NotFound stat error with no marker created.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of exact head c523ff5: the latest P2 request-changes finding is closed, and I found no remaining code-level blocker.

Root cause: admission incremented pending before the marker write. When both Write and Stat returned errors before creating a marker, the old branch retained only an in-memory marker identity, while replay enumerated durable markers only. The phantom therefore had no release path and 10,000 repeated failures could permanently close admission until restart.

The fix makes that indeterminate pre-object-write state explicit and preserves the ownership invariant:

  • Write plus Stat ambiguity records marker-to-file state and retains the same-name active fence. Prepare returns an error, so no object write follows.
  • Bounded reconciliation deletes the exact marker, or proves it absent, before atomically releasing marker identity, active fence, and pending. Delete or Stat failure retains all state for retry.
  • The same-name fence prevents an old cleanup attempt from racing with a later Prepare generation.
  • Crash behavior is safe: if no marker persisted, no object was written; if the marker persisted, startup durable replay reconstructs and removes it.
  • Durable and indeterminate work share the existing one-minute, 1,000-item replay budget. When indeterminate work exists, durable replay keeps half the initial budget and reconciliation receives the remainder, so neither class is starved. Total retained admission remains capped at 10,000.

The unhappy-path matrix now covers: Write error plus non-NotFound Stat error with no marker; deletion and Stat failure followed by recovery; a marker that did persist despite Write error; 1,001 indeterminate entries across two bounded cycles; coexistence with an active durable writer; and same-name retry fencing and release.

Fresh exact-head evidence:

  • the four new state-machine regressions were enumerated and passed with race count=100
  • all affected packages passed normal tests; tae/db/test completed in 92.058s
  • all affected packages passed race tests serially; tae/db/test completed in 109.918s
  • make static-check passed with 0 license and 0 golangci-lint findings
  • readonly package listing, production package build, and diff checks passed

Q1/Q2/Q3: cleanup ownership is released only by deletion or absence proof; all new I/O is outside the ownership mutex and under the existing one-minute deadline; memory is admission-capped and work is batch-capped. The successful Prepare/write path gains no new I/O, allocation, goroutine, or scan. The extra map is allocated only on the rare Write plus Stat ambiguity path.

Remote PR head and local head both equal c523ff5, based on current main 310fa3f. GitHub does not allow the PR author to approve their own PR, so this is submitted as a COMMENT review; the external CHANGES_REQUESTED state still needs re-review or dismissal.

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

Review completed: I found no new, reproducible P1/P2 code issues in the current PR head c523ff5.

I checked:

  • Active object ownership after Sync failures
  • The full publication → rollback → Store.Close → DeleteTxn lifecycle
  • Durable cleanup markers and GC replay
  • Transaction-level cleanup deadlines across multiple tables
  • Multi-spill tombstone publication and its callers

The previously reported ownership, error-classification, cleanup-timeout, and publication-path
issues appear to be addressed in the current head.

Validation:

  • git diff --check: passed

  • GitHub UT coverage: passed

  • Local tests could not reach the Go test phase because the environment is missing CGo headers such
    as roaring.h, usearch.h, and xxhash.h

  • Some GitHub BVT checks are still running

Conclusion: I found no remaining code-level blocker. The PR can proceed with the remaining CI and
maintainer reviews.

@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

Previous blockers I raised—including error preservation, nil cleanup, bounded ownership, transaction-boundary coverage, and the 057b96e phantom admission slot—are fixed. The new delta retains ambiguous reservations and reconciles exact markers in bounded batches; tests cover the relevant retry and fencing cases. I found no new distinct defect; the outdated handoff-budget thread from another reviewer is not duplicated. Focused tests were blocked by missing CGo headers.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of exact pushed head 87bdbcfc77c against main@310fa3f50d: I found no remaining code-level blocker after systematically closing the additional ownership, liveness, and coverage gaps below.

Confirmed findings fixed in this head:

  1. Ambiguous marker deletion could leak cleanup admission permanently. If marker deletion succeeded remotely but returned an error and the follow-up Stat also failed, the durable marker could already be absent while its in-memory identity remained charged forever. Terminal and replay deletion failures now retain the exact uncertain marker identity and reconcile it independently until absence/deletion is proven before releasing admission.
  2. A retained marker prefix could starve reclaimable work. Replaying the first fixed-size batch repeatedly allowed active, malformed, or retrying markers to pin the cursor forever. Cleanup now uses bounded lexicographic cursor pages over unordered FileService.List results, serializes cursor advancement, wraps only after the tail, and keeps memory bounded to one page plus one candidate.
  3. CCPR rollback held the global cache mutex across remote object deletion. A slow object store could block unrelated transactions for the full delete deadline. Rollback now detaches the last owner under the mutex, performs remote I/O after unlocking, and publishes an exact-object deletion fence. Unrelated names proceed immediately; same-name reuse waits for that generation fence or caller cancellation, so removing the global wait does not introduce an ABA/adoption race.
  4. The non-appendable multi-spill tombstone submission path lacked direct coverage. Aggregation is factored into one helper and tests now prove every nonzero spill statistic, database/table identity, and tombstone flag reaches submission. The exact ApplyObjects branch is exercised with a fake worker rather than only testing the helper.

Lifecycle/self-review closure:

  • Ownership is explicit across active reservation, durable marker, sink, published table, terminal deletion, and ambiguous deletion states. Release is identity-checked, so a stale reconciliation cannot release a newer generation.
  • Remote waits are bounded by the existing cleanup deadline or caller context. No remote delete remains under the CCPR global mutex, and concurrent cleanup passes use TryLock rather than queueing another remote scan.
  • Admission remains capped at 10,000; replay work is paged at 1,000; page memory is bounded; deletion fences exist only for in-flight last-owner rollbacks and always close when the bounded delete attempt returns.
  • Successful foreground write paths do not add remote I/O. The only steady-state CCPR cost is an in-memory branch under the existing mutex; rollback contention is materially reduced. Cleanup pagination is background-only and bounded.

Validation on this exact tree before commit/push:

  • Full normal tests passed for pkg/objectio/ioutil, pkg/publication, pkg/vm/engine/disttae, pkg/vm/engine/tae/db/gc/v3, and pkg/vm/engine/tae/txn/txnimpl.
  • Full -race package runs passed for the same five packages.
  • Nine lifecycle/concurrency regressions were enumerated and each passed independently with -race -count=100 under a 30-second repetition budget; observed single-run times were 0-0.03 seconds.
  • go vet passed for all affected packages; git diff --check is clean.
  • The repository CI coverage parser, run against the previous CI artifact with fresh profiles for edited production files, reports 413/531 changed lines = 77.78%, above the strict >75% gate.

This is an author-side COMMENT review because GitHub does not allow approving my own PR. The historical CHANGES_REQUESTED state is stale relative to this head; current code review result is no remaining blocker.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep code review of exact head 5df020578d1dba33793bbcc927785d30bcb3d75a: changes are required before merge.

P1 — Preserve the delete mapping for renamed non-appendable tombstones

rewriteNonAppendableTombstoneWithSinker now gives every output spill an attempt-unique object name and returns those names only through DownstreamStatsList (pkg/publication/filter_object.go:694-759). The insert side consumes that list, but a later non-appendable tombstone delete still submits the upstream info.Stats unchanged (pkg/publication/filter_object_submit.go:648-657). No upstream-object-to-downstream-spill mapping is saved in IterationContext; DownstreamStatsList is released after the current job.

Concrete lifecycle:

  1. Iteration N observes upstream tombstone object O and creates downstream objects U1...Un.
  2. The iteration commits and advances, without persisting O -> [U1...Un].
  3. A later snapshot diff reports deletion of O.
  4. The downstream calls SoftDeleteObject(O). O never existed there, so the TN treats the missing object as expected and skips it; U1...Un remain catalog-owned.

This deterministically breaks the object lifecycle for every renamed non-appendable tombstone and allows stale tombstone catalog/object state to accumulate across iterations. Persist the one-to-many mapping transactionally, use the downstream stats when processing the upstream delete, and clear it after successful deletion. Please add a cross-iteration create-then-delete regression, including multi-spill output and context serialization/recovery.

Q1/Q2/Q3: Q1 fails because the later logical delete loses the actual downstream object identities; no new unbounded wait was found; Q3 fails because repeated lifecycles can accumulate retained downstream tombstone objects.

This review is code-only; CI status was not used to waive the finding.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of exact pushed head d9aadbb3b6: the latest P1 is fixed, and I found no remaining code-level blocker in the complete PR diff.

Root cause and correction:

  • The rewritten non-appendable tombstone producer changed one upstream identity O into attempt-unique outputs [U1...Un], but the publication state retained no consumer-side identity mapping. A later snapshot deletion therefore soft-deleted O, which never existed downstream, and left every Ui catalog-owned.
  • The fix reuses the existing transactionally persisted AObjectMap; it does not add another cleanup subsystem. The create iteration records O -> [U1...Un], the same local transaction publishes both the object stats and updated mo_ccpr_log.context, and a later iteration resolves and soft-deletes the exact downstream IDs.
  • The mapping is removed only after the complete downstream delete submission succeeds. A delete error retains it for retry; a later failure elsewhere in the iteration rolls both object operations and context mutation back together.
  • A non-nil pointer distinguishes one-to-many ownership from legacy one-to-one mappings, including a valid present-but-empty rewrite. Mapping-kind mismatch, missing owner, malformed base64, and wrong ObjectId length fail closed. Contexts written before this field existed remain readable and use the original-name fallback.

Performance and boundedness:

  • Ordinary object processing adds no remote I/O, wait, goroutine, or scan. Existing mappings gain only one nullable pointer.
  • Renamed tombstones retain fixed-size ObjectIds rather than full ObjectStats; allocation and serialized state are proportional to actual live spill outputs and are cleared on logical deletion.
  • Serialization was centralized in one helper for both iteration-state update variants, removing the duplicated encoder that previously made this lifecycle easy to update incompletely.

Regression matrix:

  • actual create -> multi-spill insert -> JSON marshal/unmarshal recovery -> later delete verifies both exact downstream IDs and mapping release
  • present-but-empty rewrite survives JSON and deletes without touching the engine
  • delete failure retains the mapping
  • absent owner and appendable/non-appendable mapping mismatch fail closed
  • legacy one-to-one stats still restore; malformed new IDs are rejected
  • existing filter-job cancellation/join behavior remains intact

Fresh validation after the final semantic edit:

  • full pkg/publication normal test: passed
  • full pkg/publication race test: passed
  • 12 directly affected tests were enumerated and each passed independently with -race -count=100 (measured T=0.00s, B=30s, N=100)
  • readonly go list, production go build, go vet, and git diff --check: passed
  • new helpers: serialize 85.7%, restore 94.7%, ID conversion/deletion helpers 100% statement coverage

Reflection on the repeated miss: the prior review followed unique spills through immediate submission and rollback cleanup, then stopped at the current transaction boundary. It did not continue the renamed identity through persisted iteration recovery and the independent future snapshot-delete consumer. That made the multi-spill submission test look sufficient while it proved only the producer half. The review gate is now explicit: every name-changing writer must be traced through create, transactional context persistence, restart/recovery, later logical delete, and physical/catalog retirement, including 1-to-N and empty-output cardinalities.

Remote and local heads both equal d9aadbb3b65921eacf21cea4a105e7920a3a7f32. The branch is behind current main@0f145bbc0a, but upstream has no overlapping changed path and the current merge-tree is conflict-free; no force rebase was performed in this fix round. This is an author-side COMMENT review because GitHub cannot approve the PR author; the external CHANGES_REQUESTED review still needs re-review or dismissal.

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

Deep review of exact head d9aadbb3b65921eacf21cea4a105e7920a3a7f32: changes are still required before merge.

[P1] Make publication rollback ownership survive a CN restart (pkg/publication/filter_object.go:821).

ccprTombstoneFileSinker.Sync registers each new attempt-unique name only in CCPRTxnCache before inner.Sync. A reachable sequence is: inner.Sync successfully persists spill O; OnFileWritten returns; then the CN exits before ApplyObjects consumes DownstreamStatsList and submits O to the transaction. No catalog/checkpoint entry or gc/unpublished marker exists at that point. The cache is process-local (NewCCPRTxnCache is recreated with the engine and Engine.Close drops it), so restart loses the sole owner. Because retries now generate a different unique name, they cannot rediscover or adopt O either.

Normal TAE GC cannot close this edge: its candidates come from catalog/checkpoint metadata. The only code that lists all physical files is gcChecker.Verify, which reports unknown files but does not delete them. Thus every crash in this window leaves a permanent object-store orphan, and repeated retries/crashes produce unbounded persistent growth. This is a regression from the previous stable-name rewrite, where a later attempt could at least rediscover the same name.

Please install a restart-surviving write-ahead cleanup owner before inner.Sync (the TN transfer path in this PR already demonstrates that invariant), and release it only after publication/commit ownership is recoverable. Add a regression that persists a spill, discards/recreates the CN cache before submission, and proves restart replay removes the exact unpublished file.

Validation on this head: git diff --check passed; normal tests passed for objectio/ioutil, gc/v3, logtail, txnbase, txnimpl, and tae/db/test; full race passed for the first five, and three critical lifecycle regressions passed with -race -count=100. Local publication/disttae could not reach tests because the available prebuilt libmo lacks the new CGo symbols, so I did not count those as passing. GitHub UT/coverage/SCA/BVT checks are still in progress.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep re-review of exact pushed head 00d6c1c: the latest P1 is fixed, and I found no remaining code-level blocker in the complete PR diff.

Root-cause closure:

  • Every attempt-unique non-appendable tombstone spill now records a shared, restart-safe cleanup intent before the first possible object write. A CN exit after Sync but before object-stat submission therefore leaves an exact durable owner instead of an undiscoverable physical orphan.
  • Ownership transitions are explicit: definite commit releases only the marker; confirmed rollback releases it only after physical deletion succeeds; delete failure, ambiguous Sync, unknown commit result, marker-write ambiguity, and CN restart retain it for catalog-aware TN replay.
  • TN replay waits behind the active/soft-deleted sync-protection job. After a TN restart loses the in-memory protection table, the marker-carried lease plus the existing protection TTL supplies the safety grace. Replay then releases the marker when the catalog owns the exact object, or deletes the object and marker otherwise.
  • Shared markers carry the workspace-selected TN shard ID. A foreign TN shard always retains them, preventing a non-owning catalog from misclassifying and deleting an object committed on another shard.
  • A terminal transaction racing the marker write removes the foreground reservation, forces the writer to fail, and leaves any marker that later becomes visible to durable replay. The regression deterministically covers this interleaving.
  • Marker release cannot block commit behind the shared ants pool: at most one opportunistic, one-minute cleanup goroutine runs per CN cache, with no queue. Busy cases remain durably owned by TN replay, so there is neither unbounded waiting nor goroutine/log amplification.
  • The deterministic CI SCA failure is fixed by preallocating downstream object IDs to the actual upper bound rather than suppressing the checker.

Q1/Q2/Q3 and performance:

  • Q1 ownership is continuous across prepare, object write, transaction terminal states, process restart, TN restart, and catalog/physical retirement.
  • Q2 all new remote operations are caller-bound or have a one-minute total deadline; no remote I/O is performed while holding the CCPR cache mutex.
  • Q3 replay is cursor-paged at 1000 markers with a one-minute cycle budget. Retry state is durable rather than process-memory-unbounded.
  • Ordinary data, appendable objects, and stable-name copies add no I/O or relation lookup. Only the renamed tombstone spill path pays one small write-ahead marker write per spill; table IDs are resolved once per affected table, commit marker deletion is batched, and background scanning remains on the existing GC cadence.

Final validation:

  • Full normal tests passed for objectio/ioutil, publication, disttae, tae/db/gc/v3, tae/db, and the engine integration package.
  • Full race package runs passed for objectio/ioutil, publication, disttae, tae/db/gc/v3, and tae/db.
  • The final ownership, restart, multi-shard, terminal-race, nonblocking-commit, rollback, unknown-result, and multi-spill regressions passed with race count=20.
  • Full repository static-check passed with golangci-lint reporting 0 issues; exact-final-head targeted lint, git diff --check, and remote-head verification also passed.
  • Current main is cf3c14d; it has no changed-file overlap with this PR delta. The PR remains behind main, but this is not a code conflict and no force rebase was performed in this fix round.

This is an author-side COMMENT review because GitHub does not allow approving my own PR. The external CHANGES_REQUESTED review targets d9aadbb and now needs re-review or dismissal.

@XuPeng-SH XuPeng-SH left a comment

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.

Deep independent re-review of exact head 00d6c1cdab82f9e62364f623e6a6246a8e4c59f6: no blocking findings; I would approve this head.

I rechecked the complete 37-file diff and the final restart-safe CCPR cleanup protocol, including the earlier requested changes:

  • fail-closed transferred tombstone write/sync behavior and preservation of the primary concrete moerr
  • exact ownership transfer for persisted and commit-ambiguous objects across rollback, unknown commit result, CN restart, and TN restart
  • marker-write/delete ambiguity, catalog-owned versus unpublished decisions, TN-shard fencing, and sync-protection expiry
  • single transaction-wide cleanup deadline, cancellation independence, page/batch release, and bounded cursor replay
  • 1-to-N downstream tombstone identity persistence through iteration serialization, recovery, later deletion, and retry

Fresh validation on this exact head:

  • all 12 tests added by the final commit passed individually under -race -count=100
  • full normal and full race runs passed for objectio/ioutil, publication, disttae, TAE gc/v3, txnimpl, db, db/test, logtail, and txnbase
  • readonly build, go vet, and git diff --check passed
  • all current non-skipped GitHub checks are successful, and the PR is mergeable

This is an author-side COMMENT review because GitHub does not allow approving my own PR. The remaining external CHANGES_REQUESTED review targets older head d9aadbb3b6; its reported restart-ownership gap is closed by 00d6c1cdab82 and still requires external re-review or dismissal.

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Failed ADD UNIQUE resurrects UPDATE versions and creates duplicate primary keys

7 participants