Skip to content

dxf: acquire cross-keyspace runtimes in framework managers - #69065

Merged
ti-chi-bot[bot] merged 10 commits into
pingcap:masterfrom
D3Hunter:crossks-clean-dxf-part-change
Jun 10, 2026
Merged

ti-chi-bot[bot] merged 10 commits into
pingcap:masterfrom
D3Hunter:crossks-clean-dxf-part-change

Conversation

@D3Hunter

@D3Hunter D3Hunter commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: ref #68883

Problem Summary:

NextGen DXF tasks can execute against user keyspaces while the framework manager runs from the SYSTEM keyspace. The framework previously resolved raw keyspace stores for scheduler and task executor creation, which left runtime ownership implicit and made it harder for cross-keyspace runtime cleanup to know when DXF was still using a runtime.

What changed and how does it work?

  • Add pkg/dxf/framework/dxfutil.CheckRuntime to validate that a task runtime's store and system session pool both point at the task keyspace.
  • Pass sqlsvrapi.Runtime through scheduler and task executor params, while keeping TaskStore temporarily for existing task implementations.
  • Acquire cross-keyspace runtime handles in the DXF scheduler manager with bookkeepers in the form DXF/scheduler/<taskID>, and release them after scheduler exit or scheduler initialization failure.
  • Acquire cross-keyspace runtime handles in the DXF task executor manager with bookkeepers in the form DXF/executor/<taskID>, and release them after executor exit or executor startup failure paths.
  • Use the instance runtime directly for same-keyspace tasks, where no acquired handle needs to be released.
  • Add unit coverage for runtime validation, acquisition failures, and release behavior in scheduler and task executor startup paths.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Unit tests and manual checks:

make bazel_prepare
git diff --check upstream/master...HEAD
go test -run TestCheckRuntime -tags=intest,deadlock ./pkg/dxf/framework/dxfutil -count=1
./tools/check/failpoint-go-test.sh pkg/dxf/framework/scheduler -run 'Test(StartSchedulerCrossKeyspaceRuntime|BaseSchedulerInitChecksTaskRuntime|ManagerSchedulerNotAllocateSlots)' -count=1
./tools/check/failpoint-go-test.sh pkg/dxf/framework/taskexecutor -run 'Test(StartTaskExecutorCrossKeyspaceRuntime|StartTaskExecutorResolveTaskRuntimeFromTaskKeyspace|StartTaskExecutorResolveTaskRuntimeError|BaseTaskExecutorInitChecksTaskRuntime)' -count=1
make lint

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

Improve DXF cross-keyspace runtime cleanup by acquiring and releasing task runtime handles in framework managers.

Summary by CodeRabbit

  • New Features
    • Added a utility to acquire and validate per-task SQL runtimes for cross-keyspace tasks.
  • Chores
    • Scheduler and executor startup/cleanup now use the new runtime flow and pass runtime-backed storage to task components.
    • Build/test rules updated to include new runtime utilities.
  • Bug Fixes
    • Stronger validation and clearer errors for runtime/storage keyspace mismatches; ensured runtimes are released on failure and exit.
  • Tests
    • Expanded unit coverage for cross-keyspace acquisition, release, error paths, and startup behaviors.

@ti-chi-bot ti-chi-bot Bot added the release-note Denotes a PR that will be considered when it comes time to generate release notes. label Jun 9, 2026
@pantheon-ai

pantheon-ai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

@D3Hunter I've received your pull request and will start the review. I'll conduct a thorough review covering code quality, potential issues, and implementation details.

⏳ This process typically takes 10-30 minutes depending on the complexity of the changes.

ℹ️ Learn more details on Pantheon AI.

@ti-chi-bot ti-chi-bot Bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds dxfutil runtime helpers to acquire and validate per-task sqlsvrapi.Runtime, threads TaskRuntime through scheduler and taskexecutor params, updates start paths to acquire/release KS runtimes, and adds tests and BUILD rule updates covering cross-keyspace and mismatch cases.

Changes

Cross-Keyspace Runtime Integration for DXF Scheduler and TaskExecutor

Layer / File(s) Summary
dxfutil: Runtime-keyspace validation utility
pkg/dxf/framework/dxfutil/BUILD.bazel, pkg/dxf/framework/dxfutil/util.go, pkg/dxf/framework/dxfutil/util_test.go
New AcquireTaskRuntime and CheckTaskRuntime utilities; BUILD/test targets added; unit tests for matching keyspaces, mismatch, and error cases.
Scheduler: Param field and validation wiring
pkg/dxf/framework/scheduler/BUILD.bazel, pkg/dxf/framework/scheduler/interface.go, pkg/dxf/framework/scheduler/scheduler.go
Adds TaskRuntime sqlsvrapi.Runtime to Param, updates BUILD deps, imports dxfutil, and delegates BaseScheduler.Init() keyspace validation to dxfutil.CheckTaskRuntime.
Scheduler manager: Acquire/release KS runtime
pkg/dxf/framework/scheduler/scheduler_manager.go
startScheduler resolves a per-task KS runtime via AcquireTaskRuntime when needed, passes TaskRuntime/TaskStore into schedulers, and uses a releaseRuntime closure to release handles on init failure and exit.
Scheduler tests: runtime/session mocks and cross-keyspace cases
pkg/dxf/framework/scheduler/scheduler_nokit_test.go, pkg/dxf/framework/scheduler/scheduler_manager_nokit_test.go
Adds test helpers/wrappers for mocking sqlsvrapi runtimes/KS handles and WithNewSession expectations; introduces TestBaseSchedulerInitChecksTaskRuntime and TestStartSchedulerCrossKeyspaceRuntime and wires expectations into existing tests.
TaskExecutor: Param field and validation wiring
pkg/dxf/framework/taskexecutor/BUILD.bazel, pkg/dxf/framework/taskexecutor/task_executor.go
Adds TaskRuntime sqlsvrapi.Runtime to Param, updates BUILD deps, imports dxfutil, and delegates BaseTaskExecutor.Init() validation to dxfutil.CheckTaskRuntime.
TaskExecutor manager: Acquire/release KS runtime
pkg/dxf/framework/taskexecutor/manager.go
startTaskExecutor acquires a per-task KS runtime via AcquireTaskRuntime (DXF/executor bookkeeper) when needed, passes TaskRuntime to executor params, derives TaskStore from taskRuntime.Store(), and releases the handle on failure and exit.
TaskExecutor tests: runtime/session mocks and cross-keyspace cases
pkg/dxf/framework/taskexecutor/task_executor_test.go, pkg/dxf/framework/taskexecutor/manager_test.go
Refactors manager tests to use sqlsvrapimock, adds TestBaseTaskExecutorInitChecksTaskRuntime, TestStartTaskExecutorCrossKeyspaceRuntime, resolution and error tests, and wires runtime/session expectations into existing manager tests.

Sequence Diagram(s)

sequenceDiagram
  participant Manager
  participant SessionProvider
  participant SQLServer
  participant KSRuntimeHandle
  Manager->>SessionProvider: WithNewSession(cb)
  SessionProvider->>SQLServer: GetRuntime() or AcquireKSRuntime(taskKS, holder)
  SQLServer-->>Manager: Runtime (KSRuntimeHandle if acquired)
  Manager->>KSRuntimeHandle: Release() (via returned release closure)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • pingcap/tidb#68890: Implements sqlsvrapi.KSRuntimeHandle and Server.AcquireKSRuntime, which this PR uses for runtime acquisition/release.
  • pingcap/tidb#68824: Related work resolving per-task keyspace stores for executors; overlaps with alternative approaches to task runtime/store resolution.
  • pingcap/tidb#69046: Introduces sqlsvrapi.Runtime APIs (e.g., SysSessionPool) relied on by dxfutil and tests.

Suggested labels

size/XL, ok-to-test, approved, lgtm

Suggested reviewers

  • joechenrh
  • wjhuang2016

"I hop through sessions, tiny and spry,
I fetch a runtime beneath the sky,
I hold it gently, then let it go,
Tests nod and pass in a tidy row,
A rabbit's cheer for code that flies high." 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'dxf: acquire cross-keyspace runtimes in framework managers' accurately and concisely summarizes the main objective: acquiring cross-keyspace runtimes in DXF framework managers.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@tiprow

tiprow Bot commented Jun 9, 2026

Copy link
Copy Markdown

Hi @D3Hunter. Thanks for your PR.

PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test all.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/dxf/framework/scheduler/scheduler_manager.go (1)

378-388: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard nil scheduler factory before invoking it to avoid panic + runtime-handle leak.

Line 378 can still return nil (e.g., type drift between task fetch phases). Calling it at Line 379 panics, and an acquired cross-keyspace runtime from earlier lines is never released.

Suggested fix
 	schedulerFactory := getSchedulerFactory(task.Type)
+	if schedulerFactory == nil {
+		err := errors.Errorf("unknown task type %s", task.Type)
+		sm.logger.Warn("unknown task type when starting scheduler",
+			zap.Int64("task-id", task.ID),
+			zap.String("task-key", task.Key),
+			zap.Error(err))
+		sm.failTask(task.ID, task.State, err)
+		releaseRuntime()
+		return
+	}
 	scheduler := schedulerFactory(sm.ctx, task, Param{
 		taskMgr:        sm.taskMgr,
 		nodeMgr:        sm.nodeMgr,
 		slotMgr:        sm.slotMgr,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/scheduler/scheduler_manager.go` around lines 378 - 388,
Check whether getSchedulerFactory(task.Type) returned nil before calling it: if
schedulerFactory is nil, release the previously acquired task runtime
(taskRuntime) using its cleanup method (e.g., Release/Close) to avoid the
runtime handle leak, and return or continue with an error path instead of
invoking schedulerFactory; otherwise call schedulerFactory as before to create
scheduler. Ensure you reference getSchedulerFactory, schedulerFactory, scheduler
and taskRuntime/TaskRuntime in the fix.
🧹 Nitpick comments (1)
pkg/dxf/framework/dxfutil/BUILD.bazel (1)

21-21: ⚡ Quick win

Drop default flakiness for this new unit test target.

flaky = True on Line 21 weakens CI signal and can hide regressions; prefer keeping it non-flaky unless there is a known tracked flake.

Suggested change
 go_test(
     name = "dxfutil_test",
     timeout = "short",
     srcs = ["util_test.go"],
     embed = [":dxfutil"],
-    flaky = True,
     deps = [
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/dxfutil/BUILD.bazel` at line 21, The test target currently
sets flaky = True which weakens CI signal; remove the flaky = True attribute (or
set flaky = False) from the target declaration in BUILD.bazel so the unit test
runs as a non-flaky target; locate the entry that contains the flaky = True line
and delete or change that attribute to False in the target block.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/dxf/framework/taskexecutor/task_executor.go`:
- Around line 86-95: NewParamForTest builds a Param but leaves Param.TaskRuntime
nil, which causes BaseTaskExecutor.Init to panic when it calls
dxfutil.CheckRuntime(e.TaskRuntime,...). Update NewParamForTest to initialize
TaskRuntime using the provided TaskStore (kv.Storage) — e.g., create/obtain the
runtime instance from the store via your existing runtime constructor/factory
and assign it to param.TaskRuntime — or explicitly document that callers must
set Param.TaskRuntime before calling Init; reference NewParamForTest,
Param.TaskRuntime, TaskStore, BaseTaskExecutor.Init, and dxfutil.CheckRuntime
when making the change.

---

Outside diff comments:
In `@pkg/dxf/framework/scheduler/scheduler_manager.go`:
- Around line 378-388: Check whether getSchedulerFactory(task.Type) returned nil
before calling it: if schedulerFactory is nil, release the previously acquired
task runtime (taskRuntime) using its cleanup method (e.g., Release/Close) to
avoid the runtime handle leak, and return or continue with an error path instead
of invoking schedulerFactory; otherwise call schedulerFactory as before to
create scheduler. Ensure you reference getSchedulerFactory, schedulerFactory,
scheduler and taskRuntime/TaskRuntime in the fix.

---

Nitpick comments:
In `@pkg/dxf/framework/dxfutil/BUILD.bazel`:
- Line 21: The test target currently sets flaky = True which weakens CI signal;
remove the flaky = True attribute (or set flaky = False) from the target
declaration in BUILD.bazel so the unit test runs as a non-flaky target; locate
the entry that contains the flaky = True line and delete or change that
attribute to False in the target block.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3c8e6a54-d615-41f1-bf13-0525a967644f

📥 Commits

Reviewing files that changed from the base of the PR and between d42b17d and e5fc31a.

📒 Files selected for processing (14)
  • pkg/dxf/framework/dxfutil/BUILD.bazel
  • pkg/dxf/framework/dxfutil/util.go
  • pkg/dxf/framework/dxfutil/util_test.go
  • pkg/dxf/framework/scheduler/BUILD.bazel
  • pkg/dxf/framework/scheduler/interface.go
  • pkg/dxf/framework/scheduler/scheduler.go
  • pkg/dxf/framework/scheduler/scheduler_manager.go
  • pkg/dxf/framework/scheduler/scheduler_manager_nokit_test.go
  • pkg/dxf/framework/scheduler/scheduler_nokit_test.go
  • pkg/dxf/framework/taskexecutor/BUILD.bazel
  • pkg/dxf/framework/taskexecutor/manager.go
  • pkg/dxf/framework/taskexecutor/manager_test.go
  • pkg/dxf/framework/taskexecutor/task_executor.go
  • pkg/dxf/framework/taskexecutor/task_executor_test.go

Comment on lines 86 to 95
func NewParamForTest(taskTable TaskTable, slotMgr *slotManager, nodeRc *proto.NodeResource, execID string, store kv.Storage) Param {
return Param{
param := Param{
taskTable: taskTable,
slotMgr: slotMgr,
nodeRc: nodeRc,
execID: execID,
TaskStore: store,
}
return param
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

NewParamForTest does not initialize TaskRuntime, which may cause nil-pointer issues.

The function creates a Param without setting TaskRuntime. Since BaseTaskExecutor.Init now calls dxfutil.CheckRuntime(e.TaskRuntime, ...), tests using NewParamForTest followed by Init will panic on a nil TaskRuntime.

Consider initializing TaskRuntime from the provided store, or document that callers must set it separately.

Suggested fix
 func NewParamForTest(taskTable TaskTable, slotMgr *slotManager, nodeRc *proto.NodeResource, execID string, store kv.Storage) Param {
 	param := Param{
 		taskTable: taskTable,
 		slotMgr:   slotMgr,
 		nodeRc:    nodeRc,
 		execID:    execID,
 		TaskStore: store,
+		// Note: Callers needing Init() must set TaskRuntime explicitly.
 	}
 	return param
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func NewParamForTest(taskTable TaskTable, slotMgr *slotManager, nodeRc *proto.NodeResource, execID string, store kv.Storage) Param {
return Param{
param := Param{
taskTable: taskTable,
slotMgr: slotMgr,
nodeRc: nodeRc,
execID: execID,
TaskStore: store,
}
return param
}
func NewParamForTest(taskTable TaskTable, slotMgr *slotManager, nodeRc *proto.NodeResource, execID string, store kv.Storage) Param {
param := Param{
taskTable: taskTable,
slotMgr: slotMgr,
nodeRc: nodeRc,
execID: execID,
TaskStore: store,
// Note: Callers needing Init() must set TaskRuntime explicitly.
}
return param
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/taskexecutor/task_executor.go` around lines 86 - 95,
NewParamForTest builds a Param but leaves Param.TaskRuntime nil, which causes
BaseTaskExecutor.Init to panic when it calls
dxfutil.CheckRuntime(e.TaskRuntime,...). Update NewParamForTest to initialize
TaskRuntime using the provided TaskStore (kv.Storage) — e.g., create/obtain the
runtime instance from the store via your existing runtime constructor/factory
and assign it to param.TaskRuntime — or explicitly document that callers must
set Param.TaskRuntime before calling Init; reference NewParamForTest,
Param.TaskRuntime, TaskStore, BaseTaskExecutor.Init, and dxfutil.CheckRuntime
when making the change.

@codecov

codecov Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 1.33333% with 74 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.8955%. Comparing base (d42b17d) to head (3f503d3).
⚠️ Report is 13 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #69065        +/-   ##
================================================
- Coverage   76.3233%   74.8955%   -1.4278%     
================================================
  Files          2041       2030        -11     
  Lines        562646     571250      +8604     
================================================
- Hits         429430     427841      -1589     
- Misses       132305     143216     +10911     
+ Partials        911        193       -718     
Flag Coverage Δ
integration 41.2994% <0.0000%> (+1.5781%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 60.4610% <ø> (ø)
parser ∅ <ø> (∅)
br 49.4562% <ø> (-13.3346%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/dxf/framework/scheduler/interface.go (1)

193-198: Review: Guard against nil TaskRuntime only when Init() is called

scheduler.NewParamForTest leaves Param.TaskRuntime nil, and BaseScheduler.Init() calls dxfutil.CheckRuntime(s.TaskRuntime, ...), which unconditionally invokes runtime.Store()—so calling Init() with this Param would panic.

Current usages of scheduler.NewParamForTest are limited to pkg/dxf/importinto/scheduler_testkit_test.go (4 call sites), and that test file does not call Init() on the returned scheduler, so the panic path isn’t exercised. If future tests call Init() for schedulers created via this helper, they must set TaskRuntime (mock runtime) or avoid Init().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/scheduler/interface.go` around lines 193 - 198,
NewParamForTest currently leaves Param.TaskRuntime nil which will cause
BaseScheduler.Init to panic because BaseScheduler.Init calls
dxfutil.CheckRuntime(s.TaskRuntime, ...) and that ends up invoking
runtime.Store(); fix by initializing Param.TaskRuntime in NewParamForTest to a
lightweight/noop/mock TaskRuntime instance so callers that later call
BaseScheduler.Init won't hit the nil path (i.e., set Param.TaskRuntime to a
simple mock/noop runtime when constructing the Param in NewParamForTest);
alternatively, if you prefer the nil-safe approach, add a nil-check in
BaseScheduler.Init before calling dxfutil.CheckRuntime/Store to skip
runtime.Store when TaskRuntime is nil (reference symbols: NewParamForTest,
Param.TaskRuntime, BaseScheduler.Init, dxfutil.CheckRuntime, runtime.Store).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/dxf/framework/scheduler/interface.go`:
- Around line 193-198: NewParamForTest currently leaves Param.TaskRuntime nil
which will cause BaseScheduler.Init to panic because BaseScheduler.Init calls
dxfutil.CheckRuntime(s.TaskRuntime, ...) and that ends up invoking
runtime.Store(); fix by initializing Param.TaskRuntime in NewParamForTest to a
lightweight/noop/mock TaskRuntime instance so callers that later call
BaseScheduler.Init won't hit the nil path (i.e., set Param.TaskRuntime to a
simple mock/noop runtime when constructing the Param in NewParamForTest);
alternatively, if you prefer the nil-safe approach, add a nil-check in
BaseScheduler.Init before calling dxfutil.CheckRuntime/Store to skip
runtime.Store when TaskRuntime is nil (reference symbols: NewParamForTest,
Param.TaskRuntime, BaseScheduler.Init, dxfutil.CheckRuntime, runtime.Store).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: cb417f69-77a5-443f-98eb-83bf166b247d

📥 Commits

Reviewing files that changed from the base of the PR and between e5fc31a and 9d3bb1a.

📒 Files selected for processing (3)
  • pkg/dxf/framework/scheduler/interface.go
  • pkg/dxf/framework/scheduler/scheduler_manager_nokit_test.go
  • pkg/dxf/framework/scheduler/scheduler_nokit_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/dxf/framework/scheduler/scheduler_manager_nokit_test.go
  • pkg/dxf/framework/scheduler/scheduler_nokit_test.go

@D3Hunter

D3Hunter commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

/retest

@tiprow

tiprow Bot commented Jun 9, 2026

Copy link
Copy Markdown

@D3Hunter: PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test.

Details

In response to this:

/retest

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

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

Summary

  • Total findings: 7
  • Inline comments: 7
  • Summary-only findings (no inline anchor): 0
Findings (highest risk first)

⚠️ [Major] (2)

  1. Base Init no longer honors TaskStore-only params (pkg/dxf/framework/scheduler/scheduler.go:126; pkg/dxf/framework/taskexecutor/task_executor.go:264; pkg/dxf/framework/scheduler/interface.go:193; pkg/dxf/framework/taskexecutor/task_executor.go:86)
  2. Scheduler runtime handle is not released if factory lookup fails (pkg/dxf/framework/scheduler/scheduler_manager.go:356)

🟡 [Minor] (4)

  1. Runtime validation name drops the task-keyspace contract (pkg/dxf/framework/dxfutil/util.go:63)
  2. Runtime holder identifier uses two names (pkg/dxf/framework/scheduler/scheduler_manager.go:355)
  3. Runtime validation utility is coupled to task storage internals (pkg/dxf/framework/dxfutil/util.go:63)
  4. New dxfutil test target is marked flaky (pkg/dxf/framework/dxfutil/BUILD.bazel:21)

ℹ️ [Info] (1)

  1. SessionProvider adds an unnecessary exported helper type (pkg/dxf/framework/dxfutil/util.go:26)

Comment thread pkg/dxf/framework/dxfutil/util.go Resolved
Comment thread pkg/dxf/framework/dxfutil/util.go Resolved
Comment thread pkg/dxf/framework/dxfutil/BUILD.bazel Resolved
Comment thread pkg/dxf/framework/dxfutil/util.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/dxf/framework/dxfutil/util.go (1)

64-75: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard CheckTaskRuntime against nil runtime internals to avoid panic paths.

At Line 65, runtime.Store().GetKeyspace() can panic if runtime (or Store()) is nil; similarly runtime.SysSessionPool() at Line 72 can be nil. This validator should return contextual errors instead of crashing caller initialization.

Suggested patch
 func CheckTaskRuntime(runtime sqlsvrapi.Runtime, taskKS string) error {
-	storeKS := runtime.Store().GetKeyspace()
+	if runtime == nil {
+		return errors.Trace(fmt.Errorf("invalid task runtime: runtime is nil"))
+	}
+	store := runtime.Store()
+	if store == nil {
+		return errors.Trace(fmt.Errorf("invalid task runtime: store is nil"))
+	}
+	if runtime.SysSessionPool() == nil {
+		return errors.Trace(fmt.Errorf("invalid task runtime: sys session pool is nil"))
+	}
+	storeKS := store.GetKeyspace()
 	if storeKS != taskKS {
 		// shouldn't happen normally, but since keyspace mismatch might cause
 		// correctness error, we check it at runtime too.
 		return errors.Trace(fmt.Errorf("store keyspace mismatch with task: %s vs %s",
 			storeKS, taskKS))
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/dxf/framework/dxfutil/util.go` around lines 64 - 75, In CheckTaskRuntime,
guard against nil internals: check that runtime is non-nil, that runtime.Store()
is non-nil before calling GetKeyspace(), and that runtime.SysSessionPool() is
non-nil before passing it to storage.NewTaskManager; if any are nil return a
contextual error (use errors.Trace(fmt.Errorf(...))) instead of proceeding. Also
inside the taskMgr.WithNewSession callback, validate that the session context
(se) and se.GetStore() are non-nil before calling GetKeyspace() and return a
descriptive error if they are; reference CheckTaskRuntime, runtime.Store(),
runtime.SysSessionPool(), storage.NewTaskManager, taskMgr.WithNewSession, and
se.GetStore() when locating where to add these checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@pkg/dxf/framework/dxfutil/util.go`:
- Around line 64-75: In CheckTaskRuntime, guard against nil internals: check
that runtime is non-nil, that runtime.Store() is non-nil before calling
GetKeyspace(), and that runtime.SysSessionPool() is non-nil before passing it to
storage.NewTaskManager; if any are nil return a contextual error (use
errors.Trace(fmt.Errorf(...))) instead of proceeding. Also inside the
taskMgr.WithNewSession callback, validate that the session context (se) and
se.GetStore() are non-nil before calling GetKeyspace() and return a descriptive
error if they are; reference CheckTaskRuntime, runtime.Store(),
runtime.SysSessionPool(), storage.NewTaskManager, taskMgr.WithNewSession, and
se.GetStore() when locating where to add these checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b58c938f-a98b-4ea6-a854-11eb65632fd5

📥 Commits

Reviewing files that changed from the base of the PR and between 94601f8 and 306dacb.

📒 Files selected for processing (8)
  • pkg/dxf/framework/dxfutil/util.go
  • pkg/dxf/framework/dxfutil/util_test.go
  • pkg/dxf/framework/scheduler/scheduler.go
  • pkg/dxf/framework/scheduler/scheduler_manager.go
  • pkg/dxf/framework/scheduler/scheduler_manager_nokit_test.go
  • pkg/dxf/framework/taskexecutor/manager.go
  • pkg/dxf/framework/taskexecutor/manager_test.go
  • pkg/dxf/framework/taskexecutor/task_executor.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/dxf/framework/scheduler/scheduler_manager.go
  • pkg/dxf/framework/taskexecutor/task_executor.go
  • pkg/dxf/framework/dxfutil/util_test.go
  • pkg/dxf/framework/taskexecutor/manager_test.go

@ingress-bot

Copy link
Copy Markdown

🔍 Starting code review for this PR...

// See the License for the specific language governing permissions and
// limitations under the License.

package dxfutil

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.

Why not naming util directly, since it lies in dxf package

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.

as there are many pkg called util, if we import them both, we have to add alias(such as dxfutil) to difference them, as we have done for this one in taskexecutor pkg. so i choose to name it as dxfutil directly

tidbutil "github.com/pingcap/tidb/pkg/util"

@ti-chi-bot ti-chi-bot Bot added approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jun 10, 2026

@ingress-bot ingress-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This review was generated by AI and should be verified by a human reviewer.
Manual follow-up is recommended before merge.

Summary

  • Total findings: 6
  • Inline comments: 3
  • Summary-only findings (no inline anchor): 3
Findings (highest risk first)

🟡 [Minor] (3)

  1. Transitional TaskStore comment lacks removal tracking on a public field (pkg/dxf/framework/scheduler/interface.go:188, pkg/dxf/framework/taskexecutor/task_executor.go:81)
  2. New mock-runtime / session-pool test helpers duplicated across four DXF test packages (pkg/dxf/framework/scheduler/scheduler_nokit_test.go:54, pkg/dxf/framework/taskexecutor/task_executor_test.go:56, pkg/dxf/importinto/scheduler_test.go:48, pkg/dxf/framework/dxfutil/util_test.go:188)
  3. Executor releases the keyspace runtime handle after removing itself from the started-set, opening a holderID-collision restart window (pkg/dxf/framework/taskexecutor/manager.go:370, pkg/dxf/framework/scheduler/scheduler_manager.go:386, pkg/domain/crossks/cross_ks.go:145)

ℹ️ [Info] (1)

  1. Runtime handle release is not panic-safe, unlike the adjacent deferred slot free (pkg/dxf/framework/taskexecutor/manager.go:335, pkg/dxf/framework/scheduler/scheduler_manager.go:356, pkg/domain/crossks/cross_ks.go:383)

🧹 [Nit] (2)

  1. Init keyspace-check tests bundle three scenarios into one function, hurting failure isolation (pkg/dxf/framework/scheduler/scheduler_nokit_test.go:80, pkg/dxf/framework/taskexecutor/task_executor_test.go:173)
  2. Unrelated log-line reformatting mixed into the runtime-migration change (pkg/dxf/framework/scheduler/scheduler.go:119)

Unanchored findings

🟡 [Minor] (1)

  1. Transitional TaskStore comment lacks removal tracking on a public field
    • Request: Add a tracking reference (issue/PR) and concrete removal condition to the TaskStore comment, or mark it Deprecated: so callers know it is the legacy field and which migration unblocks its removal. Keep the wording identical across both Param structs.

ℹ️ [Info] (1)

  1. Runtime handle release is not panic-safe, unlike the adjacent deferred slot free
    • Request: Acquire the handle under a deferred release with an ownership-transfer flag (release only when not handed to the running goroutine), so a panic during factory/Init cannot leak the keyspace runtime, consistent with how the slot is already protected.

🧹 [Nit] (1)

  1. Init keyspace-check tests bundle three scenarios into one function, hurting failure isolation
    • Request: Wrap each keyspace scenario in its own t.Run subtest (as in util_test.go) so a single regressing branch fails in isolation and remains diagnosable.

return sePool
}

func newMockRuntime(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 [Minor] New mock-runtime / session-pool test helpers duplicated across four DXF test packages

Impact
The same newMockRuntime and newSessionPoolForStore scaffolding is copy-pasted into four DXF test files instead of living in the existing shared framework/testutil.
Future changes to the sqlsvrapi.Runtime mock surface must be applied in four places, and the copies can silently drift.

Scope

  • pkg/dxf/framework/scheduler/scheduler_nokit_test.go:54 — newMockRuntime
  • pkg/dxf/framework/taskexecutor/task_executor_test.go:56 — newMockRuntime
  • pkg/dxf/importinto/scheduler_test.go:48 — newMockRuntime
  • pkg/dxf/framework/dxfutil/util_test.go:188 — newCheckTaskRuntimeMockRuntime

Evidence
newMockRuntime (wrapping sqlsvrapimock.NewMockRuntime + Store()/SysSessionPool() expectations) and newSessionPoolForStore (wrapping tidbutil.NewSessionPool) are defined nearly verbatim in scheduler, taskexecutor, and importinto test files, with the same pattern reimplemented under different names in dxfutil/util_test.go. The PR already imports //pkg/dxf/framework/testutil in these test targets.

Change request
Hoist the shared newMockRuntime / newSessionPoolForStore builders into pkg/dxf/framework/testutil (exported) and consume them from the four test packages to keep one source of truth for the runtime mock setup.

}
s.task.Store(task)
logger.Info("create base scheduler", zap.Stringer("task-type", task.Type), zap.Bool("allocated-slots", param.allocatedSlots))
logger.Info("create base scheduler", zap.Stringer("task-type", task.Type),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 [Nit] Unrelated log-line reformatting mixed into the runtime-migration change

NewBaseScheduler has an unrelated cosmetic reformat of the existing create base scheduler log statement folded into a behavior-changing PR.
This adds reviewer noise and blurs which lines are functional changes versus formatting churn.

@ti-chi-bot

ti-chi-bot Bot commented Jun 10, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: joechenrh, wjhuang2016

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added the lgtm label Jun 10, 2026
@ti-chi-bot ti-chi-bot Bot removed the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Jun 10, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jun 10, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-06-10 08:47:39.037536959 +0000 UTC m=+949760.107854369: ☑️ agreed by joechenrh.
  • 2026-06-10 14:38:40.167156429 +0000 UTC m=+970821.237473829: ☑️ agreed by wjhuang2016.

@ti-chi-bot
ti-chi-bot Bot merged commit ca36959 into pingcap:master Jun 10, 2026
34 of 36 checks passed
@D3Hunter
D3Hunter deleted the crossks-clean-dxf-part-change branch June 11, 2026 03:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants