Skip to content

Fix/metax int32 overflow - #2446

Closed
im-Toqeer-506 wants to merge 2 commits into
Project-HAMi:masterfrom
im-Toqeer-506:fix/metax-int32-overflow
Closed

Fix/metax int32 overflow#2446
im-Toqeer-506 wants to merge 2 commits into
Project-HAMi:masterfrom
im-Toqeer-506:fix/metax-int32-overflow

Conversation

@im-Toqeer-506

@im-Toqeer-506 im-Toqeer-506 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind feature
/kind failing-test

What this PR does / why we need it:

All 14 HAMi device backends implement the same device.Devices interface
(pkg/device/devices.go), but each is tested in isolation — so the same class of
contract violation keeps being rediscovered and fixed one backend at a time
(int32 overflow in GenerateResourceRequests: #2278/#2284/#2336; nil-map / nil-pointer
panics on the admission and Fit paths: #2254/#2294).

This PR lands phase 1 of a shared, table-driven conformance suite that runs one
set of contract assertions against every constructible backend, so a regression in
any of them fails CI immediately instead of shipping.

Included:

  • A test-only backend registry (conformanceCases()) that constructs 14 backend
    variants from plain in-memory configs mirroring the production resource names wired
    in pkg/scheduler/config.InitDevicesWithConfig.
  • Shared invariants:
    • GetResourceNames() returns at least one non-empty name (else the backend is
      unreachable by the scheduler).
    • A container requesting none of a backend's resources yields Nums == 0.
    • Fit(nil, …) and Fit([]*DeviceUsage{}, …) return false without panicking.
    • MutateAdmission does not panic on a pod that requests none of the resources.
    • No negative Nums/Memreq/Coresreq from GenerateResourceRequests — the
      int32-overflow guard.
  • The overflow invariant surfaced a previously-untracked overflow in metax-sgpu,
    which this PR fixes inline (reject out-of-range memory before the unchecked
    int32(mem) cast) — exactly the value the suite is meant to deliver.
  • Backends with dedicated open issues (cambricon [bug]: cambricon int32 overflow in GenerateResourceRequests silently drops memory request #2278, mthreads bug: int32 overflow in GenerateResourceRequests silently drops memory request (iluvatar, mthreads) #2284) go on an
    explicit, commented skip list linked to their tracking issues, so the gap is visible,
    not silent.

Kept additive and phased per the issue: ascend and iluvatar (slice / enable-flag
constructors) and further invariants (scoring monotonicity, PatchAnnotations
round-trip, lock idempotency) are documented as follow-up.

Which issue(s) this PR fixes:
Fixes # #2379

Special notes for your reviewer:

  • The overflow invariant has teeth: with the skip list disabled, cambricon and
    mthreads fail and metax-sgpu passes (confirming the metax fix is exercised).
  • Overflow "case 2" is gated on MemoryFactor > 0, so it targets the
    scaling-multiplication overflow that the bug reports describe; backends that don't
    scale still get the in-range non-negativity check (case 1).
  • The suite lives in the external device_test package on purpose — the backend
    sub-packages import pkg/device, so an internal test importing them back would
    create an import cycle.
  • Validation: go test -race ./pkg/device/... and ./pkg/scheduler/... all pass;
    gofmt, goimports (local-prefix), and go vet are clean.

Does this PR introduce a user-facing change?:

NONE


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

* **Bug Fixes**
  * Prevented invalid memory requests from being converted into incorrect device resource values.
  * Added graceful handling for empty, nil, unrelated, and unsupported device configurations.
  * Ensured resource requests do not become negative or overflow under unusual input values.

* **Tests**
  * Added comprehensive validation across supported device backends, including registration, resource naming, and admission handling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

im-Toqeer-506 and others added 2 commits August 5, 2026 19:37
Every hardware backend implements the same device.Devices interface
(pkg/device/devices.go), but each is otherwise tested in isolation, so the
same class of contract violation has repeatedly been fixed one backend at a
time (e.g. nil-map / nil-pointer panics on the admission and Fit paths in
Project-HAMi#2254 and Project-HAMi#2294).

Add pkg/device/conformance_test.go: a backend-agnostic suite that runs one
shared set of contract assertions against every constructible backend, so a
regression in any of them fails here immediately instead of shipping and
being rediscovered vendor-by-vendor.

Invariants asserted for all 14 constructible backends:
- registry guard: every case has a name and a non-nil backend
- GetResourceNames() advertises at least one non-empty resource name
  (a backend with none is unreachable by the scheduler)
- a container requesting none of a backend's resources yields Nums == 0
- Fit against nil and empty candidate lists returns false without panicking
- MutateAdmission on a pod with no accelerator request does not panic

The suite lives in the external device_test package on purpose: the backend
sub-packages import pkg/device, so an internal test importing them back
would create an import cycle.

The ascend and iluvatar backends (slice-returning constructors gated behind
enable flags) and the int32-overflow invariant for GenerateResourceRequests
are intentionally deferred to a follow-up, so this first pass stays green
while the underlying fixes land (Project-HAMi#2278, Project-HAMi#2284).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: M Toqeer Zia <muhammadtoqeerzia586694@gmail.com>
Signed-off-by: M Toqeer Zia <muhammadtoqeerzia586694@gmail.com>
@hami-robot

hami-robot Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: im-Toqeer-506
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

@github-actions github-actions Bot added kind/bug Something isn't working and removed kind/feature new function labels Aug 7, 2026
@hami-robot hami-robot Bot added the size/L label Aug 7, 2026
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds shared conformance tests for constructible device backends and validates registration, resource handling, fitting, admission mutation, and overflow behavior. Metax now rejects memory requests outside the valid int32 range before conversion.

Changes

Device conformance and resource validation

Layer / File(s) Summary
Cross-backend conformance suite
pkg/device/conformance_test.go
Adds shared tests for backend registration, resource names, unrelated containers, nil or empty device lists, admission mutation, and non-negative resource requests.
Metax memory-range validation
pkg/device/metax/sdevice.go
Rejects negative or over-math.MaxInt32 memory requests before converting them to int32.

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

Possibly related issues

Possibly related PRs

Suggested reviewers: archlitchi

Poem

A rabbit checks each device lane,
For empty lists and bounds of range.
Metax guards the numbers bright,
Rejecting values out of sight.
Conformance hops from backend to backend.

🚥 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 clearly identifies the Metax int32 overflow fix, which is a significant change in the pull request.
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.

@coderabbitai
coderabbitai Bot requested a review from archlitchi August 7, 2026 08:19

@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 `@pkg/device/metax/sdevice.go`:
- Around line 259-265: The no-unit memory value is scaled before validation,
allowing int64 overflow to produce a small valid value. In
pkg/device/metax/sdevice.go lines 259-265, update the validation before
MemoryFactor multiplication to reject negatives and values above
math.MaxInt32/MemoryFactor, while retaining the post-conversion range check for
unit-based input. In pkg/device/conformance_test.go lines 322-348, add a no-unit
value such as (1<<54)+1 and assert GenerateResourceRequests rejects it or
returns only non-negative fields.
🪄 Autofix

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: 4ed7372c-6f76-480e-8216-647d6c008059

📥 Commits

Reviewing files that changed from the base of the PR and between c5e99b6 and 7f88e4d.

📒 Files selected for processing (2)
  • pkg/device/conformance_test.go
  • pkg/device/metax/sdevice.go

Comment on lines +259 to +265
// Reject out-of-range memory requests that would overflow int32.
// MemoryFactor is 1024, so a Gi request without a unit multiplies by that;
// a request above math.MaxInt32 wraps negative on the unchecked cast below.
if mem < 0 || mem > math.MaxInt32 {
klog.Errorf("container<%s> metax-sgpu memory request %d MiB is out of range", ctr.Name, mem)
return device.ContainerDeviceRequest{}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate no-unit memory before scaling.

The check runs after v * MemoryFactor. For v = (1<<54)+1 and MemoryFactor = 1024, the int64 multiplication wraps to 1024. The request then passes this check and returns a small Memreq for a very large request.

  • pkg/device/metax/sdevice.go#L259-L265: Reject negative values and values greater than math.MaxInt32 / MemoryFactor before multiplication. Keep the post-conversion range check for unit-based input.
  • pkg/device/conformance_test.go#L322-L348: Add a no-unit value such as (1<<54)+1 and assert that GenerateResourceRequests rejects it or returns only non-negative fields.
📍 Affects 2 files
  • pkg/device/metax/sdevice.go#L259-L265 (this comment)
  • pkg/device/conformance_test.go#L322-L348
🤖 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/metax/sdevice.go` around lines 259 - 265, The no-unit memory value
is scaled before validation, allowing int64 overflow to produce a small valid
value. In pkg/device/metax/sdevice.go lines 259-265, update the validation
before MemoryFactor multiplication to reject negatives and values above
math.MaxInt32/MemoryFactor, while retaining the post-conversion range check for
unit-based input. In pkg/device/conformance_test.go lines 322-348, add a no-unit
value such as (1<<54)+1 and assert GenerateResourceRequests rejects it or
returns only non-negative fields.

@FouoF

FouoF commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

AI generated

@FouoF FouoF closed this Aug 7, 2026
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