Skip to content

Move appendable object creation outside transactions - #25534

Merged
mergify[bot] merged 34 commits into
matrixorigin:mainfrom
jiangxinmeng1:move-aobject-create-outside-txn
Jul 24, 2026
Merged

mergify[bot] merged 34 commits into
matrixorigin:mainfrom
jiangxinmeng1:move-aobject-create-outside-txn

Conversation

@jiangxinmeng1

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:

issue #25533

What this PR does / why we need it:

  • Create appendable objects as committed catalog entries from the appender path using TxnMgr.Now(), without attaching them to the active transaction.
  • Rebuild missing appendable objects during WAL replay from append command row IDs, then normalize their create timestamp after replay using the minimum observed commit timestamp.
  • Preserve apply-table-data semantics for appendable stats and reject unexpected transactional appendable-object create entries while keeping old WAL replay compatible.
  • Added/updated tests around appendable object replay and apply-table-data behavior.

@jiangxinmeng1
jiangxinmeng1 requested a review from XuPeng-SH as a code owner July 8, 2026 09:00
@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

Choose a reason for hiding this comment

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

Deep review verdict: Request Changes. Two blocking lifecycle/correctness issues remain on the latest head 24cebe70.

  1. apply-table-data rejects valid flushed appendable objects.

pkg/vm/engine/tae/rpc/apply_table_data.go treats stats.Rows() > 0 as invalid for every appendable object. That invariant only holds for a newly created live in-memory aobject. A compacted/flushed appendable history object can legitimately carry Rows/BlkCnt/Extent. The existing pkg/vm/engine/tae/db/test.Test_ApplyTableData deterministically fails on both the PR head and PR+latest-main with:

internal error: appendable object ... has non-empty row count 2

The same test passes on clean latest main, so this is a PR regression. Please model live/non-persisted versus flushed/file-backed appendable objects separately; do not merely drop the validation and recreate a persisted object as an active memory appender. Add compacted dump/apply, rollback/retry, object-state, and restart/read coverage.

  1. write -> replay can deadlock while draining transactions.

handleToReplayCmd stops MergeScheduler before TxnMgr.SwitchToReadonly/WaitEmpty, but leaves the catalog notifier attached until after WaitEmpty. Existing transactions can still synchronously send OnCreateTableCommit / OnCreateNonAppendObject into the stopped scheduler. msgChan is bounded at 4096 and has no consumer after Stop; once full, the transaction blocks in the notifier while WaitEmpty waits for that transaction. With a background context the mode switch can hang forever.

Please first prevent new work while keeping catalog events drainable, wait for in-flight transactions, then detach the notifier and stop the consumer (or implement an equivalent lossless lifecycle protocol). Add a test with an in-flight transaction producing more than 4096 events plus switch failure/rollback coverage.

The timestamp publication, WAL replay reconstruction, checkpoint range-recovery selection, tombstone lifetime scan, and empty-aobject paths otherwise look sound. CI must be rerun after these two blockers are fixed.

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

Blocking: balance txnWaiter when readonly admission rejects a new CN transaction.

SwitchToReadonly sets all skip flags and then waits for the waiter to become empty. In loadOrStoreTxn, however, the waiter is incremented before the skip check; when the flag is skipped and the txn ID is not already present, the code still stores the new txn and returns it as offline without calling Done. Both Txn.Commit and Txn.Rollback return immediately for offline stores, so that map entry is never deleted and its waiter count can never reach zero.

This is reachable during the mode switch: the RPC server checks TxnLocalHandle before calling req.exec, so a request already dequeued before TxnForwardWait can enter GetOrCreateTxnWithMeta after readonly flags are installed. The current switch then waits until its 10-minute timeout; switching back to write mode does not remove the leaked entry, subsequent switches keep timing out, and that txn ID remains poisoned as offline.

I reproduced it with a focused test that sets TxnFlag_Normal, calls loadOrStoreTxn with an absent ID, and then waits with a 50 ms context: WaitEmpty returns context deadline exceeded. Please make the skipped/new-ID path leave neither a managed map entry nor a waiter reference (while preserving reuse of an already managed ID), and add this case beside TestLoadOrStoreTxnBalancesWaiterOnHit.

The two previously reported blockers are fixed on this head: persisted appendable stats now restore transactionally, and the merge notification queue is drained while its consumer is alive.

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

The earlier correctness blockers are fixed on this head: persisted appendable stats are handled safely during apply, write-to-replay drains in-flight transactions before stopping the merge scheduler, and readonly admission no longer leaks the waiter/store entry.

One deterministic test-lifecycle blocker remains. The new mode-switch helper creates a TxnServer on a fixed address and never closes it. Running the two new tests in the same package process makes the second test fail with listen tcp4 127.0.0.1:12345: bind: address already in use, although each test passes alone.

Reproduced with:
go test ./pkg/vm/engine/tae/db/test -count=1 -run 'TestTxnModeSwitch(DrainsInflightCatalogEvents|WaitCancelRollsBack)$'

Please give each test an ephemeral listener (for example 127.0.0.1:0) and register cleanup that calls TxnServer.Close(). This also prevents conflict with the existing basic mode-switch test.

Comment thread pkg/vm/engine/tae/db/test/db_test.go Resolved

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep review on exact head 624a27306527a16c2c8a6924492235448d76f86a found two blockers: the PR's new apply-table-data regression test fails deterministically and leaves an extra live object, and the new merge-scheduler drain barrier can bypass the mode-switch context under stalled I/O/backpressure. The timestamp publication, readonly admission, replay reconstruction, empty-object flush/recovery, active tombstone-drop scan, and mode-switch race tests otherwise passed, including targeted -race runs.

Comment thread pkg/vm/engine/tae/db/test/db_test.go Resolved
Comment thread pkg/vm/engine/tae/db/controller.go Resolved

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

Requesting changes on exact head 97839bc.

The earlier Apply Table Data snapshot issue and the mode-switch query hang are addressed, and the focused functional/race tests pass. Two blockers remain in the latest scheduler fix: stopped-generation I/O can still cross into a restarted scheduler, and the exact-head SCA check currently fails on the newly added errors.New.

Comment thread pkg/vm/engine/tae/db/merge/scheduler.go Resolved
Comment thread pkg/vm/engine/tae/db/merge/scheduler.go Resolved

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex automated review

Two issues remain on the exact head: a scheduler generation race and a nil-options panic in the new API.

P1 - Prevent stopped-generation I/O from entering a restarted scheduler (pkg/vm/engine/tae/db/merge/scheduler.go:521)

The preliminary stop check is racy. A delayed old-generation callback can pass lines 516–520, then Stop closes its channel before the second select. With ioChan capacity available, both cases are ready and Go may select the send, placing old vacuum work on the shared queue after Stop has returned. A restarted scheduler can consume it; alternatively, the old I/O loop can run it and block trying to publish triggers with no main loop. The test only invokes the function after the channel is already closed, so it misses this interleaving.

P2 - Return an error instead of panicking for nil CreateObjectWithOpt options (pkg/vm/engine/tae/txn/txnimpl/txndb.go:356)

The newly exposed CreateObjectWithOpt path dereferences opt via opt.WithIsTombstone without validation; passing nil through Relation.CreateObjectWithOpt panics before reaching the helper. The sibling CreateNonAppendableObject explicitly normalizes nil options at the relation boundary. Reject nil options (or provide the documented default) and add coverage so an invalid caller input cannot crash the TN.

…ject-create-outside-txn

# Conflicts:
#	pkg/vm/engine/tae/txn/txnbase/txnmgr.go
#	pkg/vm/engine/tae/txn/txnbase/txnmgr_test.go

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep review verdict: Request Changes on exact head 84f0581254a3bb2bc01099c34d73edb4348f7285.

P1 - Do not discard old-generation merge completion accounting (pkg/vm/engine/tae/db/merge/scheduler.go:215)

doSched records every admitted task in scheduler-wide state by incrementing supp.mergingTaskCnt and calling rc.Acquire. The new observer now tags the matching DoneTask message with the old generation, and dispatchMsg drops that message after Stop/Start. The state being balanced is not generation-local: supps and rc survive the restart.

This is reachable during write -> replay: TxnMgr.WaitEmpty can finish before the task observer runs because the observer is invoked by ops.Op.SetError only after the task implementation returns (and its transaction has already left TxnMgr). If the scheduler stops in that gap and later restarts, the completion is lost. PendingMergeCnt remains positive, line 1189 postpones that table forever, and the matching memory reservation is never released; repeated occurrences can also exhaust the global merge budget.

I reproduced this deterministically by admitting one task in generation N, stopping/restarting the scheduler, then firing its captured completion callback. A query on generation N+1 returns PendingMergeCnt == 1 instead of 0. The PR test TestStoppedGenerationIOCannotCrossRestart only covers stale I/O and misses this persistent accounting edge.

Please either wait/cancel all admitted merge work before closing a generation, or separate generation-bound scheduling messages from generation-independent exactly-once completion accounting. Add a deterministic Stop/restart test with a blocked in-flight merge and assert both PendingMergeCnt == 0 and the resource reservation is restored after completion.

The replay/create timestamp, apply-table-data, empty-object, tombstone scan, readonly waiter, and scheduler I/O paths otherwise passed the focused and package tests, including targeted -race runs.

@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

Previously blocking active-drop scanning, timestamp publication, apply-table-data restoration, readonly admission, mode-switch draining, test cleanup, nil-option handling, and stopped-generation I/O are fixed. Empty-object durability is accepted as intentional; the tombstone early-stop suggestion is withdrawn. One new blocking scheduler lifecycle issue remains. Focused tests could not run because cgo/libmo.dylib is absent; git diff --check passed.

P1 - Preserve merge completion accounting across scheduler restarts (pkg/vm/engine/tae/db/merge/scheduler.go:216)

doSched counts every accepted asynchronous compaction with mergingTaskCnt++ and rc.Acquire, but this observer sends the only corresponding DoneTask/Release notification through the task's generation. A task may still be queued when SwitchToReadonly waits for transactions, or its transaction may be removed before Op.SetError invokes observers; therefore the Query barrier can finish and Stop can close the generation first. sendMsgForGeneration then returns false and discards the completion. Start reuses the same supporters and resource controller, so mergingTaskCnt remains positive, doSched postpones that table forever, and the reservation is never released. A write→replay→write cycle can thus permanently disable automatic merging and eventually exhaust storage. Stop must drain all accepted task observers before closing, or completion accounting must cross generations losslessly and exactly once; add coverage with a queued/in-flight merge task during the mode switch.

@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

Previously blocking active-drop scanning, timestamp publication, apply-table-data restoration, readonly admission, mode-switch draining, test listener cleanup, nil-option validation, and stale-generation I/O are fixed. Empty-object durability is accepted as intentional behavior; the tombstone early-stop concern was withdrawn. The prior scheduler completion-accounting blocker is fixed by dcce800: completion now balances persistent accounting exactly once across scheduler restarts, with regression coverage. No new findings. git diff --check passed; focused Go tests could not run because the Go toolchain is absent.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep-reviewed the complete 44-file diff at dcce800. No blocking findings remain.

Verified functional closure:

  • appendable creation is atomically published with its catalog timestamp; nil/invalid options are rejected; transactional create entries are guarded
  • WAL replay reconstructs missing appendable objects, preserves object IDs, normalizes create timestamps, and remains compatible with explicit old-WAL catalog entries
  • dump/apply-table-data preserves live vs persisted appendable semantics and rollback behavior
  • tombstone range scans cover active/committed drops without duplicate versions; full-history scan is an intentional correctness tradeoff
  • write/replay mode switches drain catalog notifications and bound readonly waits
  • merge scheduler Stop/Start isolates I/O generations while completion observers balance persistent pending-task and memory accounting exactly once across restarts

Local exact-head validation:

  • focused concurrency/replay/mode-switch tests under -race with stress counts
  • full -race suites for objectio, disttae/logtailreplay, tae/catalog, tae/db/merge, tae/rpc, tae/tables, tae/txn/txnbase, and tae/txn/txnimpl
  • go build and go vet for the same core packages
  • git diff --check

Decision log: a live empty appendable with no append/delete remains intentionally non-durable because it carries no table state; the broader tombstone history scan is accepted until a safe commit-ordered index exists.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex automated review

Follow-up disposition: prior active-drop, timestamp-publication, apply-table-data, readonly-admission, listener-cleanup, nil-option, stale-I/O, and scheduler-accounting blockers are fixed. Empty appendable durability remains an accepted contract; tombstone early-stop was withdrawn as unsafe, with full-history scanning accepted as a performance trade-off. One new non-blocking scheduler lifecycle gap remains.

P2 - Rebuild merge scheduler state when leaving replay mode (pkg/vm/engine/tae/db/controller.go:815)

Replay mode now leaves the scheduler stopped and without a catalog notifier. ReplayWal runs in ReplayForever, so a table committed after NewMergeScheduler's one-time InitSource snapshot is never delivered to the scheduler. Switching to write mode only installs the notifier and calls Start; Start does not rescan InitSource, leaving that table unscheduled for automatic merging. Merge show also now fails with ErrMergeSchedulerStopped in replay mode, while the previous implementation kept the scheduler running. Add a no-gap catalog rescan/catch-up when starting write mode, or explicitly reject merge controls in replay mode.

@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

@Mergifyio refresh

@mergify

mergify Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-24 09:49 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-24 13:19 UTC · at 91c4c5b7e997c31b017309b90ad79e2709db4e5a · squash

This pull request spent 3 hours 30 minutes 11 seconds in the queue, including 1 hour 3 minutes 55 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • 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 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

@mergify

mergify Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

refresh

✅ Pull request refreshed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants