Skip to content

fix(scheduler): bound-check MIG template/instance index parsed from UUID annotation#2088

Open
mesutoezdil wants to merge 1 commit into
Project-HAMi:masterfrom
mesutoezdil:fix/scheduler-mig-index-bounds
Open

fix(scheduler): bound-check MIG template/instance index parsed from UUID annotation#2088
mesutoezdil wants to merge 1 commit into
Project-HAMi:masterfrom
mesutoezdil:fix/scheduler-mig-index-bounds

Conversation

@mesutoezdil

@mesutoezdil mesutoezdil commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

/kind bug

getNodesUsage reads a MIG template index and instance number from a pod's UUID annotation and used both without checking them.
A stale or mismatched index can panic the scheduler's usage-scrape goroutine instead of just being skipped.

This PR adds bounds and consistency checks: an out-of-range index is rejected, and an index that disagrees with the device's already-recorded MIG template is rejected too.

Two new tests: one for an out-of-range index, one for two pods that disagree on the template index.
Confirmed both panic on the old code and pass after the fix. go test with race, go vet, and golangci-lint all pass.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of invalid, stale, or mismatched MIG UUID and index data to prevent unsafe access.
    • The scheduler now safely validates MIG template and instance indexes; on inconsistencies it logs the issue and skips marking MIG usage to avoid incorrect scheduling.
  • Tests
    • Added unit tests covering stale template indices, unparsable MIG UUIDs, out-of-range MIG instances, and mismatched MIG index scenarios.

@hami-robot

hami-robot Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: mesutoezdil
Once this PR has been reviewed and has the lgtm label, please assign shouren 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

@github-actions github-actions Bot added the kind/bug Something isn't working label Jul 18, 2026
@hami-robot hami-robot Bot added the size/M label Jul 18, 2026
@coderabbitai

coderabbitai Bot commented Jul 18, 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 scheduler now validates MIG UUID parsing and template or instance indices before updating MIG usage. Tests cover stale, unparsable, out-of-range, and mismatched indices, confirming usage accounting continues without unsafe writes or panics.

Changes

MIG usage safety

Layer / File(s) Summary
Validate MIG indices
pkg/scheduler/scheduler.go, pkg/scheduler/scheduler_test.go
MIG extraction errors, template mismatches, and template or instance bounds are checked before usage updates. Tests verify invalid MIG references are skipped safely while device usage remains accounted.

Estimated code review effort: 2 (Simple) | ~15 minutes

Suggested labels: enhancement

Suggested reviewers: chaunceyjiang, ouyangluwei163

Poem

I’m a rabbit guarding GPU lanes,
Stale MIG numbers bring no pains.
Bounds are checked, the logs speak clear,
No unsafe hops or panics here.
I twitch my nose and code hops on!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main scheduler fix: bound-checking MIG template and instance indexes parsed from UUID annotations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces validation and bounds checking for MIG template and instance indices extracted from UUIDs in pkg/scheduler/scheduler.go to prevent out-of-bounds panics, along with a corresponding unit test. The review feedback suggests two improvements: validating that the extracted template index matches the already initialized MIG usage index when the usage list is already populated, and separating the parsing error check from the bounds check to ensure clearer log messages.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread pkg/scheduler/scheduler.go
Comment thread pkg/scheduler/scheduler.go Outdated

@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 (2)
pkg/scheduler/scheduler_test.go (1)

188-190: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use assert.True and correct the assert.Equal argument order.

The testify/assert package expects the signature assert.Equal(t, expected, actual). Additionally, assert.True(t, ok) is more idiomatic than assert.Equal(t, ok, true).

(Note: The rest of the file also uses this pattern, so this is just a minor stylistic suggestion for the newly added test).

♻️ Proposed refactor
-	assert.Equal(t, ok, true)
-	assert.Equal(t, v.Devices.DeviceLists[0].Device.Used, int32(1))
-	assert.Equal(t, len(v.Devices.DeviceLists[0].Device.MigUsage.UsageList), 0)
+	assert.True(t, ok)
+	assert.Equal(t, int32(1), v.Devices.DeviceLists[0].Device.Used)
+	assert.Equal(t, 0, len(v.Devices.DeviceLists[0].Device.MigUsage.UsageList))
🤖 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/scheduler/scheduler_test.go` around lines 188 - 190, Update the newly
added assertions in the test to use assert.True(t, ok) for the boolean result
and pass expected values before actual values in the assert.Equal calls,
including the Device.Used and MigUsage.UsageList checks.
pkg/scheduler/scheduler.go (1)

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

Improve variable naming and error logging clarity.

The current fix effectively prevents panics, but there are two minor maintainability improvements to consider:

  1. Variable naming: Local variables in Go should use camelCase. Instance is capitalized, which is typically reserved for exported package-level symbols.
  2. Log clarity: When tmpIdx is out of bounds but parses successfully, err is nil. This causes the current code to log <nil> at the end of the error message. Separating the parse error check from the bounds check prevents this.

Consider this combined refactor to address both:

♻️ Proposed refactor
-								tmpIdx, Instance, err := device.ExtractMigTemplatesFromUUID(udevice.UUID)
-								if err != nil || tmpIdx < 0 || tmpIdx >= len(d.Device.MigTemplate) {
-									klog.Errorf("invalid mig template index in uuid %s: %v", udevice.UUID, err)
-									continue
-								}
+								tmpIdx, instanceIdx, err := device.ExtractMigTemplatesFromUUID(udevice.UUID)
+								if err != nil {
+									klog.Errorf("failed to parse mig template from uuid %s: %v", udevice.UUID, err)
+									continue
+								}
+								if tmpIdx < 0 || tmpIdx >= len(d.Device.MigTemplate) {
+									klog.Errorf("invalid mig template index %d in uuid %s", tmpIdx, udevice.UUID)
+									continue
+								}
 								if len(d.Device.MigUsage.UsageList) == 0 {
 									device.PlatternMIG(&d.Device.MigUsage, d.Device.MigTemplate, tmpIdx)
 								}
-								if Instance < 0 || Instance >= len(d.Device.MigUsage.UsageList) {
+								if instanceIdx < 0 || instanceIdx >= len(d.Device.MigUsage.UsageList) {
 									klog.Errorf("invalid mig instance in uuid %s", udevice.UUID)
 									continue
 								}
-								d.Device.MigUsage.UsageList[Instance].InUse = true
+								d.Device.MigUsage.UsageList[instanceIdx].InUse = true
🤖 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/scheduler/scheduler.go` around lines 649 - 661, Update the MIG UUID
handling around ExtractMigTemplatesFromUUID: rename the local Instance variable
to camelCase, handle and log extraction errors separately, then validate tmpIdx
bounds with a clear index-specific message that does not include a nil error.
Preserve the existing continue behavior for invalid UUIDs or template indices.
🤖 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/scheduler/scheduler_test.go`:
- Around line 188-190: Update the newly added assertions in the test to use
assert.True(t, ok) for the boolean result and pass expected values before actual
values in the assert.Equal calls, including the Device.Used and
MigUsage.UsageList checks.

In `@pkg/scheduler/scheduler.go`:
- Around line 649-661: Update the MIG UUID handling around
ExtractMigTemplatesFromUUID: rename the local Instance variable to camelCase,
handle and log extraction errors separately, then validate tmpIdx bounds with a
clear index-specific message that does not include a nil error. Preserve the
existing continue behavior for invalid UUIDs or template indices.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1a94f4b4-2352-40a0-a53e-f8c4d92f9b93

📥 Commits

Reviewing files that changed from the base of the PR and between 125c8c6 and a376da7.

📒 Files selected for processing (2)
  • pkg/scheduler/scheduler.go
  • pkg/scheduler/scheduler_test.go

@codecov

codecov Bot commented Jul 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Flag Coverage Δ
unittests 60.59% <100.00%> (+0.14%) ⬆️

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

Files with missing lines Coverage Δ
pkg/scheduler/scheduler.go 68.81% <100.00%> (+2.04%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@hami-robot hami-robot Bot added size/L and removed size/M labels Jul 18, 2026

@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/scheduler/scheduler_test.go (1)

226-234: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use nvidia.NvidiaGPUDevice constant.

Consider using the existing nvidia.NvidiaGPUDevice constant instead of the hardcoded "NVIDIA" string to maintain consistency with the device initialization above.

🛠️ Proposed refactor
 	podMap.AddPod(&corev1.Pod{
 		ObjectMeta: metav1.ObjectMeta{UID: "1111", Name: "test1", Namespace: "default"},
 	}, "node1", device.PodDevices{
-		"NVIDIA": device.PodSingleDevice{
+		nvidia.NvidiaGPUDevice: device.PodSingleDevice{
 			[]device.ContainerDevice{{Idx: 0, UUID: "GPU0[0-0]", Usedmem: 100, Usedcores: 10}},
 		},
 	})
 	podMap.AddPod(&corev1.Pod{
 		ObjectMeta: metav1.ObjectMeta{UID: "2222", Name: "test2", Namespace: "default"},
 	}, "node1", device.PodDevices{
-		"NVIDIA": device.PodSingleDevice{
+		nvidia.NvidiaGPUDevice: device.PodSingleDevice{
 			[]device.ContainerDevice{{Idx: 0, UUID: "GPU0[1-0]", Usedmem: 100, Usedcores: 10}},
 		},
 	})
🤖 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/scheduler/scheduler_test.go` around lines 226 - 234, Replace the
hardcoded "NVIDIA" key in the pod device map with the existing
nvidia.NvidiaGPUDevice constant, matching the device initialization above while
leaving the surrounding test data unchanged.
🤖 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/scheduler/scheduler_test.go`:
- Around line 226-234: Replace the hardcoded "NVIDIA" key in the pod device map
with the existing nvidia.NvidiaGPUDevice constant, matching the device
initialization above while leaving the surrounding test data unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0c40e742-8c81-4a06-b3de-e5f1af6e40e0

📥 Commits

Reviewing files that changed from the base of the PR and between a376da7 and 2e846bc.

📒 Files selected for processing (2)
  • pkg/scheduler/scheduler.go
  • pkg/scheduler/scheduler_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/scheduler/scheduler.go

@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/scheduler/scheduler_test.go (1)

349-353: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use appropriate boolean assertions and correct parameter order.

For cleaner test output and to prevent swapping "expected" and "actual" values in failure messages, update the testify/assert usages:

  • Use assert.True for boolean checks instead of assert.Equal(..., true).
  • Follow the standard assert.Equal(t, expected, actual) argument order convention.
♻️ Proposed refactor
-	assert.Equal(t, ok, true)
+	assert.True(t, ok)
 	dev := v.Devices.DeviceLists[0].Device
-	assert.Equal(t, dev.Used, int32(2))
-	assert.Equal(t, len(dev.MigUsage.UsageList), 1)
-	assert.Equal(t, dev.MigUsage.UsageList[0].InUse, true)
+	assert.Equal(t, int32(2), dev.Used)
+	assert.Equal(t, 1, len(dev.MigUsage.UsageList))
+	assert.True(t, dev.MigUsage.UsageList[0].InUse)
🤖 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/scheduler/scheduler_test.go` around lines 349 - 353, Update the
assertions in the affected scheduler test to use assert.True for boolean values,
including ok and InUse, and correct all assert.Equal calls to pass expected
values before actual values. Preserve the existing numeric and length
expectations while applying the standard testify argument order.
🤖 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/scheduler/scheduler_test.go`:
- Around line 349-353: Update the assertions in the affected scheduler test to
use assert.True for boolean values, including ok and InUse, and correct all
assert.Equal calls to pass expected values before actual values. Preserve the
existing numeric and length expectations while applying the standard testify
argument order.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c7c31673-0c3a-45b8-a62e-c77a7670353a

📥 Commits

Reviewing files that changed from the base of the PR and between b92e3b2 and c9f1852.

📒 Files selected for processing (2)
  • pkg/scheduler/scheduler.go
  • pkg/scheduler/scheduler_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/scheduler/scheduler.go

…UID annotation

getNodesUsage parses a MIG template index and instance number from a
pod's UUID annotation and used both without validation. A stale or
mismatched index (node MIG config changed, or two pods disagreeing on
the active template) panicked the scheduler's usage-scrape goroutine
instead of being skipped.

Reject an out-of-range index, an index that disagrees with the
device's already-recorded MIG template, and an out-of-range instance.

Signed-off-by: mesutoezdil <mesudozdil@gmail.com>
@mesutoezdil
mesutoezdil force-pushed the fix/scheduler-mig-index-bounds branch from c9f1852 to c794a37 Compare July 18, 2026 09:27

@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: 4

🤖 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/scheduler/scheduler_test.go`:
- Around line 349-353: In the test assertions around dev.MigUsage.UsageList,
replace both assert.Assert calls with the appropriate testify boolean assertion,
using assert.True for the expected true conditions while preserving the existing
checks and messages.
- Around line 289-292: Replace the invalid assert.Assert calls in the scheduler
test with the appropriate testify boolean assertions: use True for ok and False
for the UsageList entry’s InUse value, preserving the existing test
expectations.
- Line 238: Replace the undefined assert.Assert call in the scheduler test with
testify's assert.True, preserving the existing t and ok arguments and assertion
behavior.
- Line 188: In the test assertion around the ok result, replace the undefined
assert.Assert call with testify/assert’s assert.True, preserving t and ok as the
assertion arguments.
🪄 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: d4a1e4b0-790e-4310-9484-3b0f311670f6

📥 Commits

Reviewing files that changed from the base of the PR and between c9f1852 and c794a37.

📒 Files selected for processing (2)
  • pkg/scheduler/scheduler.go
  • pkg/scheduler/scheduler_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/scheduler/scheduler.go

Comment thread pkg/scheduler/scheduler_test.go
Comment thread pkg/scheduler/scheduler_test.go
Comment thread pkg/scheduler/scheduler_test.go
Comment thread pkg/scheduler/scheduler_test.go

@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

@ouyangluwei163 ouyangluwei163 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

3 participants