Skip to content

fix(disttae): hand alpha stats workers a detached table stock snapshot - #30926

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27702-main-f91c1ed6
Oct 23, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27702-main-f91c1ed6

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:

Related to #27702

What this PR does / why we need it:

Removes the data race in the mo_table_stats pipeline reported in issue #27702 by making each stats collection round own a detached snapshot of the pending changed tables.

Root cause

tableStatsExecutor hands the batch of pending changed tables to alphaTask once per tick, after its prepare step (getChangedTableList) appended those tables to dynamicCtx.tableStock.tbls. Before this change the handoff passed d.tableStock.tbls[:], a slice aliasing the stock's backing array. Two owners then touched the same element memory under different synchronization rules:

  • alphaTask submits its pairs to an ants pool. Each worker writes the tablePair element it was handed (pState, and the payload errChan) without holding d.Lock — collection code treats the handed-over slice as exclusive to the invocation — and alphaTask itself rewrites and reslices tbls as batches advance.
  • A second tableStatsExecutor invocation for the same dynamicCtx can overlap it (a cron retrigger or heartbeat-expiry window racing the async-task row update that guards the executor's Concurrency=1 admission). It mutates the same backing array while holding d.Lock: getChangedTableList appends (in-place writes until capacity is exhausted, then runtime.growslice reads and copies the old elements), and cleanTableStock nils out and truncates the slice.

The result is the CI-captured pair reported in the issue: an ants worker writing tbls[i].pState while another round's getChangedTableList appended to the same backing array.

Exact change

pkg/vm/engine/disttae/mo_table_stats.go:

  • New dynamicCtx.snapshotTableStock(): takes d.Lock and returns an exact-size copy of d.tableStock.tbls, so the collection round's memory is detached from the collector's stock.
  • New dynamicCtx.runStatsCollectionRound(ctx, service): the executor's per-tick handoff, now a named production seam that calls alphaTask(ctx, service, d.snapshotTableStock(), "main routine"). tableStatsExecutor calls it in place of the previous inline aliasing handoff.
  • alphaTask's doc comment now states the exclusive-ownership caller contract: its pool workers write the handed-over elements without d.Lock, so the slice must be exclusive to the invocation.

pkg/vm/engine/disttae/mo_table_stats_test.go — new TestTableStatsExecutorDetachesStockFromAlphaTask with two subtests, both driving the production runStatsCollectionRound handoff (not a test copy of it):

  • collects a round while another collector mutates the stock: a produced-pair phase barrier proves a worker already wrote and transmitted its element while the round is still in flight; a second collector's stock mutation (cleanTableStock plus locked appends with cap == len growth, reproducing getChangedTableList's append and the growslice read of the CI report) overlaps the remaining worker; the round must complete with timeout == false, err == nil, and the stock afterwards must contain only collector-written elements.
  • cancellation of an in-flight round reports ctx error: behind the same phase barrier, mid-flight cancellation must return context.Canceled while the stock stays consistent.
  • The fixture is the queue consumer sending exactly one Done per pair (matching errWaitToReceive; launchTask is a no-op so no production beta task consumes the queue), represents that consumer as the running beta so alphaTask cannot end the round through its not-running-beta timeout shortcut, gives every round its own context.WithCancel with a joined cancellation cleanup, and uses one-minute select deadlines instead of sleeps.

Issue-to-test proof (red/green on the same byte-identical test)

The committed test was run against the assigned base 6cbe375b496 with the production handoff alone restored to the base aliasing expression — the only executed production difference between the two trees; the test files are byte-identical on both sides (SHA256 41a094cb847b499817b813eb53223a27d2b4f2cc88b99a6e5faccaccb7c0622d):

  • RED (base ownership), focused -race run at -count=1: exit 1 with 3 WARNING: DATA RACE reports; the recorded pair is the production ants worker's element write (alphaTask.func2, mo_table_stats.go:2101, reached through runStatsCollectionRound) racing the locked collector's cleanTableStock rewrite (mo_table_stats.go:1727), with alpha logs showing processed=2/1 — real in-flight work, no early exit. Repeated at -count=10: 6 race reports, exit 1.
  • GREEN (this change): the same test passes under -race at -count=1 (both subtests) and at -count=100 (ok 5.138s); the cancel subtest returns context.Canceled.
  • Owning package after the change: ./pkg/vm/engine/disttae/ green under -race (ok 16.035s) and in normal mode (ok 12.507s); full package selection (583 tests, including the pre-existing TestAlphaTask) verified non-empty.

Test commands

pkg/vm/engine/disttae is CGo-transitive; natives come from make cgo and the repository's CGo test wrapper is used:

# focused regression through the production handoff (green on this branch)
.agents/skills/mo-dev/scripts/mo-cgo-test -race -v \
  -run '^TestTableStatsExecutorDetachesStockFromAlphaTask$' \
  -count=1 -timeout 300s ./pkg/vm/engine/disttae/

# owning package, race and normal modes
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout 1800s ./pkg/vm/engine/disttae/
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout 1800s ./pkg/vm/engine/disttae/

# incremental statics for the changed package
gofmt -l pkg/vm/engine/disttae/mo_table_stats.go pkg/vm/engine/disttae/mo_table_stats_test.go
GOWORK=off go vet -mod=readonly ./pkg/vm/engine/disttae/
golangci-lint run -c .golangci.yml \
  --new-from-rev 6cbe375b49696021d72778baa292a66287f080bd \
  ./pkg/vm/engine/disttae/

All of the above pass on this change; the RED runs are reproduction-only evidence recorded at the base ownership harness and are not part of this branch.

Residual risks

  • Overlapping tableStatsExecutor invocations remain possible at the cron-framework level; after this change each round owns a detached snapshot, so no unsynchronized element memory is shared. Duplicate pair processing through tblQueue is a pre-existing framework trait outside this change.
  • snapshotTableStock adds one exact-size element copy per round under d.Lock, bounded by the stock length and dominated by the per-table I/O the round performs anyway.
  • Adjacent latent defect recorded for follow-up and deliberately out of scope: when a pair carries onlyUpdateTS (no production builder creates such pairs today), betaTask's batch path sends a second Done per pair and, under adverse scheduling, can send on a closed errQueue. This regression's fixture consumer sends exactly one Done per pair and exercises the alpha side only.
  • No SQL-visible behavior changes, so no BVT is attached; repo-wide SCA and the large cluster suites are left to CI.

tableStatsExecutor handed alphaTask a slice aliasing
dynamicCtx.tableStock.tbls's backing array. alphaTask dispatches its pairs
to an ants pool whose workers write the handed-over tablePair elements
(pState, errChan) without holding d.Lock - the invocation owns that memory
exclusively - and alphaTask itself rewrites and reslices tbls as batches
advance. A concurrent tableStatsExecutor invocation for the same
dynamicCtx (a cron retrigger or heartbeat-expiry window racing the async-task
row update that guards the executor's Concurrency=1 admission) mutates the
same backing array under d.Lock: getChangedTableList appends to it (in-place
writes, then growslice reads and copies the old elements) and cleanTableStock
nils and truncates it. The unsynchronized worker element writes therefore
race the locked collector rewrites, which is the data race reported in
issue matrixorigin#27702 (an ants worker writing tbls[i].pState while getChangedTableList
appended to the same backing array through runtime.growslice).

The stock now stays exclusively inside the d.Lock discipline:
snapshotTableStock takes the lock and returns an exact-size copy of the
pending pairs, and the executor's per-tick handoff runStatsCollectionRound
passes that detached snapshot to alphaTask, so every round owns its pairs
through completion and no unsynchronized element memory is shared between
overlapping rounds. alphaTask's exclusive-ownership caller contract is
documented at its definition. The added copy is one stock length per round
under the lock, dominated by the per-table work the round performs anyway.

The regression drives this production handoff function under the race
detector. With the base aliasing expression restored in that single executed
hunk, the same byte-identical test reports the data race at the assigned
base (3 race reports at -count=1, 6 at -count=10, exit 1); with this change
it completes the round without the not-running-beta timeout, returns
context.Canceled when an in-flight round is canceled, and the whole owning
disttae package stays green under -race and in normal mode.

Related to matrixorigin#27702
@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 commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 6f3a042b8e192f33343a78680f9e633c0d8060f9

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 6f3a042b8e192f33343a78680f9e633c0d8060f9

Assessment: approve

Reviewed the complete two-file delta, callers, ownership, cancellation, cleanup and test design. The locked snapshot correctly gives alpha workers exclusive ownership without holding the collector lock during worker I/O. Shallow copying is sufficient because stock builders leave worker-owned pointers and channels unset. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Confirmed exact HEAD, clean source, complete frozen patch, formatting and whitespace. Isolation preflight passed; native prerequisites were built from matching revision inputs.

  • The focused regression passed under the race detector, followed by 100 successful repetitions covering collection and cancellation.

  • A diagnostic overlay restoring only the old slice alias reproduced four data-race reports with the committed tests unchanged. Its expected failure confirms regression sensitivity.

  • The handoff benchmark measured one allocation per nonempty snapshot: approximately 0.10 ms/1 MiB for 8,192 entries and 21.7 ms/122 MiB for one million entries. This linear background-round cost is justified by ownership isolation; foreground SQL paths do not invoke the new handoff.

  • Reused the frozen exact-head CI snapshot reporting successful build, UT, coverage, static analysis and BVT checks.

  • Commands, source fingerprints, exit receipts and retained logs were reconciled in /home/xupeng/.local/state/mo-bot/jobs/c044761b3cfd689b45d9fc44/attempt-1/validation-report.json; review coverage is recorded in review-scope.json.

Limitations:

  • The focused fixture exercises the production handoff and alpha workers with a controlled queue consumer, not full scheduler execution or beta SQL persistence.

  • Performance measurements isolate handoff cost; they do not establish end-to-end SQL throughput or contended-lock latency.

  • Broad CI evidence consists of the supplied exact-head status snapshot, without raw CI logs. The linked issue's original incident artifacts were not supplied.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-23 08:18 UTC · Rule: main · triggered by @gouhongshen with the @mergifyio queue command
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-10-23 12:58 UTC · at b2992ed7f7d0c057729ff7ff868a3179a0e2770f

This pull request spent 4 hours 40 minutes 26 seconds in the queue, with no time running CI.

Reason

The merge conditions cannot be satisfied due to failing checks

  • CI Required

Failing checks:

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@mergify mergify Bot added the queued label Oct 23, 2026
@gouhongshen

Copy link
Copy Markdown
Contributor Author

The Matrixone UT Coverage execution / UT Coverage on Ubuntu/x86 failure at the merge-queue head b2992ed is the open lockservice bug #29447, outside this PR's change.

What happened: the queue's in-place merge pulled the new pkg/tests/issues/isolated/idle_lock_route_scale_down_test.go (from main #30832) into this head. TestDropDatabaseAfterCatalogCleanupDuringCNScaleDown failed because the survivor CN's drop database idle_route_after_scale returned Error 20702 (HY000): lock table bind changed after exhausting the 10s lock retry budget on mo_catalog.mo_database_defaults (table-id 272438) — the exact failure class #29447 tracks, including the same table-id recorded in the 2026-10-23 evidence there.

Why it is unrelated: this PR's delta is only the disttae statistics collector's alpha-worker snapshot handoff (pkg/vm/engine/disttae/mo_table_stats.go + its test); it touches none of the lockservice/lock-op/catalog-DDL/executor paths the failing statement exercises, and the failing test does not exist in this branch's history — it arrived via the Mergify merge of a newer main. Evidence and reproduction record: #29447 (comment)

Blocker removal is verified resolution of the linked issue / a passing coverage run at a current head.

@XuPeng-SH
XuPeng-SH merged commit f8c8720 into matrixorigin:main Oct 23, 2026
33 of 36 checks passed
@mergify mergify Bot added dequeued and removed queued labels Oct 23, 2026

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants