Skip to content

perf: remove unused all-device scan in metrics collector - #2166

Closed
Gaurav-205 wants to merge 1 commit into
Project-HAMi:masterfrom
Gaurav-205:fix/metrics-unused-device-scan
Closed

perf: remove unused all-device scan in metrics collector#2166
Gaurav-205 wants to merge 1 commit into
Project-HAMi:masterfrom
Gaurav-205:fix/metrics-unused-device-scan

Conversation

@Gaurav-205

@Gaurav-205 Gaurav-205 commented Jul 28, 2026

Copy link
Copy Markdown

Summary

Fixes #2165.

During Prometheus metrics collection in cmd/scheduler/metrics.go, an nested loop was iterating over all cluster nodes and node devices to calculate totaldev for every scheduled container device. This computed totaldev value was only logged at klog.V(4) and never used in any emitted metric or calculation.

This PR removes the redundant $O(A \times D)$ device scan loop and unused strings package import, eliminating unnecessary CPU and memory allocation overhead during Prometheus scrapes.

Changes

  • Removed unneeded nested node/device search loop in cmd/scheduler/metrics.go.
  • Removed unused strings import.

Summary by CodeRabbit

Summary

  • Refactor

    • Streamlined scheduler metrics collection by removing legacy device memory lookup and its associated logging.
    • Improved scheduled pod snapshot isolation: returned pod/device data is now deep-copied so callers can’t mutate cached state, with custom metadata intentionally omitted from the returned copies.
  • Tests

    • Updated pod and deep-copy tests to match the new snapshot and metadata omission behavior.
  • Chores

    • Removed unused imports and simplified internal collection/copying logic.

Signed-off-by: Gaurav-205 <gauravkhandelwal205@gmail.com>
@hami-robot

hami-robot Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Gaurav-205
Once this PR has been reviewed and has the lgtm label, please assign dsfans2014 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/S label Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Scheduled pod snapshots now deep-copy device data while omitting CustomInfo, with tests updated for the new semantics. Scheduler metrics collection also removes an unused all-device memory lookup and its strings import.

Changes

Scheduled pod snapshot isolation

Layer / File(s) Summary
Deep-copy scheduled pod devices
pkg/device/pods.go, pkg/device/pod_test.go
GetScheduledPods creates independent pod entries and deep-copies devices, while ContainerDevice.DeepCopy omits CustomInfo; tests verify copied scalar fields and internal-state isolation.

Scheduler metrics cleanup

Layer / File(s) Summary
Remove redundant device lookup
cmd/scheduler/metrics.go
Deletes the unused device total-memory scan and logging, along with the strings import used for UUID comparison.

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

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: lengrongfu

Poem

I’m a small rabbit, hopping light,
No needless device scans in sight.
Snapshots copy, maps take flight,
Custom details stay out of sight.
Squeak hooray for cleaner code!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PodManager deep-copy and test changes in pkg/device are unrelated to removing the scheduler metrics scan. Limit the PR to the metrics collector change, or split the PodManager deep-copy refactor into a separate PR.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR removes the redundant O(A×D) lookup in metrics collection as requested in #2165.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main performance fix: removing the unused all-device scan from metrics collection.
✨ 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.

@Gaurav-205

Copy link
Copy Markdown
Author

@wawa0210 @lengrongfu hey, can you please review this pr!!

Comment thread cmd/scheduler/metrics.go
}
klog.V(4).InfoS("Total memory for device",
"deviceUUID", ctrdevval.UUID,
"totalMemory", totaldev,

@Eshiv-Pandey Eshiv-Pandey Jul 28, 2026

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.

Great find! This looks reasonable tbh. The removed scan only feeds a verbose log line and does not affect any emitted metric. One question tho... was this totalMemory log used for any debugging flow, or is the node memory limit metric enough for that case?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks! I checked the full metrics collector flow. totaldev was only used by that klog.V(4) message; it does not affect emitted metrics, scheduling, or allocation.
For debugging device capacity, the collector already exposes the same per-device total-memory information through hami_gpu_memory_limit_bytes and hami_node_gpu_overview (device_memory_limit). So the verbose log is redundant, and removing the scan does not reduce Prometheus visibility.
If maintainers prefer retaining a V(4) log for troubleshooting, I can add one using the already available per-device data, without restoring the all-node scan.

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

also the description doesnt follow the pr template, no "what type of pr is this?" block or /kind line, and no ai disclosure. if any ai tool was used it has to be disclosed, see https://github.com/Project-HAMi/HAMi/blob/master/CONTRIBUTING.md#ai-assistance-notice

fyi #2170 is open on this same file, worth watching the order.

Comment thread cmd/scheduler/metrics.go
)
}
}
}

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.

the loop u deleted broke on the first uuid hit while ranging *nu, which is a map, and the pods node was already sitting in val.NodeID, so what did that V(4) line print if the same uuid ever turned up under 2 nodes?

@hami-robot hami-robot Bot added size/L and removed size/S labels Jul 29, 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/device/pod_test.go (1)

157-161: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Stop after a failed scheduled-pod lookup.

assert.True is non-fatal; a failed lookup makes got nil and line 161 panics. Return after the assertion so regressions report the actual failed condition.

Proposed fix
 got, ok := scheduledPods[pod1.UID]
-assert.True(t, ok)
+if !assert.True(t, ok) {
+	return
+}
 
 // 1. Existing Pod pointer is kept
🤖 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/device/pod_test.go` around lines 157 - 161, Make the scheduled-pod lookup
assertion in the relevant test fail fast: after checking the ok result for
scheduledPods[pod1.UID], return immediately when the lookup fails before
dereferencing got in the assert.Same call. Preserve the existing
pointer-preservation assertion for successful lookups.
🤖 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/device/pod_test.go`:
- Around line 157-161: Make the scheduled-pod lookup assertion in the relevant
test fail fast: after checking the ok result for scheduledPods[pod1.UID], return
immediately when the lookup fails before dereferencing got in the assert.Same
call. Preserve the existing pointer-preservation assertion for successful
lookups.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ef3b76eb-acae-4e01-afec-ac892d3ecb7c

📥 Commits

Reviewing files that changed from the base of the PR and between c884077 and 34203b1.

📒 Files selected for processing (2)
  • pkg/device/pod_test.go
  • pkg/device/pods.go

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.

perf: Remove unused all-device lookup loop in scheduler metrics collector

3 participants