Skip to content

fix(server): allow disabling periodic idle vNPU cleanup to avoid premature reclamation - #120

Open
dartagnanli wants to merge 1 commit into
Project-HAMi:mainfrom
dartagnanli:fix/disable-periodic-idle-vnpu-cleanup
Open

fix(server): allow disabling periodic idle vNPU cleanup to avoid premature reclamation#120
dartagnanli wants to merge 1 commit into
Project-HAMi:mainfrom
dartagnanli:fix/disable-periodic-idle-vnpu-cleanup

Conversation

@dartagnanli

@dartagnanli dartagnanli commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

What & Why

Issue #86 reports that the periodic idle vNPU cleanup goroutine (startPeriodicCheckIdleVNPUs) destroys vNPUs based solely on IsContainerUsed == 0. Because a vNPU allocated to a Pod that is already Running but whose container has not yet started using the NPU also reports IsContainerUsed == 0, the cleanup can reclaim the vNPU too early — breaking workloads (e.g. npu-smi info fails inside the container shortly after the Pod starts).

#86 is framed as a discussion and lists several more thorough directions (combining IsContainerUsed with Pod allocation state, adding a protection window, or a Pod-referenced rule like mind-cluster's DestroyNotUsedVNPU). Those require deeper changes to the cleanup policy.

This PR takes a smaller, complementary step: give operators a switch to disable the periodic cleanup goroutine so the premature-reclamation symptom stops on affected nodes without waiting for the larger redesign.

Changes

  • New bool flag --enable_periodic_idle_vnpu_cleanup (default false). When false, Start() does not launch the periodic startPeriodicCheckIdleVNPUs goroutine.
  • The one-shot CleanupIdleVNPUs() on plugin restart (cmd/main.go) is intentionally left unconditional and unchanged — it is a separate entry point. The flag name (enable_periodic_...) and its help text make this boundary explicit to avoid the "total cleanup switch" ambiguity.
  • Wiring threaded through NewPluginServer.

Scope note

This is a mitigation, not a full resolution of #86's cleanup-policy discussion. The flag defaults to false (periodic cleanup disabled) to stop the premature-reclamation symptom by default; setting it to true restores the previous behavior. Reviewers may prefer a different default — easy to adjust.

Testing

  • go build ./internal/server/... ./cmd/...
  • go vet ./internal/server/... ./cmd/...
  • go test ./internal/server/ — 109 passed, consistent with baseline (ran 3×)

Modernizations (in the touched files)

While editing these files I also applied the Go modernization lints the editor flagged. All behavior-preserving; happy to split into a separate PR if preferred:

  • interface{}any
  • wg.Add(1) + go func(){ defer Done() }wg.Go(...)
  • for i := 0; i < n; i++for i := range n
  • reverse index loop → slices.Backward

Refs #86

Summary by CodeRabbit

  • New Features
    • Added a CLI option --enable_periodic_idle_vnpu_cleanup to enable periodic cleanup of idle vNPU resources.
    • Cleanup remains disabled by default.
  • Bug Fixes
    • Improved server goroutine lifecycle and shutdown coordination for more reliable startup and termination.
  • Tests
    • Updated server tests to match the new cleanup configuration and constructor signature, including restart-related scenarios.

@hami-robot

hami-robot Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: dartagnanli
Once this PR has been reviewed and has the lgtm label, please assign archlitchi for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found 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

@hami-robot hami-robot Bot added the size/L label Jul 25, 2026
@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI adds a flag for periodic idle vNPU cleanup. PluginServer accepts and applies the flag, updates stop-channel typing, and uses WaitGroup.Go for goroutine startup. Registration and server tests are updated accordingly.

Changes

Server cleanup lifecycle

Layer / File(s) Summary
Cleanup configuration and server contract
cmd/main.go, internal/server/server.go
The CLI flag is passed into NewPluginServer; the server stores it, conditionally resets and exposes stopCh, and updates related types to any.
Runtime goroutine lifecycle
internal/server/server.go, internal/server/register.go
Periodic cleanup and gRPC serving use ps.wg.Go, while watchAndRegister no longer performs its own WaitGroup.Done; device construction uses for i := range vCount.
Server test alignment
internal/server/server_test.go
Tests adopt the constructor and channel changes, update logger variadics to any, modernize cleanup and loop syntax, and enable periodic cleanup in restart setup.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant PluginServer
  participant Cleanup
  participant GRPCServer
  CLI->>PluginServer: pass cleanup flag to NewPluginServer
  PluginServer->>PluginServer: Start with ps.wg.Go
  PluginServer->>Cleanup: start periodic cleanup when enabled
  PluginServer->>GRPCServer: start serving through ps.wg.Go
  GRPCServer-->>PluginServer: stop or restart serving
Loading

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: ashergaga, archlitchi

Poem

I’m a rabbit with cleanup to do,
Idle vNPUs get swept anew.
Goroutines hop in a managed line,
Stop channels now type just fine.
Tests thump paws and restart bright—
All servers burrow through the night.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 title clearly summarizes the main change: adding a way to disable periodic idle vNPU cleanup to prevent premature reclamation.
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.
✨ 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 requested a review from ashergaga July 25, 2026 04:24
@coderabbitai coderabbitai Bot added the enhancement New feature or request label Jul 25, 2026
@dartagnanli
dartagnanli force-pushed the fix/disable-periodic-idle-vnpu-cleanup branch from 34bc10b to 0243445 Compare July 25, 2026 04:36

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

@dartagnanli please fix the lint and dco error

…ature reclamation

The periodic idle vNPU cleanup goroutine (startPeriodicCheckIdleVNPUs) destroys vNPUs whose IsContainerUsed == 0. As discussed in Project-HAMi#86, a vNPU allocated to a Running Pod that has not yet started using the NPU also reports IsContainerUsed == 0, so the cleanup can reclaim it too early and break workloads (e.g. npu-smi info fails inside the container).

Add the --enable_periodic_idle_vnpu_cleanup flag (default false) so operators can disable the periodic cleanup goroutine while the stricter policy is being revisited. The one-shot cleanup on plugin restart (cmd/main.go) is intentionally left unconditional and unchanged.

Also apply Go modernizations in the touched files: interface{} -> any, wg.Add(1)+go -> wg.Go, range over int, slices.Backward.

Refs Project-HAMi#86

Signed-off-by: libin18 <libin18@kingsoft.com>
@dartagnanli
dartagnanli force-pushed the fix/disable-periodic-idle-vnpu-cleanup branch from 0243445 to 084b97b Compare July 28, 2026 06:34

@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

🤖 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 `@internal/server/server_test.go`:
- Line 538: Update TestNewPluginServer to include the periodic-cleanup flag in
each test case, pass that case value to NewPluginServer, and assert
ps.enablePeriodicIdleVNPUCleanup matches it. Add at least one test case with the
flag set to true while preserving coverage for false.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c5e18f1c-a9c7-4d4b-9218-0a9cdf33590b

📥 Commits

Reviewing files that changed from the base of the PR and between 34bc10b and 084b97b.

📒 Files selected for processing (4)
  • cmd/main.go
  • internal/server/register.go
  • internal/server/server.go
  • internal/server/server_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • cmd/main.go
  • internal/server/register.go
  • internal/server/server.go

t.Parallel()
mgr := &FakeManager{CommonWordFunc: func() string { return tc.args.commonWord }}
ps, err := NewPluginServer(mgr, tc.args.nodeName, 60)
ps, err := NewPluginServer(mgr, tc.args.nodeName, 60, false)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the new periodic-cleanup flag in TestNewPluginServer.

Passing false only updates the call-site signature; this test never verifies that NewPluginServer stores the argument. Add the flag to the test cases and assert ps.enablePeriodicIdleVNPUCleanup, including a true case.

🤖 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 `@internal/server/server_test.go` at line 538, Update TestNewPluginServer to
include the periodic-cleanup flag in each test case, pass that case value to
NewPluginServer, and assert ps.enablePeriodicIdleVNPUCleanup matches it. Add at
least one test case with the flag set to true while preserving coverage for
false.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants