Skip to content

fix(tae): reconcile replay promotion merge state before write - #29421

Merged
XuPeng-SH merged 10 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29415-fix
Sep 28, 2026
Merged

XuPeng-SH merged 10 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29415-fix

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Test and CI

Which issue(s) this PR fixes:

Fixes #29415

What this PR does / why we need it:

A replay TN constructs its merge scheduler before WAL replay finishes. A table and merge setting committed afterward can be visible in the replayed catalog but absent from the scheduler. The two-engine diagnostic reproduced this on clean main 5a96035fc792b07b7a28e2f509dc0dcd4236e048.

For the dormant local Replay → Write command, join replay, read a current settings snapshot, reconcile the stopped scheduler, and start write services only after validation. Preserve surviving supporter/task accounting, add late tables, remove dropped tables, and clear stale settings. Failures after the one-way replay barrier are terminal: reject retries and new transactions, then let the caller close/reopen. The queued resume is the commit point; its query barrier does not report false failure on late caller cancellation.

Deep-review corrections — 9b010b6771

The previous blocking review reproduced three gaps. All are addressed:

  • Advance the existing DB/transaction-manager clock past the replay high-water mark before enabling write services. If the clock cannot advance, fail closed. A future settings snapshot alone was insufficient: the first write could panic.
  • Preserve DisableGC when installing promotion's disk-GC job.
  • Validate promotion-only tombstone counts, overlap depth, and vacuum decay duration before scheduling; reject short decay controls and propagate parse errors. Normal settings parsing is unchanged.
  • Add the missing integration-test license header.
  • Release and join the manually driven test scheduler's query goroutine even on early assertion failure.

Follow-up review corrections — 4469fba53f

The latest blocking review found that a persisted math.MaxInt tombstone count passed promotion but made the first merge gather panic during slice preallocation. Promotion now accepts each L1/L2 count only in [1, 65536], rejecting larger persisted settings before scheduler start. At the accepted ceiling, the two initial pointer arrays consume at most 1 MiB per gather on 64-bit systems; this does not bound memory from the actual number of tombstones.

Independent QA also found that after a terminal promotion error, the 2 ms transaction heartbeat kept trying to create a transaction and repeatedly panicked on the nil result. The terminal cleanup now stops and joins that heartbeat before latching the transaction exception. This is within the existing fail-stop ownership contract; no normal heartbeat path changed.

Scope, compatibility, performance

No in-repository production service calls local modes 1/2; debug RPC uses only modes 3/4. The caller must fence the old writer and exclude concurrent DB/RPC requests. This PR does not enable live TN migration. External Go callers cannot be ruled out by repository search.

No wire, catalog, storage-format, or normal-startup settings contract changes. Normal transaction and merge hot paths execute no new calls. Promotion performs O(active tables + settings rows) work and a one-time clock update. The follow-up adds only a promotion count check and terminal heartbeat stop; it adds no worker or persistent state. Large-catalog promotion latency was not benchmarked. Existing general scheduler resource limits are unchanged.

Design: final reviewed revision, SHA-256 c55bf2388cf9f84d4bc7f03baa7784e7ae66cf54f87eaf0650889c604eef69a0. It retains the original approved contract; the count budget and heartbeat cleanup close review findings without a protocol or recovery-contract change.

Validation

Linux/amd64, Go 1.26.4, repository mo-cgo-test with provenance-checked native artifacts. Base remains 5a96035fc7.

  • PASS: 14 two-engine promotion scenarios, including a real committed write after every successful promotion, future WAL clock, exact nondefault recovered settings, disabled disk GC, a clock that ignores Update, invalid persisted settings including math.MaxInt independently in L1 and L2, absent/deleted settings, cancellation/retry, and cron conflicts.
  • PASS: final-head focused domain and two-engine integration tests with -race -vet=all -count=1 (both packages passed; no heartbeat panic or race report). The earlier -race -count=53 stress run remains evidence for unchanged promotion scenarios, not for the new count and heartbeat paths.
  • PASS: promotion settings-domain unit cases: negative/zero counts and durations, JSON codec round trips for 65537 and math.MaxInt in each count, accepted 65536 in both counts through an empty gather; existing reconciliation/generation/cancellation tests reused where inputs are unchanged.
  • PASS: final-head full owning db and merge packages in normal mode with -vet=all; final-head focused domain and two-engine integration tests in normal and race modes. Earlier full owning race results and the cancellation stress run remain valid for unchanged paths.
  • PASS: final-head incremental golangci-lint 2.6.2 and pinned molint for changed db, db/merge, and db/test packages, plus -vet=all, gofmt and diff whitespace. Earlier SCA for unchanged tables and license headers remains valid.
  • Reused: prior full tables package result; its scanner and dependencies relevant to that result are unchanged.
  • Independent review: gpt-6-sol / xhigh reviewed the clean final commit 4469fba53f, including the new count and heartbeat failure paths, with no concrete blocker.

Selected integration command:

.agents/skills/mo-dev/scripts/mo-cgo-test -race -vet=all \
  -run '^(TestPromotionSettingsDomains|TestIssue29415ReplayPromotionLateTableAndSettings)$' \
  -count=1 -timeout=180s \
  ./pkg/vm/engine/tae/db/merge ./pkg/vm/engine/tae/db/test

No SQL BVT applies because no production SQL/service caller can invoke this local promotion command. The full unrelated db/test integration suite and full-repository SCA were not run; the stated package/selection scope is intentional. Synthetic partial-batch I/O failure was not injected; the strict scanner has one effective batch owner and closes partial batches on errors.

Rollback: revert before enabling a service caller. Local validation is complete for commit 4469fba53f. The previous green CI ran on 9b010b6771; CI on the updated head is not claimed green or awaited. Correcting a bad persisted row and reopening a fresh instance was not separately tested.

@XuPeng-SH
XuPeng-SH requested a review from fengttt as a code owner September 27, 2026 21:33
@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.

Verdict: changes required

Reviewed head 2e7919d08fe7c966d24b58e3569b09f42d1208ca against freshly verified base 5a96035fc792b07b7a28e2f509dc0dcd4236e048. This is a COMMENT review because the authenticated account is also the PR author; the technical recommendation is do not merge yet.

Three concrete correctness gaps were reproduced, plus an exact-head SCA failure. These counterexamples supersede the earlier “no remaining concrete blocker” statement in the PR body. Severity is calibrated to the documented dormant local promotion path: this does not establish an incident in a currently enabled production service.

Coverage and evidence

Changed closure Review result
Replay join → settings snapshot → transaction admission A future replay timestamp is visible to the settings reader, but the first real write after successful promotion panics.
Settings decode → supporter reconciliation → scheduling Valid JSON with a negative tombstone count passes promotion validation and panics when scheduling consumes it.
Write-service startup/configuration Promotion schedules disk GC even when DisableGC is true.
Batch ownership and error cleanup Traced the single batch owner and partial-error cleanup; no additional concrete defect found. Synthetic partial-batch I/O failure was not injected.
Cancellation, terminal failure, retry, scheduler barrier Reviewed against the approved exclusive-caller/fenced-writer contract and reused the existing focused race evidence. No additional proven hang/race finding.
Compatibility/performance No wire, disk, or catalog format change; no new work on normal startup/merge hot paths. Promotion adds catalog/settings traversal and retained per-table state. Large-catalog promotion latency was not benchmarked.
Delivery SCA fails because the new integration test has no license header.

The extra probes were run in an isolated checkout with diagnostic test changes only:

  • Extend future WAL timestamp with StartTxn → CreateDatabase → Commit: process panic in TxnCtx.ToPreparingLocked.
  • Set replay GCCfg.DisableGC=true: promotion returns success and installs GC-Disk.
  • Persist a default setting with TombstoneL1Count=-1: promotion incorrectly returns nil; separately feed that accepted trigger through PreparePromotion → doSched: makeslice: cap out of range.

Commands used the repository CGo wrapper, -count=1 -timeout=60s, selecting only those discriminating cases in ./pkg/vm/engine/tae/db/test and ./pkg/vm/engine/tae/db/merge. Initial additional-test linking attempts ran out of temporary disk; reruns using a volume with sufficient space reached the failures above. Existing package/race passes are useful but do not cover these missing oracles. No CI wait was required.

Engineering assessment

Keep the fixes confined to the approved dormant promotion boundary. The shared permissive settings converter predates this PR; changing normal production settings behavior is unnecessary to make this new promotion reader fail closed. Prefer stronger end-to-end assertions (a committed write, exact recovered setting, preserved GC configuration) over more tests of internal structure. No evidence here justifies a protocol upgrade or a broader live-migration framework.

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

@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 on the four findings above: addressed in 9b010b677178527b810ee13765d502667614bd8c.

  1. Promotion now updates the shared transaction clock before write services start, verifies advancement, and fails terminally if advancement is impossible. The future-WAL case now commits a real write.
  2. Promotion preserves DisableGC; the regression checks the disk job is absent while other required write jobs are present.
  3. The promotion-only reader rejects unsafe counts and nonpositive vacuum duration; persisted-invalid-setting and lightweight domain tests cover rejection and positive boundaries. Normal production parsing is unchanged.
  4. License-eye now passes for all 9 changed Go files.

The independent gpt-6-sol / xhigh reviewer inspected the complete change and a final test-cleanup correction: no confirmed blocker remains. Local owning-package normal/race checks, 53 repetitions of all 12 promotion scenarios under race, incremental molint and golangci-lint 2.6.2 passed. Exact commands, limitations, and scope are in the updated PR body. No normal transaction/merge hot-path work, protocol change, or service enablement was introduced. Updated CI is not being waited on.

This records the resolved findings as a COMMENT review because the authenticated account is the PR author; it is not a GitHub approval.

@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: changes required

Reviewed exact head 9b010b677178527b810ee13765d502667614bd8c against current base 5a96035fc792b07b7a28e2f509dc0dcd4236e048. One concrete P2 remains: the previous unsafe-count finding is only partially closed. The newly reproduced upper-bound failure supersedes the prior no-blocker conclusion. The independent gpt-6-sol / xhigh reviewer also verified this counterexample and revised its conclusion.

Previous comments

Finding Current status
Future WAL timestamp → first-write panic Fixed: clock update precedes write workers; actual commit and unresponsive-clock failure are covered.
DisableGC ignored Fixed: promotion conditionally starts disk GC; configured absence is asserted.
Unsafe numeric settings Partially fixed: zero/negative counts and nonpositive vacuum duration are rejected, but an overflowing positive capacity is accepted and later panics.
Missing license header Fixed; exact-head SCA now passes.

New evidence

Diagnostic tests ran in an isolated checkout; the PR branch remains untouched.

  1. Serialize a default setting with TombstoneL1Count = math.MaxInt through the real JSON encoding and decoding. toPromotionTrigger accepts it.
  2. Repeat for L2. Passing each accepted trigger to GatherTombstoneTasks(ctx, IterStats(nil), trigger.tomb, 0) deterministically panics with runtime error: makeslice: cap out of range at statVacuum.go:120/121. These probes do not allocate an enormous working set: the impossible capacity is rejected by the runtime.
  3. Extend the existing two-engine fixture with a persisted MaxInt L1 setting. SwitchTxnMode returns nil, failing the expected invalid-settings error. Thus the input reaches the real promotion boundary.

Both targeted CGo test commands exited 1 with the expected assertion/panic evidence. Existing 53-repeat race/package/static passes were reused for unchanged closures; they do not cover this upper boundary.

Other closures and engineering assessment

  • Rechecked replay join/cancellation, terminal admission/retry rejection, scheduler generation and supporter ownership, snapshot/deletion handling, batch close ownership, and commit-point query release paths. No second confirmed blocker.
  • The copied scanner has an explicit single batch owner. Injected partial-batch I/O failure remains untested; no leak/double-close is claimed.
  • No new wire/storage format, normal startup call, or transaction/merge hot-path work. No justification for expanding this fix into live migration or changing normal production parsing.
  • Reconciliation retains O(table count) state; changed heap entries also incur heap maintenance, and settings scanning includes tombstone processing. Large-catalog latency/memory were not benchmarked, so the PR's linear-cost shorthand is not a measured bound.
  • Current GitHub required checks, UT, SCA, coverage, proxy BVT and pessimistic compose BVT are successful. Platform/upgrade jobs marked skipped are not counted as verified.

Recommendation: close the positive-capacity boundary locally and add the missing upper-bound controls before merge. This is still a dormant promotion-path issue, not evidence of an incident in an enabled production caller.

Submitted as COMMENT because the authenticated account is the PR author; the technical verdict is REQUEST_CHANGES.

Comment thread pkg/vm/engine/tae/db/merge/settings.go Resolved
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Follow-up to my blocking review: fixed in 4469fba53f.

  • Promotion now rejects persisted L1/L2 tombstone counts above 65536 before starting the merge scheduler. The JSON round-trip tests reject 65537 and math.MaxInt independently for both fields; the accepted boundary reaches GatherTombstoneTasks without a capacity panic.
  • Two-engine tests persist each oversized value and verify the original error, blocked retry and transaction admission, and absence of write-only cron jobs.
  • Independent unhappy-path QA also found a repeated transaction-heartbeat panic after terminal promotion failure. The terminal path now stops and joins the heartbeat before setting the transaction exception. Focused normal and race runs pass with no heartbeat panic.

The final-head owning db/merge tests, focused race, vet, incremental golangci-lint and molint pass locally. Independent gpt-6-sol / xhigh review found no remaining concrete blocker. Updated-head CI is running; I am not treating the previous head's green checks as evidence for this commit.

@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 of 4469fba53f141e664a80f04defade1cd503794c6 against 5a96035fc792b07b7a28e2f509dc0dcd4236e048: no remaining confirmed correctness blocker within the approved local promotion contract. Technical recommendation: approve, with one non-blocking documentation correction below. Submitted as COMMENT because this account is the PR author.

I reviewed the full 10-file change and its consumers, including replay/clock/admission ordering, fresh-scheduler reconciliation and supporter ownership, settings decoding and scan cleanup, cancellation/terminal error/retry/close, cron configuration, compatibility, cost, and test cleanup. An independent gpt-6-sol / xhigh pass challenged the controller/replay/heartbeat paths and found no concrete blocker. The detached resume barrier was rechecked against actual scheduler execution and nonblocking task admission; no supported wait-cycle counterexample remained.

Previous findings are closed in the current source:

Previous finding Evidence of closure
Future replay timestamp causes first-write panic Shared clock advances before write services; future-WAL regression commits a real write; unresponsive clock fails terminally.
DisableGC ignored Disk-GC installation preserves the option; other required write cron jobs remain present.
Negative/zero numeric settings Promotion-only validation rejects unsafe counts and durations before scheduler startup.
Unsafe positive slice capacities Both counts are bounded to 65536; 65537 and MaxInt pass through the catalog JSON codec and are rejected; the accepted boundary reaches the real gather consumer. Both persisted MaxInt variants reject promotion/retry/new transactions.
Missing license header Header is present; prior license verification remains applicable, with final Go delta passing incremental static checks.
Heartbeat panic after terminal failure The terminal path cancels and joins heartbeat before setting the transaction exception; the final normal/race logs contain no heartbeat panic.

Additional review evidence, beyond the author test cases: in an isolated checkout of this exact head, TestReviewPromotionPartialBatchOwnership passed five white-box cases. A two-block scan covers success, second-block data-scan error, tombstone-read error, workspace-delete-read error, and cancellation after the first block. Each failure returns the original error (or cancellation), returns no partial batch, releases its data owner once, and returns MergeAllocator bytes to the pre-call value. Success transfers batch ownership to the caller. These are injected lower-layer errors, not a real fileservice outage test. Command: mo-cgo-test -v -vet=all -run '^TestReviewPromotionPartialBatchOwnership$' -count=1 -timeout=60s ./pkg/vm/engine/tae/tables; exit 0.

I reused the semantically valid exact-head focused normal/race, owning db/merge, and incremental static results. PR head and author worktree were reverified unchanged. Current shared build has passed; UT/SCA/BVT remain pending and are not counted as green or awaited.

Engineering assessment: the repair stays at the dormant promotion boundary, preserves supporter identity, and introduces no protocol/storage format or normal transaction/merge hot-path work. There is no demonstrated need for a broader migration framework or new recovery protocol. The code does not establish production live migration: fencing and exclusive callers remain prerequisites. Large-catalog latency and correcting a bad persisted row followed by fresh-instance recovery have not been separately measured/tested; this review does not claim those results.

changes references held by the catalog/DB. Rejected.
- Asynchronously enqueue replayed table/config events: leaves an interval in
which writes or merge scheduling can observe stale state. Rejected.
- Reconcile the stopped scheduler before admission: selected. Work is O(active

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.

[P3, non-blocking] Describe the actual promotion cost instead of a linear bound

The O(active tables + settings rows) statement also appears in the PR body, but the implementation includes heap.Remove/heap.Push for changed supporters and, for each data block, a new full visible-tombstone iteration in scanMergeSettingsBlockForPromotion. The aggregate scan batch also includes rows before final delete compaction. Thus table/settings row counts alone do not describe either work or peak batch memory.

Please describe the heap maintenance, data-block/tombstone traversal and transient batch cost explicitly, or qualify this as an unmeasured one-time operation. This is a documentation correction, not a request to redesign the scheduler or change the normal production hot path. No performance regression was reproduced.

@XuPeng-SH
XuPeng-SH merged commit 9b7c2c2 into matrixorigin:main Sep 28, 2026
14 of 18 checks passed
XuPeng-SH added a commit that referenced this pull request Sep 28, 2026
## Problem

Current `main` fails UT, Coverage UT, and SCA after #29421. The replay
promotion test calls `SendConfig` with two arguments although the API
requires a snapshot timestamp. A separate replay case accepts five L0
decay points during promotion preflight, but the task-trigger converter
requires exactly four, so it fails later with a different error.

These failures also appear in #29423 CI, but neither failure is
introduced by that PR.

## Change

- Pass the zero timestamp in the scheduler unit test, matching the
current API.
- Enforce the existing four-point trigger contract at promotion
preflight, before workers start; reject extra points instead of silently
truncating them.
- Update the replay regression case to expect that validation error.

## Validation

- `mo-cgo-test -count=1 -timeout=4m ./pkg/vm/engine/tae/db/merge
./pkg/vm/engine/tae/db/test` — passed.
- Focused scheduler and replay promotion tests — passed.

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: replay-to-write promotion can load stale merge settings

3 participants