← Back to Pull requests

Fail RunPodSandbox before NRI timeout expires and optimize multi-NIC attachment #370

Closed
aojea closed this pull request without merging on Oct 27, 2026 20:22 UTC
View on GitHub
aojea aojea commented on Oct 03, 2026 17:16 UTC
Author

What type of PR is this?

/kind bug

What this PR does / why we need it:

NRI plugins run under a strict per-request timeout enforced by the container runtime (plugin_request_timeout, 2 seconds by default in containerd). When RunPodSandbox exceeds this deadline while attaching multiple network interfaces (such as 8 RDMA NICs on a4-highgpu-8g / a3-megagpu-8g nodes), the NRI adaptation library returns context deadline exceeded (errPluginTimedOut), disconnects the NRI plugin, and allows the Pod sandbox to start with only a subset of its requested network devices attached.

sequenceDiagram
    autonumber
    participant K as Kubelet
    participant C as Containerd (CRI)
    participant A as NRI Adaptation (pkg/adaptation)
    participant S as Plugin Stub (pkg/stub)
    participant P as Plugin Handler

    rect rgb(235, 245, 255)
    Note over A,P: Stage 1: Plugin Startup, Registration & Synchronization
    S->>A: Connect to /var/run/nri/nri.sock
    par Registration Timeout (default 5s on both sides)
        Note over S: stub.register(ctx)<br/>context.WithTimeout(ctx, stub.registrationTimeout [5s])
        S->>A: RegisterPlugin(req) [TimeoutNano = 5s]
    and
        Note over A: p.start() waits on:<br/>select {<br/>  case <-p.regC:<br/>  case <-time.After(pluginRegistrationTimeout [5s]): p.close()<br/>}
    end

    Note over A: p.configure(ctx)<br/>context.WithTimeout(ctx, pluginRequestTimeout [2s])
    A->>S: Configure(req{RegistrationTimeout: 5000ms, RequestTimeout: 2000ms}) [TimeoutNano = 2s]
    Note over S: Saves stub.registrationTimeout = 5s, stub.requestTimeout = 2s<br/>ttRPC Server passes 2s ctx to plugin.Configure()
    S->>P: Configure(ctx [2s], cfg, runtime, version)
    P-->>S: EventMask
    S-->>A: ConfigureResponse{Events}

    Note over A: p.synchronize(ctx)<br/>Single context.WithTimeout(ctx, pluginRequestTimeout [2s])<br/>shared across all split Synchronize chunks
    A->>S: Synchronize(req) [TimeoutNano <= 2s]
    S->>P: Synchronize(ctx [<= 2s], pods, containers)
    P-->>S: updates
    S-->>A: SynchronizeResponse{Update}
    end

    rect rgb(235, 255, 235)
    Note over K,P: Stage 2A: Event Handling — Normal or Explicit Error (< 2s)
    K->>C: CRI RunPodSandbox / CreateContainer (ctx [deadline = 2m])
    C->>A: Adaptation.RunPodSandbox(ctx [deadline = 2m])
    Note over A: Holds Adaptation.Lock()<br/>Wraps ctx: WithTimeout(ctx, pluginRequestTimeout [2s])
    A->>S: RunPodSandbox(req) [TimeoutNano = 2s]
    S->>P: RunPodSandbox(ctx [deadline = 2s], pod)
    alt Plugin returns nil (< 2s)
        P-->>S: nil
        S-->>A: RunPodSandboxResponse{}
        A-->>C: nil (Proceeds to next plugin / starts Pod)
    else Plugin returns explicit error (< 2s)
        P-->>S: error("failed to attach device")
        S-->>A: gRPC status error
        Note over A: isFatalError(err) == false<br/>Plugin stays connected!
        A-->>C: error (FAIL-CLOSED: Pod creation aborted)
    end
    end

    rect rgb(255, 235, 235)
    Note over K,P: Stage 2B: Event Handling — Timeout (>= 2s)
    K->>C: CRI RunPodSandbox / CreateContainer (ctx [deadline = 2m])
    C->>A: Adaptation.RunPodSandbox(ctx [deadline = 2m])
    Note over A: Holds Adaptation.Lock()<br/>Wraps ctx: WithTimeout(ctx, pluginRequestTimeout [2s])
    A->>S: RunPodSandbox(req) [TimeoutNano = 2s]
    S->>P: RunPodSandbox(ctx [deadline = 2s], pod)
    Note over P: Handler takes > 2s (e.g. moving multiple NICs)...

    par At t = 2s on Containerd (ttRPC Client)
        Note over A: <-ctx.Done() fires in ttrpc.Client.dispatch()<br/>Returns context.DeadlineExceeded
        Note over A: isFatalError(context.DeadlineExceeded) == true!<br/>1. Calls p.close() (closes multiplexed socket)<br/>2. Swallows error: returns (nil, nil)<br/>3. defer r.removeClosedPlugins() drops plugin from r.plugins
        A-->>C: nil (FAIL-OPEN: Pod starts WITHOUT devices!)
        C-->>K: RunPodSandbox succeeds (broken pod state)
    and At t = 2s on Plugin (ttRPC Server)
        Note over P: Handler <-ctx.Done() fires (from TimeoutNano = 2s)
        A-xS: Socket closed by p.close() (EOF)
        Note over S: stub.connClosed() -> stub.close() -> stub.onClose()<br/>Plugin is DISCONNECTED (must exit/restart & re-register)
    end
    end

This PR addresses the problem in two ways:
1. Fail closed before the NRI request deadline expires: RunPodSandbox inspects the incoming NRI context deadline (ctx.Deadline()), reserves a reply margin (200ms by default), and aborts/returns an error before the container runtime's NRI deadline expires if device attachment is about to run out of time (elapsed/completed > remaining). This guarantees containerd receives the error response and tears down the sandbox instead of disconnecting the plugin and starting a broken Pod with missing NICs.
2. Optimize 8-NIC RunPodSandbox latency to fit comfortably within the 2-second NRI budget:
- Brings passthrough host network interfaces DOWN during NodePrepareResources (which runs under kubelet's 30s gRPC timeout) after host addresses/routes/neighbors have been read, rather than during RunPodSandbox (which runs under NRI's 2s timeout). If a prepared claim is unprepared before RunPodSandbox ever moves the interface, UnprepareResourceClaims restores the host interface back UP.
- Reuses a single podNetnsHandle (hostHandle, hostSocket, open pod containerNs FD, and podHandle) as well as the attached nsLink across all devices and post-attach configuration in RunPodSandbox, avoiding repeated namespace opens, thread setns transitions, and netlink socket allocations per device.
- Moves applyEthtoolConfig before LinkSetUp in nsAttachNetdevWithHandle so hardware drivers (mlx5_core) do not execute a second channel teardown/reopen cycle (mlx5e_safe_switch_params) when features or private flags are changed.

---

1. Production Evidence (a4-highgpu-8g, 8 × Mellanox ConnectX-7 NICs)

From networking-dra-driver logs on an a4-highgpu-8g GKE cluster (kernel 6.12.90+, containerd://2.2.3, 8 × Mellanox ConnectX-7 gpu0rdma0..gpu7rdma0 per node):

PrepareResourceClaim (Kubelet NodePrepareResources phase)


I1002 02:27:37.728754 dra_hooks.go:141] PrepareResourceClaim Claim default/a4pr-p2tel-2026-10-01-192734-benchmar-mrdma-clnz9nf
I1002 02:27:37.745276 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_0
I1002 02:27:37.752686 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_1
I1002 02:27:37.768997 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_2
I1002 02:27:37.774361 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_3
I1002 02:27:37.785303 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_4
I1002 02:27:37.788327 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_5
I1002 02:27:37.797085 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_6
I1002 02:27:37.798193 dra_hooks.go:380] RunPodSandbox processing RDMA device: mlx5_7
I1002 02:27:37.798260 dra_hooks.go:144] PrepareResourceClaim Claim default/a4pr-p2tel-2026-10-01-192734-benchmar-mrdma-clnz9nf took 69.502879ms

RunPodSandbox (Container Runtime NRI hook phase — 2.0s timeout)


I1002 02:27:39.960131 nri_hooks.go:115] RunPodSandbox Pod default/a4pr-p2tel-2026-10-01-192734-benchmark-0-2-wpls2 UID c44625b2-3dc6-4fee-9fe6-e6eafd5064e9
I1002 02:27:39.960188 nri_hooks.go:243] RunPodSandbox processing Network device: gpu4rdma0   (+243.4 ms)
I1002 02:27:40.203603 nri_hooks.go:243] RunPodSandbox processing Network device: gpu5rdma0   (+241.2 ms)
I1002 02:27:40.444844 nri_hooks.go:243] RunPodSandbox processing Network device: gpu6rdma0   (+234.7 ms)
I1002 02:27:40.679550 nri_hooks.go:243] RunPodSandbox processing Network device: gpu7rdma0   (+283.9 ms)
I1002 02:27:40.963459 nri_hooks.go:243] RunPodSandbox processing Network device: gpu0rdma0   (+245.0 ms)
I1002 02:27:41.208444 nri_hooks.go:243] RunPodSandbox processing Network device: gpu1rdma0   (+238.9 ms)
I1002 02:27:41.447303 nri_hooks.go:243] RunPodSandbox processing Network device: gpu2rdma0   (+235.2 ms)
I1002 02:27:41.682539 nri_hooks.go:243] RunPodSandbox processing Network device: gpu3rdma0   (+238.2 ms)
I1002 02:27:41.920715 nri_hooks.go:120] RunPodSandbox Pod default/a4pr-p2tel-2026-10-01-192734-benchmark-0-2-wpls2 UID c44625b2-3dc6-4fee-9fe6-e6eafd5064e9 took 1.960558231s

Each ConnectX-7 NIC takes 218 ms – 284 ms in RunPodSandbox, putting 8 NICs at 1.75 s – 1.96 s under ideal conditions and >2.0 s whenever there is scheduling/lock jitter or additional interface configuration.

---

2. Root-Cause Measurements & Benchmarks

A. Software dummy Interface Microbenchmarks (pkg/driver/attach_bench_test.go)

Command:

go test -run=^$ -bench=BenchmarkAttach -benchtime=2x ./pkg/driver

##### Per-Phase Breakdown (BenchmarkAttachNetdevPhases, 96-vCPU node)
| Benchmark Sub-test | Latency (ns/op) | Latency (ms) | What it measures |
| :--- | ---: | ---: | :--- |
| 1_LinkByName_Host | 75,765 | 0.076 ms | Netlink RTM_GETLINK in host netns |
| 2_LinkSetDown_And_Up_Host | 207,417 | 0.207 ms | Software dummy link DOWN + UP |
| 3_NetnsMove_IFLA_NET_NS_FD_RoundTrip | 100,861,603 | 100.86 ms | 50.00 ms host $\to$ pod + 50.33 ms pod $\to$ host |
| 4_NewHandleAt_And_LinkByName_PodNS | 152,290 | 0.152 ms | setns + netlink socket + RTM_GETLINK in pod netns |
| 5_Sysctl_PodNS | 205,670 | 0.206 ms | Unshare mount ns + mount /proc/sys + write accept_ra |
| 6_Ethtool_FeaturesSet_PodNS | 227,502 | 0.228 ms | ETHTOOL_MSG_FEATURES_GET + SET in pod netns |
| 7_FullAttachConfigureAndDetach_1NIC | 95,361,329 | 95.36 ms | 46.33 ms attach + 0.33 ms config + 48.33 ms detach |

##### Sequential vs. Parallel vs. Pre-Downed + Shared Handle (BenchmarkAttachManyDevices, 1 to 8 dummy NICs)
| NIC Count | Sequential Total (ms/nic) | Parallel Goroutines Total (ms/nic) | Pre-Downed + Shared podNetnsHandle (ms/nic) |
| :--- | ---: | ---: | ---: |
| 1 NIC | 94.5 ms (94.5 ms/nic) | 67.0 ms (67.0 ms/nic) | 50.5 ms (50.5 ms/nic) |
| 2 NICs | 93.5 ms (46.8 ms/nic) | 111.0 ms (55.5 ms/nic) | 86.0 ms (43.0 ms/nic) |
| 4 NICs | 215.0 ms (53.8 ms/nic) | 239.5 ms (59.9 ms/nic) | 226.0 ms (56.5 ms/nic) |
| 8 NICs | 446.5 ms (55.81 ms/nic) | 408.0 ms (51.00 ms/nic) | 397.0 ms (49.62 ms/nic) |

Why parallel goroutines do not speed up RunPodSandbox:

Every RTM_NEWLINK (IFLA_NET_NS_FD, IFF_UP, etc.) acquires the Linux kernel's global rtnl_lock(). Inside dev_change_net_namespace() (net/core/dev.c), while holding rtnl_lock(), the kernel executes dev_close_many(), call_netdevice_notifiers(NETDEV_UNREGISTER), synchronize_net(), and rcu_barrier() across all CPUs. Even for a software dummy interface, the RCU grace period + barrier under rtnl_lock() takes ~50 ms per NIC (~400 ms for 8 NICs), and spawning concurrent goroutines only adds LockOSThread + setns + rtnl_lock contention. Sequential execution with a single shared podNetnsHandle is both simpler and faster.

---

B. Hardware Measurements on a4-highgpu-8g (8 × Mellanox ConnectX-7 NICs)

Measured on an idle a4-highgpu-8g node (kernel 6.12.90+, gpu0rdma0..gpu7rdma0, PCIe 0000:91:00.0 .. 0000:ce:00.0, mtu 8896, numtxqueues 96, numrxqueues 11):

##### 1. Single Mellanox ConnectX-7 NIC (gpu0rdma0) Phase Breakdown

=== 1. SINGLE NIC (gpu0rdma0) PHASE BREAKDOWN ===
1. Host LinkSetDown (UP->DOWN):        56 ms (56508 us)
2. Netns move (while already DOWN):    35 ms (35812 us)
3. Pod AddrAdd:                         3 ms ( 3125 us)
4. Pod LinkSetUp (DOWN->UP):          132 ms (132864 us)
5. Pod RouteAdd (2 routes):             4 ms ( 4849 us)
   TOTAL (1..5 current flow):         233 ms
   TOTAL (2..5 if already DOWN):      176 ms
6. Netns move while UP (fused close):  99 ms (99793 us)
7. Host LinkSetUp (DOWN->UP):         123 ms (123206 us)

  • Why LinkSetDown takes 56–65 ms and LinkSetUp takes 124–136 ms on ConnectX-7:

  • - Each gpuNrdma0 interface has 11 RX queues and 96 TX queues.
    - LinkSetDown calls mlx5e_close_locked(), which issues synchronous PCIe firmware commands (mlx5_cmd_exec) to the ConnectX-7 HCA to tear down all TIRs, RQT, RQs, SQs, and CQs while holding rtnl_lock().
    - LinkSetUp calls mlx5e_open_locked(), which allocates ring buffers and issues synchronous PCIe firmware commands to create all 11 RX + 96 TX queues, CQs, RQs, SQs, and TIRs while holding rtnl_lock().
    - Moving gpu0rdma0 while still UP (99.8 ms) takes the same time as LinkSetDown (56.5 ms) + Netns move while DOWN (35.8 ms) = 92.3 ms because dev_change_net_namespace() calls dev_close_many() (mlx5e_close_locked()) inside the kernel.
    - Furthermore, if applyEthtoolConfig is called after LinkSetUp (as dranet previously did), mlx5_core executes mlx5e_safe_switch_params(), closing (56 ms) and reopening (132 ms) all channels a second time (+188 ms/NIC = +1.5 s for 8 NICs).

    ##### 2. All 8 Mellanox ConnectX-7 NICs (gpu0rdma0..gpu7rdma0) Across 3 Scenarios

    ###### Scenario A: Unoptimized DraNet Flow (1,917 ms in RunPodSandbox)

    === 2. 8 MELLANOX NICs (gpu0rdma0..gpu7rdma0): CURRENT FLOW ===
      gpu0rdma0: total=230ms (down=56ms, move=42ms, addr+up=125ms, routes=6ms)
      gpu1rdma0: total=235ms (down=59ms, move=42ms, addr+up=128ms, routes=5ms)
      gpu2rdma0: total=253ms (down=65ms, move=47ms, addr+up=136ms, routes=4ms)
      gpu3rdma0: total=246ms (down=62ms, move=45ms, addr+up=134ms, routes=4ms)
      gpu4rdma0: total=233ms (down=59ms, move=40ms, addr+up=128ms, routes=4ms)
      gpu5rdma0: total=234ms (down=61ms, move=40ms, addr+up=128ms, routes=4ms)
      gpu6rdma0: total=236ms (down=58ms, move=45ms, addr+up=128ms, routes=4ms)
      gpu7rdma0: total=237ms (down=56ms, move=43ms, addr+up=133ms, routes=5ms)
    TOTAL 8 NICs (Current Flow): 1917 ms
    

    ###### Scenario B: Pre-Downing Passthrough NICs in NodePrepareResources (1,444 ms in RunPodSandbox)
    Moving LinkSetDown to the end of prepareDevice in NodePrepareResources (after getDHCP, AddrList, getRouteInfo, and NeighList have already captured the host state) shifts 463 ms (8 × ~58 ms) out of the 2-second NRI RunPodSandbox hook into the kubelet NodePrepareResources gRPC call:

    === SCENARIO B: Host LinkSetDown in NodePrepareResources, then RunPodSandbox ===
    NodePrepareResources (8x LinkSetDown): 463 ms
      gpu0rdma0: total=182ms (move=43ms, addr+up=133ms, routes=5ms)
      gpu1rdma0: total=169ms (move=39ms, addr+up=124ms, routes=5ms)
      gpu2rdma0: total=180ms (move=44ms, addr+up=130ms, routes=5ms)
      gpu3rdma0: total=174ms (move=38ms, addr+up=125ms, routes=10ms)
      gpu4rdma0: total=184ms (move=46ms, addr+up=132ms, routes=5ms)
      gpu5rdma0: total=175ms (move=39ms, addr+up=130ms, routes=5ms)
      gpu6rdma0: total=183ms (move=47ms, addr+up=128ms, routes=7ms)
      gpu7rdma0: total=186ms (move=48ms, addr+up=132ms, routes=4ms)
    TOTAL RunPodSandbox (Scenario B): 1444 ms
    

    ###### Scenario C: Pre-Downing in NodePrepareResources + Shared podNetnsHandle in RunPodSandbox (1,277–1,284 ms in RunPodSandbox)
    Combining pre-downed interfaces with a single shared podNetnsHandle (hostHandle, hostSocket, containerNs, podHandle) across the 8 NICs in pkg/driver (avoiding 40+ LockOSThread + setns + netlink socket creations and redundant LinkByName lookups) reduces RunPodSandbox for 8 ConnectX-7 NICs to 1,277–1,284 ms:

    === pkg/driver VALIDATION ON a4-highgpu-8g (gpu0rdma0..gpu7rdma0) ===
    [OPTIMIZED 8 NICs] PrepareResourceClaims(LinkSetDown)=444.900367ms (stillUp=0) | RunPodSandbox total=1.283657168s (nsAttachNetdevWithHandle=1.278215563s, configureNetdevInNSWithHandle=5.386411ms, avg=160.457146ms/NIC)
    [BASELINE 8 NICs]  RunPodSandbox total=1.739782814s (nsAttachNetdev=1.732717876s, configureNetdevInNS=7.059386ms, avg=217.472851ms/NIC)
    

    | Scenario (8 × Mellanox ConnectX-7 on a4-highgpu-8g) | NodePrepareResources | RunPodSandbox | Margin Before 1,800 ms Budget (2.0s NRI Timeout) |
    | :--- | ---: | ---: | :--- |
    | A. Unoptimized Flow | 69 ms | 1,740 – 1,917 ms | -117 ms to +60 ms (Fails budget / times out under jitter) |
    | B. LinkSetDown in NodePrepareResources | 532 ms | 1,444 ms | +356 ms (+556 ms before 2.0s) |
    | C. LinkSetDown in NodePrepareResources + Shared podNetnsHandle | 514 – 532 ms | 1,277 – 1,284 ms | +516 – 523 ms (+716 – 723 ms before 2.0s) |

    Which issue(s) this PR is related to:

    Fixes #310

    Special notes for your reviewer:

    Structured into 3 commits for easy review:
    1. driver: benchmark NIC netns attachment and skip empty route/rule/neighbor netlink calls (66fcdea)
    - Adds BenchmarkAttachNetdevPhases and BenchmarkAttachManyDevices in pkg/driver/attach_bench_test.go (using userns.RunBenchmark in internal/testutils/userns.go) to measure per-phase netlink/kernel costs and demonstrate why rtnl_lock serialization prevents parallel goroutine speedups.
    - Skips opening the pod netns and netlink handles in applyRoutingConfig, applyRulesConfig, and applyNeighborConfig when the corresponding config slice is empty.
    2. driver: fail RunPodSandbox before the NRI request timeout expires (2813ece)
    - Keeps RunPodSandbox completely synchronous (no background goroutines or OCI hook binary).
    - RunPodSandbox derives a budgetCtx from ctx.Deadline() minus defaultNRIReplyMargin (200ms). Before starting each device (and after each device completes), runPodSandbox checks whether budgetCtx has expired or whether the remaining budget is smaller than the average time spent per device so far (elapsed / completed > remaining).
    - If the budget is exceeded, RunPodSandbox emits a NetworkDeviceAttachTimeout Warning event on the Pod, increments dranet_driver_sandbox_attach_total{result="rejected_timeout"}, and returns an error before containerd's NRI timer expires.
    3. driver: set passthrough NICs down in PrepareResourceClaims and reuse pod netlink handle (7c9f172)
    - Sets passthrough host interfaces DOWN at the end of prepareDevice in NodePrepareResources (after addresses, routes, permanent neighbors, and device snapshots have been captured) so hardware queue teardown (mlx5e_close_locked, ~56 ms/NIC) runs under kubelet's 30s gRPC timeout instead of NRI's 2s RunPodSandbox timeout, and restores the host interface to UP in unprepareResourceClaim if the pod never moved it.
    - Skips redundant LinkSetDown calls in nsAttachNetdevWithHandle when the host device is already DOWN.
    - Introduces podNetnsHandle to reuse a single host netlink handle, host netlink route socket, open pod netns FD, and pod netlink handle (as well as the attached nsLink) across all devices and configureNetdevInNSWithHandle in RunPodSandbox.

    Does this PR introduce a user-facing change?

    ``release-note
    DRANET now fails
    RunPodSandbox before the container runtime's NRI request timeout expires (emitting a NetworkDeviceAttachTimeout Warning event on the Pod) instead of letting the runtime disconnect the NRI plugin and start a Pod with missing network interfaces. Additionally, PrepareResourceClaims now sets passthrough host interfaces down ahead of RunPodSandbox and RunPodSandbox reuses a single netlink handle across all devices for a Pod, reducing 8-NIC ConnectX-7 attachment time from ~1.92s to ~1.28s. New dranet_driver_nri_request_timeout_seconds, dranet_driver_device_attach_duration_seconds, and dranet_driver_sandbox_attach_total Prometheus metrics report NRI timeout and device attachment latencies.
    ``

    Diff: 1918 lines (+1776 / -142) across 29 files Reviewer: aojea Review duration: 34746m
    All Vouch review confidence checks passed
    Residual risk 0.13 = Change Risk (0.86) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 1918 lines diff across 29 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.76 · 5 substantive comment(s)
    0.76
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    39 items
    netlify[bot] netlify[bot] commented on Oct 03, 2026 17:16 UTC
    Bot

    <span aria-hidden="true">✅</span> Deploy Preview for dranet canceled.

    | Name | Link |
    |:-:|------------------------|
    |<span aria-hidden="true">🔨</span> Latest commit | b4111d2507b866196b18c8271c6952cacfa5b8ea |
    |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/dranet/deploys/6ac4f3969170c700081324fd |

    kubernetes-prow[bot] kubernetes-prow[bot] commented on Oct 03, 2026 17:16 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/dranet/pull/370#" title="Author self-approved">aojea</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [aojea]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    aojea aojea commented on Oct 06, 2026 10:34 UTC
    Author

    /assign @dkennetzoracle @gauravkghildiyal

    Allowing to move forward without binding all interfaces when we were told to you so is terrible , it also adds better instrumentation to be able to detect problems and create alerst in case the budget for attaching is close to the limit.

    As today if the budget is low the official solution is to configure containerd or crio to increase the per plugin timeout ... we still can find a better solution long term but I do not want us to put into a temporary hack that later will bit us and we no longer can get rid of it ... I have some ideas but we need to work with the runtime and NRI folks

    aojea aojea commented on code on Oct 06, 2026 11:04 UTC
    Code Review
    tests/e2e.bats:1
    @@ -356,7 +356,7 @@ wait_for_ready_pods() {
       assert_output --partial "00:11:22:33:44:55"
     
       # Validate ethtool settings inside the pod for interface dranet0
    -  run kubectl exec pod-advanced-cfg -- ash -c "apk add ethtool && ethtool -k dranet0"

    this flakes since it depends on the cdn

    WARNING: updating and opening https://dl-cdn.alpinelinux.org/alpine/v3.19/main: temporary error (try again later)

    aojea aojea commented on Oct 07, 2026 10:56 UTC
    Author

    /priority important-soon

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:32 UTC
    Code Review
    pkg/driver/nri_hooks.go:1
    @@ -144,86 +171,82 @@ func (np *NetworkDriver) RunPodSandbox(ctx context.Context, pod *api.PodSandbox)
     	}
     	return err
     }
    +
     func (np *NetworkDriver) runPodSandbox(ctx context.Context, pod *api.PodSandbox, podConfig PodConfig) error {
     	logger := klog.FromContext(ctx)
    +	podUID := types.UID(pod.GetUid())
    +	if deadline, ok := ctx.Deadline(); ok {
    +		nriRequestTimeoutSeconds.Set(time.Until(deadline).Round(100 * time.Millisecond).Seconds())
    +	}
     	// get the pod network namespace
     	ns := getNetworkNamespace(pod)
     	// host network pods can not allocate network devices because it impact the host
     	if ns == "" {
     		return fmt.Errorf("RunPodSandbox pod %s/%s using host network can not claim host devices", pod.Namespace, pod.Name)
     	}
     	// store the Pod network namespace in the pod config store
    -	np.podConfigStore.SetPodNetNs(types.UID(pod.GetUid()), ns)
    +	np.podConfigStore.SetPodNetNs(podUID, ns)
    +
    +	total := len(podConfig.DeviceConfigs)
    +	if total == 0 {
    +		return nil
    +	}
    +
    +	nsHandle := newPodNetnsHandle(ns)
    +	defer nsHandle.Close()
    +
    +	budgetCtx, cancel := np.requestBudget(ctx)
    +	defer cancel()
    +	budgetDeadline, hasDeadline := budgetCtx.Deadline()
    +
    +	failTimeout := func(attached int) error {
    +		sandboxAttachTotal.WithLabelValues(attachResultRejected).Inc()
    +		np.eventRecorder.Eventf(podObjectRef(pod), v1.EventTypeWarning, "NetworkDeviceAttachTimeout",
    +			"attached %d/%d network devices to pod %s/%s within the container runtime NRI request timeout; failing the sandbox so the pod does not start with missing devices. Increase the container runtime NRI plugin_request_timeout",
    +			attached, total, pod.GetNamespace(), pod.GetName())
    +		logger.Info("RunPodSandbox out of request budget, failing the sandbox", "attached", attached, "total", total)
    +		return fmt.Errorf("attached %d/%d network devices: %w", attached, total, errNRIBudgetExceeded)
    +	}
     
     	// Track all the status updates needed for the resource claims of the pod.
     	statusUpdates := map[types.NamespacedName]*resourceapply.ResourceClaimStatusApplyConfiguration{}
    -	// Process the configurations of the ResourceClaim
    +	loopStart := time.Now()
    +	attached := 0
     	for deviceName, config := range podConfig.DeviceConfigs {
    +		if budgetCtx.Err() != nil || (hasDeadline && attached > 0 && time.Until(budgetDeadline) < time.Since(loopStart)/time.Duration(attached)) {

    Does the first device ever get checked?

    Additionnally, a device that runs 200ms more than the average still finishes past the runtime deadline. Based on my simulations (nics in the meta comment) spread between 218-284ms per NIC.

    Rec: project with the longest device seen so far instead of average (I have an example with attachBudget in #371 that does this).
    rec: pass the budget context into the per-device work down on 221, right?

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:34 UTC
    Code Review
    pkg/driver/nri_hooks.go:1
    @@ -144,86 +171,82 @@ func (np *NetworkDriver) RunPodSandbox(ctx context.Context, pod *api.PodSandbox)
     	}
     	return err
     }
    +
     func (np *NetworkDriver) runPodSandbox(ctx context.Context, pod *api.PodSandbox, podConfig PodConfig) error {
     	logger := klog.FromContext(ctx)
    +	podUID := types.UID(pod.GetUid())
    +	if deadline, ok := ctx.Deadline(); ok {
    +		nriRequestTimeoutSeconds.Set(time.Until(deadline).Round(100 * time.Millisecond).Seconds())
    +	}
     	// get the pod network namespace
     	ns := getNetworkNamespace(pod)
     	// host network pods can not allocate network devices because it impact the host
     	if ns == "" {
     		return fmt.Errorf("RunPodSandbox pod %s/%s using host network can not claim host devices", pod.Namespace, pod.Name)
     	}
     	// store the Pod network namespace in the pod config store
    -	np.podConfigStore.SetPodNetNs(types.UID(pod.GetUid()), ns)
    +	np.podConfigStore.SetPodNetNs(podUID, ns)
    +
    +	total := len(podConfig.DeviceConfigs)
    +	if total == 0 {
    +		return nil
    +	}
    +
    +	nsHandle := newPodNetnsHandle(ns)
    +	defer nsHandle.Close()
    +
    +	budgetCtx, cancel := np.requestBudget(ctx)
    +	defer cancel()
    +	budgetDeadline, hasDeadline := budgetCtx.Deadline()
    +
    +	failTimeout := func(attached int) error {
    +		sandboxAttachTotal.WithLabelValues(attachResultRejected).Inc()
    +		np.eventRecorder.Eventf(podObjectRef(pod), v1.EventTypeWarning, "NetworkDeviceAttachTimeout",
    +			"attached %d/%d network devices to pod %s/%s within the container runtime NRI request timeout; failing the sandbox so the pod does not start with missing devices. Increase the container runtime NRI plugin_request_timeout",
    +			attached, total, pod.GetNamespace(), pod.GetName())
    +		logger.Info("RunPodSandbox out of request budget, failing the sandbox", "attached", attached, "total", total)
    +		return fmt.Errorf("attached %d/%d network devices: %w", attached, total, errNRIBudgetExceeded)
    +	}
     
     	// Track all the status updates needed for the resource claims of the pod.
     	statusUpdates := map[types.NamespacedName]*resourceapply.ResourceClaimStatusApplyConfiguration{}
    -	// Process the configurations of the ResourceClaim
    +	loopStart := time.Now()
    +	attached := 0
     	for deviceName, config := range podConfig.DeviceConfigs {
    +		if budgetCtx.Err() != nil || (hasDeadline && attached > 0 && time.Until(budgetDeadline) < time.Since(loopStart)/time.Duration(attached)) {
    +			return failTimeout(attached)
    +		}
     		logger.V(4).Info("RunPodSandbox processing device", "device", deviceName, "config", fmt.Sprintf("%#v", config))
    +		deviceStart := time.Now()
    +		resourceClaimStatusDevice, err := np.attachDevice(ctx, pod, ns, nsHandle, deviceName, config)
    +		if err != nil {
    +			deviceAttachDurationSeconds.WithLabelValues(attachResultFailed).Observe(time.Since(deviceStart).Seconds())
    +			sandboxAttachTotal.WithLabelValues(attachResultFailed).Inc()
    +			return err
    +		}
    +		deviceAttachDurationSeconds.WithLabelValues(attachResultAttached).Observe(time.Since(deviceStart).Seconds())
    +		attached++
    +		if budgetCtx.Err() != nil {

    Should you skip this when attached == total? IE can this fail a sandbox that's already fully attached?

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:36 UTC
    Code Review
    pkg/driver/nri_hooks.go:1
    @@ -144,86 +171,82 @@ func (np *NetworkDriver) RunPodSandbox(ctx context.Context, pod *api.PodSandbox)
     	}
     	return err
     }
    +
     func (np *NetworkDriver) runPodSandbox(ctx context.Context, pod *api.PodSandbox, podConfig PodConfig) error {
     	logger := klog.FromContext(ctx)
    +	podUID := types.UID(pod.GetUid())
    +	if deadline, ok := ctx.Deadline(); ok {
    +		nriRequestTimeoutSeconds.Set(time.Until(deadline).Round(100 * time.Millisecond).Seconds())
    +	}
     	// get the pod network namespace
     	ns := getNetworkNamespace(pod)
     	// host network pods can not allocate network devices because it impact the host
     	if ns == "" {
     		return fmt.Errorf("RunPodSandbox pod %s/%s using host network can not claim host devices", pod.Namespace, pod.Name)
     	}
     	// store the Pod network namespace in the pod config store
    -	np.podConfigStore.SetPodNetNs(types.UID(pod.GetUid()), ns)
    +	np.podConfigStore.SetPodNetNs(podUID, ns)
    +
    +	total := len(podConfig.DeviceConfigs)
    +	if total == 0 {
    +		return nil
    +	}
    +
    +	nsHandle := newPodNetnsHandle(ns)
    +	defer nsHandle.Close()
    +
    +	budgetCtx, cancel := np.requestBudget(ctx)
    +	defer cancel()
    +	budgetDeadline, hasDeadline := budgetCtx.Deadline()
    +
    +	failTimeout := func(attached int) error {

    Devices here stay in the pod netns and getting them back depends on the runtime calling NRI StopPodSandbox before it deletes the netns. Crio 1.36 does this, but I think this was the initial problem I hit with crio right? Teardown out of order or error in StopPodSandbox orphaned devices?

    I think we should detach what this request attached before returnning would make the fail-closed guarantee independent of the runtime..

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:38 UTC
    Code Review
    pkg/driver/nri_hooks.go:1

    I also noticed in testing that this tries to detach every device of the claim, including ones the budget never gets to. In one of my runs, I got 28 link not found errors for devices still on the host. If we keep track of attached devices, this and the rollback I mentioned at the failTimeout funnc get easier.

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:40 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their

    Setting these as "down" during NodePrepareResources can cause race conditions with our health checks. I'm not sure we will use passthrough though.. @OguzPastirmaci what do you think here?

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:41 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -565,12 +583,19 @@ func (np *NetworkDriver) unprepareResourceClaim(_ context.Context, claim kubelet
     		}
     		for deviceName, devCfg := range podCfg.DeviceConfigs {
     			if devCfg.Claim.Namespace == claim.Namespace && devCfg.Claim.Name == claim.Name {
    +				ifName := devCfg.NetworkInterfaceConfigInHost.Interface.Name
    +				if ifName != "" && !devCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() {
    +					if hostDev, err := nlwrap.LinkByName(ifName); err == nil && hostDev.Attrs().Flags&net.FlagUp == 0 {
    +						if err := netlink.LinkSetUp(hostDev); err != nil {

    this brings up any down passthrough host link of the claim. Prepare only takes down links that were up, but doesn't record which ones, so a link an admin had down before prepare gets brought up here. Persisting a "downed by prepare" flag in the DeviceConfig checkpoint and only restoring that would fix it.

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:47 UTC
    Code Review
    pkg/driver/hostdevice.go:1
    @@ -163,17 +242,17 @@ func nsAttachNetdev(hostIfName string, containerNsPAth string, interfaceConfig a
     		}
     		err = nhNs.AddrAdd(nsLink, &netlink.Addr{IPNet: &net.IPNet{IP: ip, Mask: ipnet.Mask}})
     		if err != nil {
    -			return nil, fmt.Errorf("failed to set up address %s on namespace %s: %w", address, containerNsPAth, err)
    +			return nil, nil, fmt.Errorf("failed to set up address %s on namespace %s: %w", address, containerNsPAth, err)
     		}
     		networkData.IPs = append(networkData.IPs, address)
     	}
     
     	err = nhNs.LinkSetUp(nsLink)

    description says this runs before but looks like it still runs after re: nri_hooks.go:420

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:49 UTC
    Code Review
    pkg/driver/driver.go:1
    @@ -95,6 +95,15 @@ func WithKubeletRootDir(dir string) Option {
     	}
     }
     
    +// WithNRIReplyMargin sets the time reserved at the end of every NRI request
    +// for the reply to reach the container runtime before its plugin request
    +// timeout fires. Defaults to 200ms.
    +func WithNRIReplyMargin(d time.Duration) Option {
    +	return func(o *NetworkDriver) {
    +		o.nriReplyMargin = d

    should we make this configurable? Seems like we could make 200ms the default but add an option to increase it?

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:51 UTC
    Code Review
    pkg/driver/nri_hooks.go:1
    @@ -40,6 +41,32 @@ import (
     // the information necessary should passed to the NRI hooks via the np.podConfigStore so it can be executed
     // quickly.
     
    +// defaultNRIReplyMargin is the time reserved at the end of an NRI request for
    +// the reply to reach the runtime before its plugin_request_timeout fires.
    +const defaultNRIReplyMargin = 200 * time.Millisecond
    +
    +// errNRIBudgetExceeded is returned when attaching the Pod's devices does not fit
    +// in the NRI request budget. The runtime treats a plugin error returned before
    +// its deadline as a failure of the sandbox (cleaning up the network namespace
    +// and letting the kubelet retry), whereas a reply after the deadline
    +// disconnects the plugin and starts the Pod without its devices.
    +var errNRIBudgetExceeded = errors.New("not enough time left in the NRI request to attach all the network devices; increase the container runtime NRI plugin_request_timeout")

    I think in crio this is called nri_plugin_request_timeout so we could either make it agnostic "runtime NRI plugin request timeout" or mention both?

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:53 UTC
    Code Review
    pkg/driver/metrics.go:1
    @@ -75,6 +84,25 @@ var (
     		Name:      "nri_plugin_requests_latency_seconds",
     		Help:      "NRI plugin request latency in seconds.",
     	}, []string{"method", "status"})
    +	nriRequestTimeoutSeconds = prometheus.NewGauge(prometheus.GaugeOpts{

    This is set at nri_hooks.go from time.Until(deadline) when the hook starts, so this would be the time left in the request, not the configured timeout. Maybe rename to something like request_remaining_seconds or say more accurately what it measures in the help text.

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:53 UTC
    Code Review
    pkg/driver/netnamespace.go:1
    @@ -279,7 +326,9 @@ func applyVRFConfig(containerNsPath string, ifName string, vrfConfig *apis.VRFCo
     			LinkAttrs: netlink.LinkAttrs{Name: vrfName},
     			Table:     vrfTable,
     		}
    -		if err := nhNs.LinkAdd(vrfReq); err != nil {
    +		// Devices attach in parallel and may share the VRF: the first one to

    nit: these are sequential now right?

    dkennetzoracle dkennetzoracle commented on code on Oct 07, 2026 20:54 UTC
    Code Review
    tests/setup_suite.bash:1
    @@ -7,9 +7,15 @@ function setup_suite {
       # Define the name of the kind cluster
       export CLUSTER_NAME="dranet-test-cluster"
       export IMAGE_NAME="registry.k8s.io/networking/dranet"
    +  export AGNHOST_IMAGE="registry.k8s.io/e2e-test-images/agnhost:2.66.1"

    nit: unrelated?

    dkennetzoracle dkennetzoracle requested changes on Oct 07, 2026 20:58 UTC
    Changes Requested Reviewer

    Thanks for this, tested it pretty heavily on OKE (k8s 1.36.4, CRI-O 1.36.3,) with passthrough dummy interfaces up to 40 per pod, with up to 1800 addresses each so attach is slow enough to hit the limit.

  • fail-closed path does waht it says, each attempt stopped at 1.68-1.78s, CRI-O reported FailedCreatePodSandbox with the new error, the kubelet retried, and the pod never started with missing devices. CRI-O also called StopPodSandbox before removing the netns on this path, so the devices that had been moved came back.

  • The happy path was fine: 8 devices in 71ms, 40 in 410ms
  • A few things below, the main ones are the budget check (one device can still overrun), the post-loop check throwing away a complete attach, and the side-effects of taking NICs down in PrepareResourceClaims. The description also mentions the ethool reorder that doesn't appear in the diff.

    Some additional recs below, but overall small changes requested and solid PR for the work.

    OguzPastirmaci OguzPastirmaci commented on code on Oct 07, 2026 22:51 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their

    This doesn't reach OKE RDMA NICs because we reject passthrough in OKE provider. If we do the same thing in the IPv6 side, we should be safe.

    aojea aojea commented on code on Oct 08, 2026 09:24 UTC
    Code Review
    tests/setup_suite.bash:1
    @@ -7,9 +7,15 @@ function setup_suite {
       # Define the name of the kind cluster
       export CLUSTER_NAME="dranet-test-cluster"
       export IMAGE_NAME="registry.k8s.io/networking/dranet"
    +  export AGNHOST_IMAGE="registry.k8s.io/e2e-test-images/agnhost:2.66.1"

    yeah, but speeds up CI , I hate slow CIs, is a separate commit so we can land it here or independnetly

    dkennetzoracle dkennetzoracle commented on code on Oct 08, 2026 12:09 UTC
    Code Review
    tests/setup_suite.bash:1
    @@ -7,9 +7,15 @@ function setup_suite {
       # Define the name of the kind cluster
       export CLUSTER_NAME="dranet-test-cluster"
       export IMAGE_NAME="registry.k8s.io/networking/dranet"
    +  export AGNHOST_IMAGE="registry.k8s.io/e2e-test-images/agnhost:2.66.1"

    Works for me, I did not know what it was - thanks for sharing!

    anson627 anson627 commented on code on Oct 09, 2026 18:02 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their
    +	// addresses, routes, and neighbors have been captured so hardware queue
    +	// teardown happens before the latency-sensitive RunPodSandbox NRI hook.
    +	linkDowned := false
    +	if !deviceCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() &&
    +		(deviceCfg.NetworkInterfaceConfigInPod.Interface.AcceptRA == nil ||
    +			deviceCfg.NetworkInterfaceConfigInPod.Interface.MTU != nil ||
    +			link.Attrs().MTU >= apis.MinIPv6MTU) &&
    +		link.Attrs().Flags&net.FlagUp != 0 {
    +		if err := nlHandle.LinkSetDown(link); err != nil {
    +			return fmt.Errorf("failed to set interface %s down: %v", ifName, err)
    +		}
    +		linkDowned = true

    One side effect of taking the link down here that might bite on retries: when an interface goes down, the kernel flushes its IPv4 routes, and its IPv6 addresses too unless keep_addr_on_down=1. prepareDevice reads addresses and routes from the live host interface every time it runs, and nothing skips devices that were already prepared

    So if a claim has devices A and B, A is taken down and saved, and then B fails, the kubelet retries NodePrepareResources. A gets prepared again from its down state, and the saved config ends up without its routes and IPv6 addresses. The pod then starts with A but no routing

    Two options:

    skip devices that are already saved for this podUID/claim, or
    only take links down once every device in the claim has prepared successfully

    WDYT?

    anson627 anson627 commented on code on Oct 09, 2026 18:03 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their
    +	// addresses, routes, and neighbors have been captured so hardware queue
    +	// teardown happens before the latency-sensitive RunPodSandbox NRI hook.
    +	linkDowned := false
    +	if !deviceCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() &&
    +		(deviceCfg.NetworkInterfaceConfigInPod.Interface.AcceptRA == nil ||
    +			deviceCfg.NetworkInterfaceConfigInPod.Interface.MTU != nil ||
    +			link.Attrs().MTU >= apis.MinIPv6MTU) &&
    +		link.Attrs().Flags&net.FlagUp != 0 {
    +		if err := nlHandle.LinkSetDown(link); err != nil {
    +			return fmt.Errorf("failed to set interface %s down: %v", ifName, err)
    +		}
    +		linkDowned = true
    +	}
    +
     	if err := np.podConfigStore.SetDeviceConfig(podUID, result.Device, deviceCfg); err != nil {
    +		if linkDowned {

    Related to the comment at L521: this brings the link back up only when SetDeviceConfig fails for this device. If a later device in the same claim fails in prepareResourceClaim, the devices already taken down stay down until the claim is unprepared or a retry succeeds. That leaves the host NIC unusable in the meantime, and it creates the retry problem above

    One idea: have prepareDevice return the links it took down, and either bring them all back up in prepareResourceClaim when errorList isn’t empty, or run the link-down in a second pass after every device in the claim has prepared. A second pass would also keep all the state capture ahead of any changes

    anson627 anson627 commented on code on Oct 09, 2026 18:06 UTC
    Code Review
    pkg/driver/driver.go:1
    @@ -95,6 +95,15 @@ func WithKubeletRootDir(dir string) Option {
     	}
     }
     
    +// WithNRIReplyMargin sets the time reserved at the end of every NRI request
    +// for the reply to reach the container runtime before its plugin request
    +// timeout fires. Defaults to 200ms.
    +func WithNRIReplyMargin(d time.Duration) Option {
    +	return func(o *NetworkDriver) {
    +		o.nriReplyMargin = d

    +1. The option exists now, but as far as I can tell nothing in cmd/ calls WithNRIReplyMargin, so it’s always the 200ms default. A flag like --nri-reply-margin would let operators tune it for slow NICs

    anson627 anson627 commented on code on Oct 09, 2026 18:08 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -565,12 +583,19 @@ func (np *NetworkDriver) unprepareResourceClaim(_ context.Context, claim kubelet
     		}
     		for deviceName, devCfg := range podCfg.DeviceConfigs {
     			if devCfg.Claim.Namespace == claim.Namespace && devCfg.Claim.Name == claim.Name {
    +				ifName := devCfg.NetworkInterfaceConfigInHost.Interface.Name
    +				if ifName != "" && !devCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() {
    +					if hostDev, err := nlwrap.LinkByName(ifName); err == nil && hostDev.Attrs().Flags&net.FlagUp == 0 {
    +						if err := netlink.LinkSetUp(hostDev); err != nil {

    +1 on persisting the flag. Minor nit while you’re in here: this calls the plain netlink.LinkSetUp instead of the nlwrap handle used everywhere else, so it skips the dump-interrupted retry handling

    anson627 anson627 commented on Oct 09, 2026 18:09 UTC
    Contributor

    Thanks @aojea, this is a really valuable fix: failing closed before the runtime deadline is clearly better than starting a pod without its NICs, and the benchmarks make the reasoning easy to follow. @dkennetzoracle’s comments cover the time-budget side well. I left a couple of notes on what happens when prepare is retried after the link has already been taken down, since that looks like it can quietly lose routes and IPv6 addresses. Happy to help test on CoreWeave hardware once those are sorted

    anson627 anson627 commented on code on Oct 09, 2026 18:10 UTC
    Code Review
    pkg/driver/nri_hooks.go:1
    @@ -40,6 +41,32 @@ import (
     // the information necessary should passed to the NRI hooks via the np.podConfigStore so it can be executed
     // quickly.
     
    +// defaultNRIReplyMargin is the time reserved at the end of an NRI request for
    +// the reply to reach the runtime before its plugin_request_timeout fires.
    +const defaultNRIReplyMargin = 200 * time.Millisecond
    +
    +// errNRIBudgetExceeded is returned when attaching the Pod's devices does not fit
    +// in the NRI request budget. The runtime treats a plugin error returned before
    +// its deadline as a failure of the sandbox (cleaning up the network namespace
    +// and letting the kubelet retry), whereas a reply after the deadline
    +// disconnects the plugin and starts the Pod without its devices.
    +var errNRIBudgetExceeded = errors.New("not enough time left in the NRI request to attach all the network devices; increase the container runtime NRI plugin_request_timeout")
    +
    +func requestBudget(ctx context.Context, margin time.Duration) (context.Context, context.CancelFunc) {
    +	if margin <= 0 {

    Small thing: a margin of 0 or less silently becomes 200ms, so there’s no way to opt out of the early cutoff. That could be handy for runtimes that don’t set a deadline, or for debugging. Maybe only fall back to the default when the value is unset, or document the behavior on WithNRIReplyMargin?

    aojea aojea commented on code on Oct 14, 2026 14:32 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their

    can you expand on how this health checks are performed?

    aojea aojea commented on code on Oct 14, 2026 14:34 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their
    +	// addresses, routes, and neighbors have been captured so hardware queue
    +	// teardown happens before the latency-sensitive RunPodSandbox NRI hook.
    +	linkDowned := false
    +	if !deviceCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() &&
    +		(deviceCfg.NetworkInterfaceConfigInPod.Interface.AcceptRA == nil ||
    +			deviceCfg.NetworkInterfaceConfigInPod.Interface.MTU != nil ||
    +			link.Attrs().MTU >= apis.MinIPv6MTU) &&
    +		link.Attrs().Flags&net.FlagUp != 0 {
    +		if err := nlHandle.LinkSetDown(link); err != nil {
    +			return fmt.Errorf("failed to set interface %s down: %v", ifName, err)
    +		}
    +		linkDowned = true

    interesting scenario, but IIRC (I need to verify) you don't go back to the kubelet retries NodePrepareResources , you do the RunPodSandbox and StopPodSandbox dance only

    aojea aojea commented on code on Oct 14, 2026 14:37 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -506,7 +506,25 @@ func (np *NetworkDriver) prepareDevice(ctx context.Context, nlHandle nlwrap.Hand
     		}
     	}
     
    +	// Set passthrough interfaces down during NodePrepareResources after their
    +	// addresses, routes, and neighbors have been captured so hardware queue
    +	// teardown happens before the latency-sensitive RunPodSandbox NRI hook.
    +	linkDowned := false
    +	if !deviceCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() &&
    +		(deviceCfg.NetworkInterfaceConfigInPod.Interface.AcceptRA == nil ||
    +			deviceCfg.NetworkInterfaceConfigInPod.Interface.MTU != nil ||
    +			link.Attrs().MTU >= apis.MinIPv6MTU) &&
    +		link.Attrs().Flags&net.FlagUp != 0 {
    +		if err := nlHandle.LinkSetDown(link); err != nil {
    +			return fmt.Errorf("failed to set interface %s down: %v", ifName, err)
    +		}
    +		linkDowned = true
    +	}
    +
     	if err := np.podConfigStore.SetDeviceConfig(podUID, result.Device, deviceCfg); err != nil {
    +		if linkDowned {

    That leaves the host NIC unusable in the meantime,

    we implement a clear separation of concerns, the NIC on the host are a host problem, DRANET takes them and move them with the additional configuration, but is responsibility from the host process to ensure they are configured correctly, using systemd or custom process

    For the system to be resilient we can not workaround the problem of "the host may not do what is supposed to do", for DRANET the configuration in the host is not a problem and it will be also surprising that if the host depend on that interface that is not already managed

    aojea aojea commented on code on Oct 14, 2026 14:39 UTC
    Code Review
    pkg/driver/dra_hooks.go:1
    @@ -565,12 +583,19 @@ func (np *NetworkDriver) unprepareResourceClaim(_ context.Context, claim kubelet
     		}
     		for deviceName, devCfg := range podCfg.DeviceConfigs {
     			if devCfg.Claim.Namespace == claim.Namespace && devCfg.Claim.Name == claim.Name {
    +				ifName := devCfg.NetworkInterfaceConfigInHost.Interface.Name
    +				if ifName != "" && !devCfg.NetworkInterfaceConfigInPod.Interface.IsSubinterface() {
    +					if hostDev, err := nlwrap.LinkByName(ifName); err == nil && hostDev.Attrs().Flags&net.FlagUp == 0 {
    +						if err := netlink.LinkSetUp(hostDev); err != nil {

    good point, we should not change the behavior now , let me figure out what we were doing before

    aojea aojea commented on code on Oct 14, 2026 14:40 UTC
    Code Review
    pkg/driver/driver.go:1
    @@ -95,6 +95,15 @@ func WithKubeletRootDir(dir string) Option {
     	}
     }
     
    +// WithNRIReplyMargin sets the time reserved at the end of every NRI request
    +// for the reply to reach the container runtime before its plugin request
    +// timeout fires. Defaults to 200ms.
    +func WithNRIReplyMargin(d time.Duration) Option {
    +	return func(o *NetworkDriver) {
    +		o.nriReplyMargin = d

    good call, I was trying to start minimalistic for feedback, but seems the operator feedback is clear here

    aojea aojea commented on code on Oct 14, 2026 14:44 UTC
    Code Review
    pkg/driver/metrics.go:1
    @@ -75,6 +84,25 @@ var (
     		Name:      "nri_plugin_requests_latency_seconds",
     		Help:      "NRI plugin request latency in seconds.",
     	}, []string{"method", "status"})
    +	nriRequestTimeoutSeconds = prometheus.NewGauge(prometheus.GaugeOpts{

    it is effectively the timeout for the request, and seconds is also wrong, it should be milliseconds, let's try to find a more clear name., remaining does not really represent the metrics ... maybe we should introduce the number of the hook to ... the interescting things here will be the efficiency as "time it takes to execute the request" vs "total time it has allocated to execute", this is the later

    aojea aojea commented on code on Oct 14, 2026 14:46 UTC
    Code Review
    pkg/driver/nri_hooks.go:1
    @@ -40,6 +41,32 @@ import (
     // the information necessary should passed to the NRI hooks via the np.podConfigStore so it can be executed
     // quickly.
     
    +// defaultNRIReplyMargin is the time reserved at the end of an NRI request for
    +// the reply to reach the runtime before its plugin_request_timeout fires.
    +const defaultNRIReplyMargin = 200 * time.Millisecond
    +
    +// errNRIBudgetExceeded is returned when attaching the Pod's devices does not fit
    +// in the NRI request budget. The runtime treats a plugin error returned before
    +// its deadline as a failure of the sandbox (cleaning up the network namespace
    +// and letting the kubelet retry), whereas a reply after the deadline
    +// disconnects the plugin and starts the Pod without its devices.
    +var errNRIBudgetExceeded = errors.New("not enough time left in the NRI request to attach all the network devices; increase the container runtime NRI plugin_request_timeout")
    +
    +func requestBudget(ctx context.Context, margin time.Duration) (context.Context, context.CancelFunc) {
    +	if margin <= 0 {

    the problem is that it does not error and Pod start, this is a bug we can not have, if you don't get the things in the Pod that Pod can not run ... unfortunately is hard to change this in NRI today, but people running in production expect the Pod when is running to be fully operational

    aojea aojea commented on Oct 15, 2026 21:09 UTC
    Author

    we should fix this in https://github.com/containerd/nri/pull/329 , this solution is racy and hacky

    aojea aojea commented on Oct 16, 2026 14:39 UTC
    Author

    /hold

    kubernetes-prow[bot] kubernetes-prow[bot] commented on Oct 25, 2026 22:01 UTC
    Bot

    PR needs rebase.

    <details>

    Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
    </details>

    aojea aojea commented on Oct 27, 2026 20:22 UTC
    Author

    I will break this down in pieces now that we have https://github.com/kubernetes-sigs/dranet/pull/401 to solve it natively

    /close

    Reviewers
    Assignees
    aojea aojea
    Labels
    risk: low confidence: 85.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.3% · Lower = rushed or shallow review
    85.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 12.6% · Safe to merge
    12.6%