Skip to content

refactor(schedule): harden runtime worker scheduling - #25564

Merged
XuPeng-SH merged 2 commits into
mainfrom
refactor_schedule_phase6_0709
Jul 10, 2026
Merged

XuPeng-SH merged 2 commits into
mainfrom
refactor_schedule_phase6_0709

Conversation

@XuPeng-SH

Copy link
Copy Markdown
Contributor

What this PR does

This PR is the final phase of the scheduling subsystem refactor (#25451). It introduces runtime worker state awareness, hardens dispatch API correctness, and adds full scheduling observability.

Runtime-aware worker scheduling

  • Worker type gains a WorkerState field (Unknown / Working / Draining / Drained)
  • selectEligibleCandidateWorkers filters candidates by runtime state (Draining/Drained are ineligible)
  • DecideQueryPlacement checks CurrentCN runtime state before ensureCurrentWorker/preferCurrentWorker
  • All dropped workers are recorded in QueryDecision.Dropped with structured cause reasons

Dispatch API hardening

  • New constructLocalDispatchFromScopes replaces the unsafe pattern of discarding hasRemote from constructDispatchLocalAndRemote
  • Cross-CN targets, nil source, missing proc, and index out-of-bounds are rejected at compile time with descriptive errors
  • All 4 call sites that previously discarded hasRemote now use the safe local-only constructor

Malformed address detection

  • Removed isSameCN and its dangerous "malformed address → treat as same CN" fallback
  • Added validateRemoteRunAddress — rejects malformed remote addresses at RemoteRun entry
  • ipAddrMatch/sameExecutionAddr now strictly compare strings (no silent lenience)

Scheduling observability

  • New scheduling_trace.go records full query-level and scan-level scheduling decisions
  • Tracks candidate/selected/dropped counts per reason, fallback decisions, and selected-worker failures

Cancel signal propagation

  • waitRemoteRegsReady now correctly propagates context.CancelCause instead of silently swallowing cancellation

Bug fix

  • compileExternScanParallelWrite now uses c.addr instead of empty string for constructScopeForExternal, fixing a hang with compressed file LOAD DATA (root cause: sameExecutionNode("", addr) → false exposed the missing address)

Type of change

  • Refactoring / Performance improvement
  • Bug fix
  • New feature
  • Documentation
  • Testing
  • CI/CD

Related issues

Testing

  • TestConstructLocalDispatchFromScopesRejectsRemoteTarget — dispatch API safety
  • TestWaitRemoteRegsReadyPropagatesCancelCause — cancel propagation
  • TestValidateRemoteRunAddressRejectsMalformedRemote — address validation
  • TestDecideQueryPlacementRejectsRequiredDrainingCurrentCN — CurrentCN runtime filtering (Required)
  • TestDecideQueryPlacementDoesNotPreferDrainingCurrentCandidate — CurrentCN runtime filtering (Preferred)
  • TestDecideQueryPlacementDoesNotFallbackToDrainedCurrentCN — no fallback to unhealthy CN
  • TestDecideQueryPlacementDropsRuntimeIneligibleCandidates — candidate filtering
  • TestDecideQueryPlacementFallsBackWhenCandidatesAreRuntimeIneligible — fallback edge case
  • TestScheduleQueryWorkersRejectsDrainingRequiredCurrentCN — integration test
  • TestScheduleQueryWorkersDropsRuntimeIneligibleCandidates — integration test
  • TestScheduleQueryWorkersFallsBackWhenCandidatesRuntimeIneligible — integration test
  • TestValidateScheduledQueryRoutesRejectsRuntimeIneligibleSelectedWorker — defense-in-depth
  • TestRecordScanSchedulingTrace — trace observability
  • TestScheduleQueryWorkersKeepsLocalExecTypesFromRuntimeStateLookup — TP/AP-oneCN isolation

Checklist

  • I have performed a self-review of my own code
  • I have added tests that prove my fix/refactor is effective
  • New and existing unit tests pass locally with my changes
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (inline comments)

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

Blocking findings:

  1. High: malformed remote-address rejection returns before pipeline cleanup, so a nested producer can still hang its receiver.

Scope.RemoteRun returns directly from the new validation branch at pkg/sql/compile/scope.go:400, before pipeline.New(...) and CleanRootOperator(...). For a Remote pre-scope whose root is a connector/dispatch, no terminal signal is sent to its downstream register. MergeRun starts that producer and then synchronously runs the parent merge pipeline before it reads preScopeResultReceiveChan; the parent can therefore block on the receiver forever even though the producer error is already buffered.

I reproduced this with a malformed Remote scope rooted at a connector: RemoteRun returned the expected error, but the connected PipelineEdge received no terminal signal within 100ms. Calling cleanPipelineWitchStartFail(s, err, c.isPrepare) before returning made the same regression test pass. Please make every pre-execution failure exit use the same cleanup path, and add a bounded test that both verifies receiver termination and, ideally, that an outer MergeRun returns.

  1. Medium: malformedExecutionAddr is not an address validator.

The colon-count check at pkg/sql/compile/compile.go:5567 accepts malformed values such as host: or :, while rejecting valid bracketed IPv6 endpoints such as [2001:db8::1]:6001. A malformed value that happens to contain one colon still bypasses the guard and reaches RPC dialing, so the hardening is incomplete. Please parse the declared endpoint format with net.SplitHostPort (plus the required host/port checks), and cover missing host/port, invalid port, hostname/IPv4, and bracketed IPv6 according to the supported address contract.

  1. Medium: the advertised scheduling observability is currently internal dead state, and runtime-drop accounting is not reachable in the real engine path.

scheduleTrace is only written, asserted by unit tests, and cleared; there is no metric/log/statement-trace/exported consumer. It also stores only lastScan, so a multi-scan query overwrites earlier decisions. In addition, disttae.Engine.Nodes still uses GetCNService, which filters Draining/Drained CNs before they reach selectEligibleCandidateWorkers; the new draining/drained dropped counters are therefore populated by mocks but not by production discovery. Please either wire this into an actual low-cardinality observability sink with all scan decisions and preserve upstream drop reasons, or remove/defer the unused trace state and narrow the PR claim.

The new scheduling/dispatch unit cases and the schedule package pass locally, and CI is otherwise green/pending on two jobs, but they do not cover finding 1.

@XuPeng-SH
XuPeng-SH requested a review from aptend as a code owner July 10, 2026 00:05

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

Addressed the blocking review in 44e3540c1:

  • All RemoteRun pre-start validation failures now use the pipeline start-failure cleanup path. Added both direct receiver-terminal coverage and a bounded outer MergeRun regression; the hang tests pass 100 consecutive runs and under -race.
  • Remote endpoints now use net.SplitHostPort plus non-empty host and numeric port-range validation, with hostname, IPv4, bracketed IPv6, missing host/port, invalid port, zero/overflow port, and unbracketed IPv6 coverage.
  • Replaced the private last-value trace with registered low-cardinality Prometheus decision/drop/failure and worker/input metrics. Every scan is recorded; no CN IDs or addresses are labels. Draining/Drained candidates filtered by cluster discovery are surfaced to scheduler accounting without replacing the existing working-CN label fallback.
  • Local dispatch construction now rejects empty targets and validates every target before mutating receiver state.

Local validation passed: full pkg/sql/compile, pkg/vm/engine/disttae, and pkg/vm/engine/memoryengine test binaries; pkg/sql/schedule; targeted race tests; go vet for all changed packages; and git diff --check.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Self-review note from a correctness / unhappy-path pass:

I walked this PR from the following angles:

  • runtime-aware candidate filtering and CurrentCN policy behavior
  • local-only dispatch hardening vs accidental remote registration
  • malformed remote-address rejection and pre-start cleanup
  • cancel/timeout propagation for remote receiver registration waits
  • engine/runtime-state propagation into scheduler inputs and final route validation

I did not find a blocking correctness or unhappy-path issue in this change set. The added tests also cover the key regressions and failure paths well.

GitHub does not allow the PR author account to approve its own pull request, so I am recording the conclusion here instead of an approval review.

@XuPeng-SH
XuPeng-SH merged commit 6891155 into main Jul 10, 2026
32 checks passed
@XuPeng-SH
XuPeng-SH deleted the refactor_schedule_phase6_0709 branch July 24, 2026 03:21
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
)

## What this PR does

This PR is the final phase of the scheduling subsystem refactor
(matrixorigin#25451). It introduces runtime worker state awareness, hardens dispatch
API correctness, and adds full scheduling observability.

### Runtime-aware worker scheduling
- `Worker` type gains a `WorkerState` field (Unknown / Working /
Draining / Drained)
- `selectEligibleCandidateWorkers` filters candidates by runtime state
(Draining/Drained are ineligible)
- `DecideQueryPlacement` checks CurrentCN runtime state before
`ensureCurrentWorker`/`preferCurrentWorker`
- All dropped workers are recorded in `QueryDecision.Dropped` with
structured cause reasons

### Dispatch API hardening
- **New `constructLocalDispatchFromScopes`** replaces the unsafe pattern
of discarding `hasRemote` from `constructDispatchLocalAndRemote`
- Cross-CN targets, nil source, missing proc, and index out-of-bounds
are rejected at compile time with descriptive errors
- All 4 call sites that previously discarded `hasRemote` now use the
safe local-only constructor

### Malformed address detection
- Removed `isSameCN` and its dangerous "malformed address → treat as
same CN" fallback
- Added `validateRemoteRunAddress` — rejects malformed remote addresses
at `RemoteRun` entry
- `ipAddrMatch`/`sameExecutionAddr` now strictly compare strings (no
silent lenience)

### Scheduling observability
- New `scheduling_trace.go` records full query-level and scan-level
scheduling decisions
- Tracks candidate/selected/dropped counts per reason, fallback
decisions, and selected-worker failures

### Cancel signal propagation
- `waitRemoteRegsReady` now correctly propagates `context.CancelCause`
instead of silently swallowing cancellation

### Bug fix
- `compileExternScanParallelWrite` now uses `c.addr` instead of empty
string for `constructScopeForExternal`, fixing a hang with compressed
file LOAD DATA (root cause: `sameExecutionNode("", addr)` → false
exposed the missing address)

## Type of change

- [x] Refactoring / Performance improvement
- [x] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Testing
- [ ] CI/CD

## Related issues

- Closes matrixorigin#25451
- Closes matrixorigin#25554 (LOAD DATA hang)

## Testing

- `TestConstructLocalDispatchFromScopesRejectsRemoteTarget` — dispatch
API safety
- `TestWaitRemoteRegsReadyPropagatesCancelCause` — cancel propagation
- `TestValidateRemoteRunAddressRejectsMalformedRemote` — address
validation
- `TestDecideQueryPlacementRejectsRequiredDrainingCurrentCN` — CurrentCN
runtime filtering (Required)
- `TestDecideQueryPlacementDoesNotPreferDrainingCurrentCandidate` —
CurrentCN runtime filtering (Preferred)
- `TestDecideQueryPlacementDoesNotFallbackToDrainedCurrentCN` — no
fallback to unhealthy CN
- `TestDecideQueryPlacementDropsRuntimeIneligibleCandidates` — candidate
filtering
- `TestDecideQueryPlacementFallsBackWhenCandidatesAreRuntimeIneligible`
— fallback edge case
- `TestScheduleQueryWorkersRejectsDrainingRequiredCurrentCN` —
integration test
- `TestScheduleQueryWorkersDropsRuntimeIneligibleCandidates` —
integration test
- `TestScheduleQueryWorkersFallsBackWhenCandidatesRuntimeIneligible` —
integration test
-
`TestValidateScheduledQueryRoutesRejectsRuntimeIneligibleSelectedWorker`
— defense-in-depth
- `TestRecordScanSchedulingTrace` — trace observability
- `TestScheduleQueryWorkersKeepsLocalExecTypesFromRuntimeStateLookup` —
TP/AP-oneCN isolation

## Checklist

- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix/refactor is effective
- [x] New and existing unit tests pass locally with my changes
- [ ] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation (inline
comments)
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
)

## What this PR does

This PR is the final phase of the scheduling subsystem refactor
(matrixorigin#25451). It introduces runtime worker state awareness, hardens dispatch
API correctness, and adds full scheduling observability.

### Runtime-aware worker scheduling
- `Worker` type gains a `WorkerState` field (Unknown / Working /
Draining / Drained)
- `selectEligibleCandidateWorkers` filters candidates by runtime state
(Draining/Drained are ineligible)
- `DecideQueryPlacement` checks CurrentCN runtime state before
`ensureCurrentWorker`/`preferCurrentWorker`
- All dropped workers are recorded in `QueryDecision.Dropped` with
structured cause reasons

### Dispatch API hardening
- **New `constructLocalDispatchFromScopes`** replaces the unsafe pattern
of discarding `hasRemote` from `constructDispatchLocalAndRemote`
- Cross-CN targets, nil source, missing proc, and index out-of-bounds
are rejected at compile time with descriptive errors
- All 4 call sites that previously discarded `hasRemote` now use the
safe local-only constructor

### Malformed address detection
- Removed `isSameCN` and its dangerous "malformed address → treat as
same CN" fallback
- Added `validateRemoteRunAddress` — rejects malformed remote addresses
at `RemoteRun` entry
- `ipAddrMatch`/`sameExecutionAddr` now strictly compare strings (no
silent lenience)

### Scheduling observability
- New `scheduling_trace.go` records full query-level and scan-level
scheduling decisions
- Tracks candidate/selected/dropped counts per reason, fallback
decisions, and selected-worker failures

### Cancel signal propagation
- `waitRemoteRegsReady` now correctly propagates `context.CancelCause`
instead of silently swallowing cancellation

### Bug fix
- `compileExternScanParallelWrite` now uses `c.addr` instead of empty
string for `constructScopeForExternal`, fixing a hang with compressed
file LOAD DATA (root cause: `sameExecutionNode("", addr)` → false
exposed the missing address)

## Type of change

- [x] Refactoring / Performance improvement
- [x] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Testing
- [ ] CI/CD

## Related issues

- Closes matrixorigin#25451
- Closes matrixorigin#25554 (LOAD DATA hang)

## Testing

- `TestConstructLocalDispatchFromScopesRejectsRemoteTarget` — dispatch
API safety
- `TestWaitRemoteRegsReadyPropagatesCancelCause` — cancel propagation
- `TestValidateRemoteRunAddressRejectsMalformedRemote` — address
validation
- `TestDecideQueryPlacementRejectsRequiredDrainingCurrentCN` — CurrentCN
runtime filtering (Required)
- `TestDecideQueryPlacementDoesNotPreferDrainingCurrentCandidate` —
CurrentCN runtime filtering (Preferred)
- `TestDecideQueryPlacementDoesNotFallbackToDrainedCurrentCN` — no
fallback to unhealthy CN
- `TestDecideQueryPlacementDropsRuntimeIneligibleCandidates` — candidate
filtering
- `TestDecideQueryPlacementFallsBackWhenCandidatesAreRuntimeIneligible`
— fallback edge case
- `TestScheduleQueryWorkersRejectsDrainingRequiredCurrentCN` —
integration test
- `TestScheduleQueryWorkersDropsRuntimeIneligibleCandidates` —
integration test
- `TestScheduleQueryWorkersFallsBackWhenCandidatesRuntimeIneligible` —
integration test
-
`TestValidateScheduledQueryRoutesRejectsRuntimeIneligibleSelectedWorker`
— defense-in-depth
- `TestRecordScanSchedulingTrace` — trace observability
- `TestScheduleQueryWorkersKeepsLocalExecTypesFromRuntimeStateLookup` —
TP/AP-oneCN isolation

## Checklist

- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix/refactor is effective
- [x] New and existing unit tests pass locally with my changes
- [ ] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation (inline
comments)
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
)

## What this PR does

This PR is the final phase of the scheduling subsystem refactor
(matrixorigin#25451). It introduces runtime worker state awareness, hardens dispatch
API correctness, and adds full scheduling observability.

### Runtime-aware worker scheduling
- `Worker` type gains a `WorkerState` field (Unknown / Working /
Draining / Drained)
- `selectEligibleCandidateWorkers` filters candidates by runtime state
(Draining/Drained are ineligible)
- `DecideQueryPlacement` checks CurrentCN runtime state before
`ensureCurrentWorker`/`preferCurrentWorker`
- All dropped workers are recorded in `QueryDecision.Dropped` with
structured cause reasons

### Dispatch API hardening
- **New `constructLocalDispatchFromScopes`** replaces the unsafe pattern
of discarding `hasRemote` from `constructDispatchLocalAndRemote`
- Cross-CN targets, nil source, missing proc, and index out-of-bounds
are rejected at compile time with descriptive errors
- All 4 call sites that previously discarded `hasRemote` now use the
safe local-only constructor

### Malformed address detection
- Removed `isSameCN` and its dangerous "malformed address → treat as
same CN" fallback
- Added `validateRemoteRunAddress` — rejects malformed remote addresses
at `RemoteRun` entry
- `ipAddrMatch`/`sameExecutionAddr` now strictly compare strings (no
silent lenience)

### Scheduling observability
- New `scheduling_trace.go` records full query-level and scan-level
scheduling decisions
- Tracks candidate/selected/dropped counts per reason, fallback
decisions, and selected-worker failures

### Cancel signal propagation
- `waitRemoteRegsReady` now correctly propagates `context.CancelCause`
instead of silently swallowing cancellation

### Bug fix
- `compileExternScanParallelWrite` now uses `c.addr` instead of empty
string for `constructScopeForExternal`, fixing a hang with compressed
file LOAD DATA (root cause: `sameExecutionNode("", addr)` → false
exposed the missing address)

## Type of change

- [x] Refactoring / Performance improvement
- [x] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Testing
- [ ] CI/CD

## Related issues

- Closes matrixorigin#25451
- Closes matrixorigin#25554 (LOAD DATA hang)

## Testing

- `TestConstructLocalDispatchFromScopesRejectsRemoteTarget` — dispatch
API safety
- `TestWaitRemoteRegsReadyPropagatesCancelCause` — cancel propagation
- `TestValidateRemoteRunAddressRejectsMalformedRemote` — address
validation
- `TestDecideQueryPlacementRejectsRequiredDrainingCurrentCN` — CurrentCN
runtime filtering (Required)
- `TestDecideQueryPlacementDoesNotPreferDrainingCurrentCandidate` —
CurrentCN runtime filtering (Preferred)
- `TestDecideQueryPlacementDoesNotFallbackToDrainedCurrentCN` — no
fallback to unhealthy CN
- `TestDecideQueryPlacementDropsRuntimeIneligibleCandidates` — candidate
filtering
- `TestDecideQueryPlacementFallsBackWhenCandidatesAreRuntimeIneligible`
— fallback edge case
- `TestScheduleQueryWorkersRejectsDrainingRequiredCurrentCN` —
integration test
- `TestScheduleQueryWorkersDropsRuntimeIneligibleCandidates` —
integration test
- `TestScheduleQueryWorkersFallsBackWhenCandidatesRuntimeIneligible` —
integration test
-
`TestValidateScheduledQueryRoutesRejectsRuntimeIneligibleSelectedWorker`
— defense-in-depth
- `TestRecordScanSchedulingTrace` — trace observability
- `TestScheduleQueryWorkersKeepsLocalExecTypesFromRuntimeStateLookup` —
TP/AP-oneCN isolation

## Checklist

- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix/refactor is effective
- [x] New and existing unit tests pass locally with my changes
- [ ] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation (inline
comments)

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

Projects

None yet

2 participants