Skip to content

fix(webhook) : Multi-Container & InitContainer Mutating Webhook Test - #2495

Closed
aniket866 wants to merge 9 commits into
Project-HAMi:masterfrom
aniket866:test/webHook-pod-patch
Closed

fix(webhook) : Multi-Container & InitContainer Mutating Webhook Test#2495
aniket866 wants to merge 9 commits into
Project-HAMi:masterfrom
aniket866:test/webHook-pod-patch

Conversation

@aniket866

@aniket866 aniket866 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Closes #2490

Specification Field Details & Implementation Context
Target File webhook.go
Target Functions MutateValidation / Webhook Pod Patching
Missing Scenario Webhook mutating requests for pods with multiple application containers, initContainers requesting vGPU resources, or sidecar containers.
Risk / Failure Mode Resource requests or environment variables (CUDA_VISIBLE_DEVICES, LD_PRELOAD) might only be injected into the first container, leaving secondary or initContainers unconfigured or causing duplicate JSON patches that fail pod creation.
Why It Is Critical Production workloads heavily rely on initContainers (e.g. model downloaders) and sidecars (e.g. logging/monitoring) that interact with GPU runtimes.
Proposed Test Add test cases in webhook_test.go passing multi-container Pod specs to verify precise JSON patch generation for each container index.

Architecture Flow: Before vs After Test Coverage

flowchart LR
    subgraph Before["Before: Untested & Vulnerable Flow"]
        direction TB
        B_Mutate["Mutating Webhook Request\n(Multi-Container / InitContainer)"]
        B_Parser["MutateValidation\n(webhook.go)"]
        B_FirstOnly["Injects container[0] Only"]
        B_DupPatch["Duplicate JSON Patch Conflict"]
        B_Fail["Pod Startup Failure / Unconfigured GPU"]

        B_Mutate --> B_Parser
        B_Parser -->|Single Index Assumption| B_FirstOnly
        B_Parser -->|Patch Collision| B_DupPatch
        B_FirstOnly --> B_Fail
        B_DupPatch --> B_Fail
    end

    Before ==>|webhook_test.go Patch Validation| After

    subgraph After["After: Validated & Hardened Flow"]
        direction TB
        A_Mutate["Mutating Webhook Request\n(Multi-Container / InitContainer)"]
        A_Test["webhook_test.go Suite"]
        A_Loop["Indexed Container & InitContainer Iteration"]
        A_Patch["Precise Per-Container JSON Patches"]
        A_Success["Multi-Container GPU Injection Validated"]

        A_Mutate --> A_Test
        A_Test --> A_Loop
        A_Loop --> A_Patch
        A_Patch --> A_Success
    end

    classDef danger fill:#fee2e2,stroke:#ef4444,stroke-width:2px,color:#991b1b;
    classDef success fill:#dcfce7,stroke:#22c55e,stroke-width:2px,color:#166534;
    classDef neutral fill:#f3f4f6,stroke:#4b5563,stroke-width:1.5px,color:#1f2937;

    class B_FirstOnly,B_DupPatch,B_Fail danger;
    class A_Patch,A_Success success;
    class B_Mutate,B_Parser,A_Mutate,A_Test,A_Loop neutral;
Loading

Summary by CodeRabbit

  • Bug Fixes

    • Fixed admission processing for pods with init containers and multiple application containers.
    • Improved GPU resource detection, mutation, validation, and quota calculations for init containers.
    • Init-container resource requests are now correctly considered during quota checks.
    • Device-specific mutation errors now return an appropriate server error response.
  • Tests

    • Added coverage for multi-container admission, GPU resources, init containers, and quota enforcement.

@hami-robot

hami-robot Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: aniket866
Once this PR has been reviewed and has the lgtm label, please assign fouof 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 Aug 8, 2026
@coderabbitai

coderabbitai Bot commented Aug 8, 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 webhook now processes init containers during device admission mutation and quota calculation. Tests cover GPU patches, quota precedence, quota rejection, and CPU-only pods. The change also adds an invalid duplicate GetLocalCache declaration.

Changes

Webhook init-container support

Layer / File(s) Summary
Init-container mutation and quota aggregation
pkg/scheduler/webhook.go, pkg/device/quota.go
The webhook mutates init containers, returns HTTP 500 for device mutation errors, aggregates detected resources, and applies maximum generated memory and core requests during quota validation. pkg/device/quota.go also contains a duplicate nested GetLocalCache declaration.
Admission and quota regression coverage
pkg/scheduler/webhook_test.go, CHANGELOG.md
Tests validate patches for init and regular containers, init-container quota precedence and rejection, and CPU-only admission. The changelog records the v2.9.0 fix.

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

Sequence Diagram(s)

sequenceDiagram
  participant AdmissionWebhook
  participant Device
  participant QuotaManager
  AdmissionWebhook->>Device: mutate init container
  Device-->>AdmissionWebhook: return patches and detected resources
  AdmissionWebhook->>QuotaManager: validate maximum init-container demands
  QuotaManager-->>AdmissionWebhook: return quota decision
Loading

Possibly related issues

  • Project-HAMi issue 2490 — Covers webhook mutation for multiple application containers and init containers.
  • Project-HAMi issue 2366 — Covers GPU and resource-quota enforcement for init containers.

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: chaunceyjiang, dsfans2014, lakshya77089

Poem

A rabbit checks init pods today,
GPU patches find their way.
Memory and cores meet the gate,
Tests record each quota state.
A duplicate function blocks the trail—
“Fix that hop,” says the rabbit pale.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main webhook changes for multi-container and init-container mutation testing.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 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 DSFans2014 August 8, 2026 20:04

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

1153-1179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Validate the patched pod contents.

The path checks pass for any patch below these container paths. They do not verify the required resource requests, CUDA_VISIBLE_DEVICES, or LD_PRELOAD. They also do not verify that sidecar-logging remains unmodified.

Apply resp.Patches to the input pod and assert the exact mutations for init-downloader and app-main. Assert that sidecar-logging has no GPU resources or injected device environment variables.

🤖 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/webhook_test.go` around lines 1153 - 1179, Extend the test
around the webhook response and resp.Patches to apply the patches to the input
pod, then assert the exact expected resource requests and CUDA_VISIBLE_DEVICES
and LD_PRELOAD environment mutations for init-downloader and app-main. Also
verify sidecar-logging remains unchanged, with no GPU resources or injected
device environment variables, while retaining the existing patch-path checks.
🤖 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/webhook.go`:
- Around line 154-161: Update fitResourceQuota to track init-container resource
requests separately from application-container totals, retaining the maximum
init-container request per resource instead of adding it to memoryReq and
coresReq. Before calling FitQuota, pass the larger effective request for each
resource: the init-container maximum or the application-container sum.

---

Nitpick comments:
In `@pkg/scheduler/webhook_test.go`:
- Around line 1153-1179: Extend the test around the webhook response and
resp.Patches to apply the patches to the input pod, then assert the exact
expected resource requests and CUDA_VISIBLE_DEVICES and LD_PRELOAD environment
mutations for init-downloader and app-main. Also verify sidecar-logging remains
unchanged, with no GPU resources or injected device environment variables, while
retaining the existing patch-path checks.
🪄 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: b6a7a00a-69fa-47fa-9cbd-2bdebbeb31e9

📥 Commits

Reviewing files that changed from the base of the PR and between 3616313 and 33ae307.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • pkg/scheduler/webhook.go
  • pkg/scheduler/webhook_test.go

Comment thread pkg/scheduler/webhook.go
@codecov

codecov Bot commented Aug 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.33333% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/device/quota.go 0.00% 3 Missing and 2 partials ⚠️
pkg/scheduler/webhook.go 86.95% 2 Missing and 1 partial ⚠️
Flag Coverage Δ
unittests 64.29% <73.33%> (+0.08%) ⬆️

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

Files with missing lines Coverage Δ
...ice-plugin/nvidiadevice/nvinternal/cdi/api_mock.go 0.00% <ø> (ø)
pkg/util/client/client.go 81.81% <100.00%> (+9.09%) ⬆️
pkg/scheduler/webhook.go 84.61% <86.95%> (+0.66%) ⬆️
pkg/device/quota.go 73.71% <0.00%> (-1.73%) ⬇️

... and 1 file with indirect coverage changes

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

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

🤖 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/webhook_test.go`:
- Around line 1183-1424: Update TestFitResourceQuotaInitContainers to initialize
the NVIDIA backend independently of TestFitResourceQuota, then register
t.Cleanup handlers restoring config.SchedulerName, device.DevicesMap, and
device.DevicesToHandle. Ensure each quota-denial subtest uses an isolated
namespace or restores its cache.Quotas entry so targeted and repeated test runs
do not leak device or quota state.
- Around line 1184-1292: Update the two fitResourceQuota test cases to configure
explicit resource-quota limits that distinguish the aggregation rule: the
init-larger-pod case should pass when limits match the maximum init-container
requirements plus regular-container totals, but fail under summed init
requirements; the container-larger-pod case should fail when limits are below
the regular-container sum despite exceeding the init maximum. Assert the
expected outcomes through the existing fitResourceQuota helper.
🪄 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: 68c46d14-1ce6-466b-a056-96b7524ebf6d

📥 Commits

Reviewing files that changed from the base of the PR and between c8abcc8 and 7bc81ed.

📒 Files selected for processing (1)
  • pkg/scheduler/webhook_test.go

Comment thread pkg/scheduler/webhook_test.go
Comment thread pkg/scheduler/webhook_test.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.

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/quota.go`:
- Around line 48-50: Update GetLocalCache’s lazy quota initialization to return
NewQuotaManager() directly when localCache.Quotas is nil, ensuring
initialization remains synchronized through the existing sync.Once in
NewQuotaManager and avoiding an unsynchronized read/write during first
initialization.
🪄 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: 2aae3331-6ac2-4981-8d4b-d13c688492af

📥 Commits

Reviewing files that changed from the base of the PR and between 7bc81ed and e44e3fc.

📒 Files selected for processing (1)
  • pkg/device/quota.go

Comment thread pkg/device/quota.go Outdated
aniket866 and others added 6 commits August 9, 2026 03:26
Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
…tainers

Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
…il map assignment panic

Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
…and prevent nil quota map access

Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
@aniket866

Copy link
Copy Markdown
Contributor Author

Codecov Report

❌ Patch coverage is 60.86957% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/scheduler/webhook.go 60.86% 5 Missing and 4 partials ⚠️
Flag Coverage Δ
unittests 64.24% <60.86%> (+0.02%) ⬆️
Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
pkg/scheduler/webhook.go 78.84% <60.86%> (-5.11%) ⬇️
... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:

fixed

Signed-off-by: aniket866 <iamaniketkumarmaner@gmail.com>
@aniket866 aniket866 changed the title Multi-Container & InitContainer Mutating Webhook Test fix(webhook) : Multi-Container & InitContainer Mutating Webhook Test Aug 9, 2026
@github-actions github-actions Bot added the kind/bug Something isn't working label Aug 9, 2026
@mesutoezdil

Copy link
Copy Markdown
Contributor

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.

Multi-Container & InitContainer Mutating Webhook Test

2 participants