Skip to content

*: reset prepare checker once the cache is reset#8860

Open
rleungx wants to merge 16 commits into
tikv:masterfrom
rleungx:reset-prepared
Open

*: reset prepare checker once the cache is reset#8860
rleungx wants to merge 16 commits into
tikv:masterfrom
rleungx:reset-prepared

Conversation

@rleungx

@rleungx rleungx commented Nov 28, 2024

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: Close #8634, might fix #8689

What is changed and how does it work?

Check List

Tests

  • Unit test

Release note

None.

Summary by CodeRabbit

  • Bug Fixes
    • Cache-clearing actions now fully reset scheduling readiness, so operators and region scheduling resume correctly after an admin reset.
    • Improved scheduling startup behavior to wait for the system to be ready before running patrol and dispatch work, reducing premature operations.
    • Adjusted recovery flows to clear readiness state as part of cleanup, helping avoid stale scheduling state after recovery.

@ti-chi-bot ti-chi-bot Bot added do-not-merge/needs-linked-issue release-note-none Denotes a PR that doesn't merit a release note. dco-signoff: yes Indicates the PR's author has signed the dco. size/S Denotes a PR that changes 10-29 lines, ignoring generated files. and removed do-not-merge/needs-linked-issue labels Nov 28, 2024
@codecov

codecov Bot commented Nov 28, 2024

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.09804% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.21%. Comparing base (8abdf30) to head (6a3ca64).
⚠️ Report is 7 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #8860      +/-   ##
==========================================
- Coverage   79.26%   79.21%   -0.06%     
==========================================
  Files         541      541              
  Lines       75674    75751      +77     
==========================================
+ Hits        59985    60005      +20     
- Misses      11467    11505      +38     
- Partials     4222     4241      +19     
Flag Coverage Δ
unittests 79.21% <95.09%> (-0.06%) ⬇️

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lhy1024 lhy1024 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. Do we need a unit test for it?

@ti-chi-bot ti-chi-bot Bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Nov 29, 2024
@rleungx

rleungx commented Nov 29, 2024

Copy link
Copy Markdown
Member Author

/hold

@ti-chi-bot ti-chi-bot Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Nov 29, 2024
@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Dec 2, 2024
@ti-chi-bot

ti-chi-bot Bot commented Dec 2, 2024

Copy link
Copy Markdown
Contributor

[LGTM Timeline notifier]

Timeline:

  • 2024-11-29 08:05:45.749481506 +0000 UTC m=+796533.369136021: ☑️ agreed by lhy1024.
  • 2024-12-02 09:44:37.166732665 +0000 UTC m=+1061664.786387215: ☑️ agreed by okJiang.

@ti-chi-bot ti-chi-bot Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/S Denotes a PR that changes 10-29 lines, ignoring generated files. labels Dec 2, 2024
@rleungx rleungx force-pushed the reset-prepared branch 2 times, most recently from 9101749 to be95f0c Compare December 2, 2024 10:02

@lhy1024 lhy1024 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

BTW, do we need pick it to 8.5?

}

// NewController create a new Controller.
func NewController(ctx context.Context, cluster sche.CheckerCluster, conf config.CheckerConfigProvider, ruleManager *placement.RuleManager, labeler *labeler.RegionLabeler, opController *operator.Controller) *Controller {
func NewController(ctx context.Context, cluster sche.CheckerCluster, conf config.CheckerConfigProvider, ruleManager *placement.RuleManager, labeler *labeler.RegionLabeler, opController *operator.Controller, prepareChecker *sche.PrepareChecker) *Controller {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

BTW, this function has too many parameters. Do we have any good way to solve it?

Comment thread pkg/schedule/coordinator.go Outdated
Comment on lines -225 to -234
if c.ShouldRun(collectWaitTime...) {
log.Info("coordinator has finished cluster information preparation")
break
}
select {
case <-ticker.C:
case <-c.ctx.Done():
log.Info("coordinator stops running")
return
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need the similar log?

@ti-chi-bot ti-chi-bot Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Dec 4, 2024
@rleungx rleungx force-pushed the reset-prepared branch 2 times, most recently from c3f0411 to ad5fe05 Compare December 5, 2024 03:34
@rleungx

rleungx commented Dec 5, 2024

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot ti-chi-bot Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Dec 5, 2024
@rleungx

rleungx commented Dec 5, 2024

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot

ti-chi-bot Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: lhy1024, okJiang

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

@coderabbitai

coderabbitai Bot commented Jul 6, 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

The prepare checker is extracted into a dedicated preparecheck package with exported Checker, NewChecker, Check, RunIfPrepared, and ResetPrepared. Scheduler and checker controllers gate patrol/dispatch on readiness. ResetPrepared() is wired through admin cache-reset and unsafe-recovery completion paths. Tests, minor logging, and an example test removal are included.

Changes

Prepare checker gating and cache-reset wiring

Layer / File(s) Summary
Extract exported preparecheck.Checker
pkg/schedule/preparecheck/prepare_checker.go, pkg/schedule/preparecheck/prepare_checker_test.go
Renames prepareChecker/newPrepareChecker/check to exported Checker/NewChecker/Check, adds RunIfPrepared and ResetPrepared, and moves the code into a new package with a matching test.
Wire prepare checker into Coordinator lifecycle
pkg/schedule/coordinator.go
Coordinator constructs a Checker, injects it into scheduler and checker controllers, runs a periodic runPrepareChecker goroutine, and exposes it via ShouldRun()/GetPrepareChecker().
Gate scheduler and checker patrol loops on readiness
pkg/schedule/schedulers/scheduler_controller.go, pkg/schedule/checker/checker_controller.go, pkg/schedule/checker/checker_controller_test.go
Controllers accept optional preparecheck.Checker instances, default to an auto-prepared one, and gate patrol/priority-region/operator-dispatch and scheduling ticks with RunIfPrepared/IsPrepared.
Expose and invoke ResetPrepared across cluster and admin endpoints
pkg/mock/mockcluster/mockcluster.go, pkg/unsaferecovery/unsafe_recovery_controller.go, server/api/admin.go, pkg/mcs/scheduling/server/apis/v1/api.go, pkg/mcs/scheduling/server/cluster.go, server/cluster/scheduling_controller.go
Adds ResetPrepared() methods on cluster interfaces/implementations and calls them before ResetRegionCache() in admin cache-reset and unsafe-recovery finish paths.
Update tests to mark checker prepared and add coverage
server/cluster/cluster_test.go, tests/server/api/diagnostic_test.go, tests/server/api/api_test.go, tests/server/api/region_test.go, tests/server/cluster/cluster_test.go, server/cluster/split_scatter_test.go, tests/server/storage/hot_region_storage_test.go
Adds SetPrepared()/ResetPrepared() calls to existing tests, adds a new TestDeleteAllRegionCacheScheduling test, adjusts region suite failpoint setup, and waits for storage iteration to complete.
Miscellaneous cleanups
pkg/btree/btree_generic_test.go, pkg/mcs/scheduling/server/server.go, tools/pd-ctl/pdctl/command/operator_command.go, tools/pd-ctl/tests/store/store_test.go
Removes an unused example test, updates leader-switch log field names, switches pd-ctl output to cmd.Println, and adds a blank line.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Admin as Admin API
  participant Cluster
  participant Coordinator
  participant Checker as preparecheck.Checker
  participant SchedulerController
  participant CheckerController

  Coordinator->>Checker: NewChecker(...)
  Coordinator->>SchedulerController: NewController(..., Checker)
  Coordinator->>CheckerController: NewController(..., Checker)
  loop every 3s
    Coordinator->>Checker: Check(cluster)
  end
  Admin->>Cluster: DeleteAllRegionCache
  Cluster->>Coordinator: ResetPrepared()
  Coordinator->>Checker: ResetPrepared()
  Cluster->>Cluster: ResetRegionCache()
  SchedulerController->>Checker: RunIfPrepared(scheduleFn)
  CheckerController->>Checker: RunIfPrepared(patrolFn)
Loading

Possibly related PRs

  • tikv/pd#10621: Both PRs modify the scheduling checker_controller patrol loop, interacting with the new prepareChecker gating and constructor wiring.
  • tikv/pd#10689: Both PRs modify the DeleteAllRegionCache admin handler in server/api/admin.go, directly overlapping in the same code path.

Suggested reviewers: lhy1024, JmPotato

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The template is mostly present, but the "What is changed and how does it work?" section is effectively empty. Add a concise implementation summary explaining the cache-reset and prepare-checker changes, and fill in the commit-message block.
Linked Issues check ⚠️ Warning The cache-reset behavior for #8634 is addressed, but there is no clear fix for the flaky TestStoreLimit issue #8689. Add the actual #8689 TestStoreLimit fix or remove that issue reference if it is not part of this PR.
Out of Scope Changes check ⚠️ Warning Several unrelated edits appear, including deleting the BTree example and changing pd-ctl logging/output and unrelated tests. Split unrelated cleanup, logging, and test-only changes into separate PRs so this patch stays focused on prepare-checker reset behavior.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: resetting the prepare checker when cache is reset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@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/unsaferecovery/unsafe_recovery_controller.go (1)

587-592: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reset prepared before clearing the region cache
ResetRegionCache() can run while prepared is still true, so a scheduler tick may see an empty cache and keep going. Swap these two calls here and in server/api/admin.go (the same order is also used in pkg/mcs/scheduling/server/apis/v1/api.go).

🤖 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/unsaferecovery/unsafe_recovery_controller.go` around lines 587 - 592, The
Finished-state cleanup in UnsafeRecoveryController is resetting the region cache
before clearing the prepared flag, which can let scheduling observe an empty
cache while `prepared` is still true. Update the `Finished` branch in
`UnsafeRecoveryController` to call `ResetPrepared()` before
`ResetRegionCache()`, and make the same call-order swap in the matching admin
recovery path in `server/api/admin.go` and the API implementation in
`pkg/mcs/scheduling/server/apis/v1/api.go` so all recovery flows stay
consistent.
🧹 Nitpick comments (2)
pkg/schedule/preparecheck/prepare_checker.go (1)

102-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update the misleading "for test purpose" doc on ResetPrepared.

ResetPrepared is the load-bearing hook for this PR: it's invoked from production cache-reset paths (e.g. the admin/API deleteAllRegionCache handler → Cluster.ResetPrepared()coordinator.GetPrepareChecker().ResetPrepared()), not only from tests. The comment risks a future dev treating this as test-only and altering/removing it, breaking the delay-rebalancing behavior.

📝 Proposed doc fix
-// ResetPrepared is for test purpose
+// ResetPrepared resets the checker so that scheduling pauses until cluster
+// information is re-collected. It is invoked when the region cache is reset
+// (admin/API cache-reset and unsafe-recovery completion).
 func (checker *Checker) ResetPrepared() {
🤖 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/schedule/preparecheck/prepare_checker.go` around lines 102 - 108, The doc
comment on Checker.ResetPrepared is misleading because this method is used by
production cache-reset flows, not just tests. Update the comment to describe its
real role in resetting prepared state for cache/prepare workflows, and keep the
method name ResetPrepared as the key reference so future changes don’t treat it
as test-only. Make sure the wording reflects its usage from
Cluster.ResetPrepared and coordinator.GetPrepareChecker().ResetPrepared rather
than implying it’s only a test hook.
tests/server/api/api_test.go (1)

1758-1773: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test doesn't actually verify the "pause immediately after reset" behavior.

After calling the delete-cache API, the test manually calls RemoveOperators() then only checks eventual resumption via testutil.Eventually. It never asserts that scheduling is actually blocked right after ResetPrepared() runs (e.g. IsPrepared() returns false immediately, or the operator count stays at 0 before the readiness threshold is met). Given the tiny region set here, readiness could be re-achieved almost instantly on the next heartbeat regardless of whether ResetPrepared() works, so this test would likely still pass even if the reset had no effect — weakening its value as a regression guard for the PR's actual intent (delaying rebalancing until region data refreshes).

Consider adding an assertion right after the delete call that rc.GetCoordinator().GetPrepareChecker().IsPrepared() is false (or that operator count is 0) before triggering the next heartbeat.

♻️ Suggested strengthening of the assertion
 	output := sendRequest(re, addr, http.MethodDelete, http.StatusOK)
 	re.Contains(string(output), "All regions are removed from server cache")
+	re.False(rc.GetCoordinator().GetPrepareChecker().IsPrepared())
 	rc.GetOperatorController().RemoveOperators()
 	re.Equal(0, int(rc.GetOperatorController().OperatorCount(operator.OpSplit)))
🤖 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 `@tests/server/api/api_test.go` around lines 1758 - 1773, The delete-cache test
in api_test.go only checks eventual recovery and does not verify that scheduling
is blocked immediately after the cache reset. In the test around the delete API
call and the subsequent heartbeat, add an assertion using
rc.GetCoordinator().GetPrepareChecker().IsPrepared() (or the operator count via
rc.GetOperatorController()) right after the delete response and before
rc.HandleRegionHeartbeat(regionInfo) to confirm the reset takes effect
immediately, then keep the existing eventual resumption check as the follow-up.
🤖 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 `@server/api/admin.go`:
- Around line 157-158: The reset sequence in the admin handler should clear the
prepared state before the region cache so a patrol tick cannot run against a
cleared cache while prepared is still true. Update the reset logic in the admin
API flow around rc.ResetRegionCache and rc.ResetPrepared to either swap their
order or guard both operations with the same lock, keeping the two state changes
atomic.

---

Outside diff comments:
In `@pkg/unsaferecovery/unsafe_recovery_controller.go`:
- Around line 587-592: The Finished-state cleanup in UnsafeRecoveryController is
resetting the region cache before clearing the prepared flag, which can let
scheduling observe an empty cache while `prepared` is still true. Update the
`Finished` branch in `UnsafeRecoveryController` to call `ResetPrepared()` before
`ResetRegionCache()`, and make the same call-order swap in the matching admin
recovery path in `server/api/admin.go` and the API implementation in
`pkg/mcs/scheduling/server/apis/v1/api.go` so all recovery flows stay
consistent.

---

Nitpick comments:
In `@pkg/schedule/preparecheck/prepare_checker.go`:
- Around line 102-108: The doc comment on Checker.ResetPrepared is misleading
because this method is used by production cache-reset flows, not just tests.
Update the comment to describe its real role in resetting prepared state for
cache/prepare workflows, and keep the method name ResetPrepared as the key
reference so future changes don’t treat it as test-only. Make sure the wording
reflects its usage from Cluster.ResetPrepared and
coordinator.GetPrepareChecker().ResetPrepared rather than implying it’s only a
test hook.

In `@tests/server/api/api_test.go`:
- Around line 1758-1773: The delete-cache test in api_test.go only checks
eventual recovery and does not verify that scheduling is blocked immediately
after the cache reset. In the test around the delete API call and the subsequent
heartbeat, add an assertion using
rc.GetCoordinator().GetPrepareChecker().IsPrepared() (or the operator count via
rc.GetOperatorController()) right after the delete response and before
rc.HandleRegionHeartbeat(regionInfo) to confirm the reset takes effect
immediately, then keep the existing eventual resumption check as the follow-up.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5399764e-2f20-478e-bff8-4c2bd732121b

📥 Commits

Reviewing files that changed from the base of the PR and between 2b485f5 and 003eba3.

📒 Files selected for processing (19)
  • pkg/btree/btree_generic_test.go
  • pkg/mcs/scheduling/server/apis/v1/api.go
  • pkg/mcs/scheduling/server/cluster.go
  • pkg/mcs/scheduling/server/server.go
  • pkg/mock/mockcluster/mockcluster.go
  • pkg/schedule/checker/checker_controller.go
  • pkg/schedule/coordinator.go
  • pkg/schedule/preparecheck/prepare_checker.go
  • pkg/schedule/schedulers/scheduler_controller.go
  • pkg/unsaferecovery/unsafe_recovery_controller.go
  • server/api/admin.go
  • server/cluster/cluster_test.go
  • server/cluster/scheduling_controller.go
  • tests/server/api/api_test.go
  • tests/server/api/diagnostic_test.go
  • tests/server/api/region_test.go
  • tests/server/cluster/cluster_test.go
  • tools/pd-ctl/pdctl/command/operator_command.go
  • tools/pd-ctl/tests/store/store_test.go
💤 Files with no reviewable changes (1)
  • pkg/btree/btree_generic_test.go

Comment thread server/api/admin.go Outdated
@rleungx

rleungx commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

/retest

rleungx added 2 commits July 6, 2026 16:58
Signed-off-by: Ryan Leung <rleungx@gmail.com>
Signed-off-by: Ryan Leung <rleungx@gmail.com>
@ti-chi-bot ti-chi-bot Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Jul 6, 2026
rleungx added 2 commits July 6, 2026 17:45
Signed-off-by: Ryan Leung <rleungx@gmail.com>
Signed-off-by: Ryan Leung <rleungx@gmail.com>

# Conflicts:
#	pkg/unsaferecovery/unsafe_recovery_controller.go
@rleungx rleungx removed the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jul 6, 2026
Signed-off-by: Ryan Leung <rleungx@gmail.com>

@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

🧹 Nitpick comments (1)
pkg/schedule/operator/operator_controller.go (1)

661-673: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Inconsistent metric accounting vs. RemoveOperators.

For waiting operators, this loop explicitly increments operatorCounter.WithLabelValues(op.Desc(), "remove") in addition to whatever buryOperator records based on the resulting status (e.g. "cancel"). The running-operator path in RemoveOperators (Lines 634-649) does not do this extra "remove" increment for the same cancel-then-bury flow. This produces asymmetric metrics between the two operator classes now merged into one purge operation.

🤖 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/schedule/operator/operator_controller.go` around lines 661 - 673, The
waiting-operator branch in the purge loop is double-counting by incrementing
operatorCounter with "remove" before calling buryOperator, while the
running-operator path in RemoveOperators only relies on buryOperator for its
final status. Make the metric accounting symmetric by removing the extra
"remove" increment here or applying the same cancel-then-bury metric flow used
in RemoveOperators, using the waiting-operator handling in
operator_controller.go as the place to align the behavior.
🤖 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/schedule/operator/operator_controller.go`:
- Around line 651-674: RemoveAllOperators currently races with
PromoteWaitingOperator because RemoveOperators(), wop.Clear(), and later
promotion can interleave, letting a waiting operator be re-added after bulk
removal starts. Add a controller-level guard or shared lock around the full
remove-all flow and the promotion path in Controller.RemoveAllOperators and
Controller.PromoteWaitingOperator so dequeueing from wop and moving into
oc.operators cannot happen during a reset. Use the existing Controller, wop,
RemoveOperators, and PromoteWaitingOperator symbols to keep the atomicity
consistent.

---

Nitpick comments:
In `@pkg/schedule/operator/operator_controller.go`:
- Around line 661-673: The waiting-operator branch in the purge loop is
double-counting by incrementing operatorCounter with "remove" before calling
buryOperator, while the running-operator path in RemoveOperators only relies on
buryOperator for its final status. Make the metric accounting symmetric by
removing the extra "remove" increment here or applying the same cancel-then-bury
metric flow used in RemoveOperators, using the waiting-operator handling in
operator_controller.go as the place to align the behavior.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: d2ef4710-8e10-4217-9b87-36ede354a8b8

📥 Commits

Reviewing files that changed from the base of the PR and between 0f18547 and c4b3916.

📒 Files selected for processing (6)
  • pkg/mcs/scheduling/server/cluster.go
  • pkg/schedule/operator/operator_controller.go
  • pkg/schedule/operator/operator_controller_test.go
  • pkg/schedule/operator/waiting_operator.go
  • server/cluster/scheduling_controller.go
  • tests/server/api/api_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/server/api/api_test.go

Comment thread pkg/schedule/operator/operator_controller.go Outdated
This reverts commit c4b3916.

Signed-off-by: Ryan Leung <rleungx@gmail.com>
@rleungx

rleungx commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

/retest

Signed-off-by: Ryan Leung <rleungx@gmail.com>

@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/schedule/checker/checker_controller.go (1)

103-111: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Consolidate duplicated prepare-checker resolution logic.

The same "use override if provided, else build a default and SetPrepared()" block is copy-pasted here and in scheduler_controller.go (lines 66-71). Extracting it into a small helper in the preparecheck package would keep both call sites in sync as this logic evolves.

♻️ Suggested helper
// in pkg/schedule/preparecheck
func Resolve(totalRegionCountFn func() (int, error), checkers ...*Checker) *Checker {
	if len(checkers) > 0 && checkers[0] != nil {
		return checkers[0]
	}
	c := NewChecker(totalRegionCountFn)
	c.SetPrepared()
	return c
}
-	prepareChecker := preparecheck.NewChecker(cluster.GetPrepareRegionCount)
-	if len(prepareCheckers) > 0 && prepareCheckers[0] != nil {
-		prepareChecker = prepareCheckers[0]
-	} else {
-		prepareChecker.SetPrepared()
-	}
+	prepareChecker := preparecheck.Resolve(cluster.GetPrepareRegionCount, prepareCheckers...)
🤖 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/schedule/checker/checker_controller.go` around lines 103 - 111, The
prepare-checker selection logic in NewController is duplicated and should be
consolidated so both controller call sites stay consistent. Move the “use the
provided checker if present, otherwise create a default Checker and call
SetPrepared()” behavior into a small helper in the preparecheck package, such as
a Resolve-style function, and then update NewController to use that helper
instead of inlining the override/default logic.
🧹 Nitpick comments (1)
pkg/schedule/preparecheck/prepare_checker_test.go (1)

15-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing coverage for Check() readiness path.

This new test file only exercises RunIfPrepared/SetPrepared/ResetPrepared. Check() (the heartbeat-count/timeout-driven readiness transition referenced in the AI summary) isn't tested here, yet it's the primary mechanism by which prepared becomes true in production (vs. the test-only SetPrepared).

🤖 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/schedule/preparecheck/prepare_checker_test.go` around lines 15 - 47, The
new test only covers the manual prepared-state helpers in Checker, so add
coverage for the readiness transition driven by Check() as well. Extend
prepare_checker_test.go with a test that exercises NewChecker and Check() using
the heartbeat-count/timeout path from the implementation, asserting that
prepared becomes true only after the expected conditions are met and that
RunIfPrepared behavior reflects that state. Keep the focus on the Checker
methods Check, RunIfPrepared, SetPrepared, and ResetPrepared so the production
readiness flow is covered, not just the test-only helper path.
🤖 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/schedule/checker/checker_controller.go`:
- Around line 103-111: The prepare-checker selection logic in NewController is
duplicated and should be consolidated so both controller call sites stay
consistent. Move the “use the provided checker if present, otherwise create a
default Checker and call SetPrepared()” behavior into a small helper in the
preparecheck package, such as a Resolve-style function, and then update
NewController to use that helper instead of inlining the override/default logic.

---

Nitpick comments:
In `@pkg/schedule/preparecheck/prepare_checker_test.go`:
- Around line 15-47: The new test only covers the manual prepared-state helpers
in Checker, so add coverage for the readiness transition driven by Check() as
well. Extend prepare_checker_test.go with a test that exercises NewChecker and
Check() using the heartbeat-count/timeout path from the implementation,
asserting that prepared becomes true only after the expected conditions are met
and that RunIfPrepared behavior reflects that state. Keep the focus on the
Checker methods Check, RunIfPrepared, SetPrepared, and ResetPrepared so the
production readiness flow is covered, not just the test-only helper path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c19fa5f0-984a-4817-bc51-e09c09e804e6

📥 Commits

Reviewing files that changed from the base of the PR and between c4b3916 and a778ebd.

📒 Files selected for processing (8)
  • pkg/mcs/scheduling/server/cluster.go
  • pkg/schedule/checker/checker_controller.go
  • pkg/schedule/checker/checker_controller_test.go
  • pkg/schedule/preparecheck/prepare_checker.go
  • pkg/schedule/preparecheck/prepare_checker_test.go
  • pkg/schedule/schedulers/scheduler_controller.go
  • server/cluster/scheduling_controller.go
  • tests/server/api/api_test.go
💤 Files with no reviewable changes (2)
  • server/cluster/scheduling_controller.go
  • pkg/mcs/scheduling/server/cluster.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/schedule/preparecheck/prepare_checker.go
  • tests/server/api/api_test.go

@rleungx

rleungx commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

/hold

@ti-chi-bot ti-chi-bot Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jul 7, 2026
rleungx added 3 commits July 8, 2026 10:46
Signed-off-by: Ryan Leung <rleungx@gmail.com>
Signed-off-by: Ryan Leung <rleungx@gmail.com>
Signed-off-by: Ryan Leung <rleungx@gmail.com>
@rleungx

rleungx commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

/retest

1 similar comment
@rleungx

rleungx commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

/retest

rleungx added 2 commits July 13, 2026 16:57
Signed-off-by: Ryan Leung <rleungx@gmail.com>
Signed-off-by: Ryan Leung <rleungx@gmail.com>
@ti-chi-bot ti-chi-bot Bot added size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. and removed size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Jul 13, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

@rleungx: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
non-block/pull-unit-test-next-gen 390bbc3 link false /test pull-unit-test-next-gen

Full PR test history. Your PR dashboard.

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. I understand the commands that are listed here.

@rleungx

rleungx commented Jul 13, 2026

Copy link
Copy Markdown
Member Author

/test pull-unit-test-next-gen-3

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

Labels

approved dco-signoff: yes Indicates the PR's author has signed the dco. do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. lgtm release-note-none Denotes a PR that doesn't merit a release note. 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.

Prevent rebalancing immediately after resetting the cache TestStoreLimit is flaky

3 participants