← Back to Pull requests

[TAS][Webhook 2/2] Deliver node labels to Ray workers through admission webhooks #5300

Merged
martinlhw merged 43 files (1747 lines) on Oct 16, 2026 03:21 UTC
View on GitHub
martinlhw martinlhw commented on Sep 16, 2026 20:19 UTC
Author

<!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. -->

Why are these changes needed?


This is the second and last PR of the series adding device-agnostic node label delivery webhook. #5260 added the API: workerGroupSpecs[].labelRefs and the allowedNodeLabels operator config; this PR adds the delivery. Each worker pod receives the actual labels that are attainable in the kubernetes node after it's bound to. The feature is behind the alpha NodeLabelDelivery. gate and requires the operator to run with webhooks (ENABLE_WEBHOOKS).

What this PR adds


1. labelRefs validation in the existing validating webhooks, rejecting invalid worker groups at apply time. Rules in validateLabelRefs, each shown with its message in the rejection table below.
2. Reconciler checks rejecting labelRefs when the operator cannot deliver them. Rules in ValidateRayClusterSpec.
3. Two mutating webhooks. At pod CREATE, the worker's generated ray start is wrapped to read RAY_NODE_LABELS_JSON from the pod annotation ray.io/node-labels and pass it as --labels-file. At pod binding, the bound node's referenced labels are written into that annotation; if any is missing, nothing is delivered, a RequiredNodeLabelMissing event is recorded, and the container exits before ray start.
4. RBAC nodes get. Kustomize webhook manifests and the objectSelector patch. Helm support behind webhooks.enabled.

Related issue number


N/A
<!-- For example: "Closes #1234" -->

Labels

<!-- Please add the appropriate labels to this PR. -->

  • If this PR has user-facing changes that require documentation updates at release time, I have added the doc-updates-required label.

  • If this PR contains breaking changes, I have added the breaking-change label.
  • Checks

  • I've made sure the tests are passing.

  • Testing Strategy

  • - [x] Unit tests
    - [x] Manual tests
    - [ ] This PR is not tested :(

    <!-- If you selected "Manual tests" above, please fill in the section below. Otherwise you can remove it. -->

    Manual test instructions

    Summary: On a kind cluster with labeled nodes: a worker with labelRefs gets its node's labels as Ray node labels, a worker on a node missing a label is withheld with an event, admission rejects bad specs, other pods are untouched.

    1. Cluster, cert-manager, labeled nodes, operator with webhooks, allowlist and the gate on

    cat > kind-tas.yaml <<'EOF'
    kind: Cluster
    apiVersion: kind.x-k8s.io/v1alpha4
    nodes: [{role: control-plane}, {role: worker}, {role: worker}, {role: worker}]
    EOF
    kind create cluster --name tas --config kind-tas.yaml
    kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.17.2/cert-manager.yaml
    kubectl -n cert-manager wait deploy --all --for=condition=Available --timeout=180s
    
    kubectl label node tas-worker  nvidia.com/gpu.clique=rack-a.0 topology.kubernetes.io/zone=zone-1
    kubectl label node tas-worker2 nvidia.com/gpu.clique=rack-b.0 topology.kubernetes.io/zone=zone-1
    kubectl label node tas-worker3 topology.kubernetes.io/zone=zone-1   # no clique, on purpose
    
    cd ray-operator && make docker-image IMG=kuberay/operator:tas && kind load docker-image kuberay/operator:tas --name tas
    cat > tas-values.yaml <<'EOF'
    image: {repository: kuberay/operator, tag: tas}
    webhooks: {enabled: true}
    configuration:
      enabled: true
      allowedNodeLabels: [nvidia.com/gpu.clique, topology.kubernetes.io/zone]
    featureGates:   # replaces the chart's default list, other gates keep their built-in defaults
    - {name: NodeLabelDelivery, enabled: true}
    EOF
    helm install kuberay-operator ../helm-chart/kuberay-operator -n ray-system --create-namespace -f tas-values.yaml
    kubectl -n ray-system rollout status deploy/kuberay-operator
    

    2. Happy path. train delivers the clique as ray.io/accelerator-domain and the zone under its own key, one worker per clique node. plain has no labelRefs.

    kubectl apply -f - <<'EOF'
    apiVersion: ray.io/v1
    kind: RayCluster
    metadata: {name: topo}
    spec:
      rayVersion: "2.49.0"
      headGroupSpec:
        template: {spec: {containers: [{name: ray-head, image: rayproject/ray:2.49.0}]}}
      workerGroupSpecs:
      - groupName: train
        replicas: 2
        minReplicas: 2
        maxReplicas: 2
        labelRefs:
        - name: ray.io/accelerator-domain
          valueFrom:
            nodeRef:
              fieldPath: metadata.labels['nvidia.com/gpu.clique']
        - valueFrom:
            nodeRef:
              fieldPath: metadata.labels['topology.kubernetes.io/zone']
        template:
          spec:
            affinity:
              nodeAffinity: {requiredDuringSchedulingIgnoredDuringExecution: {nodeSelectorTerms: [{matchExpressions: [{key: nvidia.com/gpu.clique, operator: Exists}]}]}}
              podAntiAffinity: {requiredDuringSchedulingIgnoredDuringExecution: [{labelSelector: {matchLabels: {ray.io/group: train}}, topologyKey: kubernetes.io/hostname}]}
            containers: [{name: ray-worker, image: rayproject/ray:2.49.0}]
      - groupName: plain
        replicas: 1
        minReplicas: 1
        maxReplicas: 1
        template: {spec: {containers: [{name: ray-worker, image: rayproject/ray:2.49.0}]}}
    EOF
    kubectl wait pod -l ray.io/cluster=topo --for=condition=Ready --timeout=300s
    
    # annotation delivered at bind equals the node's labels
    for p in $(kubectl get pod -l ray.io/group=train -o name); do
      kubectl get $p -o jsonpath='{.spec.nodeName}  {.metadata.annotations.ray\.io/node-labels}{"\n"}'
    done
    #  tas-worker   {"ray.io/accelerator-domain":"rack-a.0","topology.kubernetes.io/zone":"zone-1"}
    #  tas-worker2  {"ray.io/accelerator-domain":"rack-b.0","topology.kubernetes.io/zone":"zone-1"}
    
    # Ray sees them as node labels; head and plain carry only ray.io/node-id and ray.io/node-group
    kubectl exec $(kubectl get pod -l ray.io/node-type=head -o name) -c ray-head -- \
      python -c "import ray, json; ray.init(address='auto', logging_level='ERROR'); print(json.dumps({n['NodeManagerAddress']: n.get('Labels') for n in ray.nodes()}, indent=1))"
    
    # plain worker untouched
    kubectl get $(kubectl get pod -l ray.io/group=plain -o name) -o jsonpath='{.spec.containers[0].env[?(@.name=="RAY_NODE_LABELS_JSON")].name}  {.metadata.annotations.ray\.io/node-labels}{"\n"}'   # empty
    

    3. Missing label is withheld. Same train group pinned to tas-worker3.

    kubectl apply -f - <<'EOF'
    apiVersion: ray.io/v1
    kind: RayCluster
    metadata: {name: topo-missing}
    spec:
      rayVersion: "2.49.0"
      headGroupSpec:
        template: {spec: {containers: [{name: ray-head, image: rayproject/ray:2.49.0}]}}
      workerGroupSpecs:
      - groupName: train
        replicas: 1
        minReplicas: 1
        maxReplicas: 1
        labelRefs:
        - name: ray.io/accelerator-domain
          valueFrom:
            nodeRef:
              fieldPath: metadata.labels['nvidia.com/gpu.clique']
        - valueFrom:
            nodeRef:
              fieldPath: metadata.labels['topology.kubernetes.io/zone']
        template:
          spec:
            nodeSelector: {kubernetes.io/hostname: tas-worker3}
            containers: [{name: ray-worker, image: rayproject/ray:2.49.0}]
    EOF
    sleep 60
    W=$(kubectl get pod -l ray.io/cluster=topo-missing,ray.io/group=train -o name)
    kubectl get $W -o jsonpath='{.status.containerStatuses[0].state.waiting.reason}  {.metadata.annotations.ray\.io/node-labels}{"\n"}'   # CrashLoopBackOff, no annotation
    kubectl logs $W -c ray-worker --previous | tail -1
    #  RAY_NODE_LABELS_JSON is empty: node labels were not delivered to this pod, see the pod events
    kubectl get events --field-selector reason=RequiredNodeLabelMissing -o custom-columns=MESSAGE:.message
    #  node labels not delivered for the binding to node tas-worker3: node lacks label "nvidia.com/gpu.clique"
    
    # recovery
    kubectl label node tas-worker3 nvidia.com/gpu.clique=rack-c.0 && kubectl delete $W
    kubectl wait pod -l ray.io/cluster=topo-missing --for=condition=Ready --timeout=300s
    kubectl get pod -l ray.io/cluster=topo-missing,ray.io/group=train -o jsonpath='{.items[0].metadata.annotations.ray\.io/node-labels}{"\n"}'
    #  {"ray.io/accelerator-domain":"rack-c.0","topology.kubernetes.io/zone":"zone-1"}
    

    4. Admission rejections. Apply topo again with --dry-run=server after each edit to the train group.

    | edit | error |
    |---|---|
    | fieldPath: metadata.labels['cloud.google.com/gke-nodepool'] | labelRefs[0].valueFrom.nodeRef.fieldPath: Forbidden: node label "cloud.google.com/gke-nodepool" is not in the operator's allowedNodeLabels |
    | fieldPath: metadata.annotations['topology.kubernetes.io/zone'] | labelRefs[1].valueFrom.nodeRef.fieldPath: Invalid value: ... only metadata.labels['<key>'] is supported |
    | fieldPath: metadata.labels['bad key!'] | labelRefs[1].valueFrom.nodeRef.fieldPath: Invalid value: "bad key!": name part must consist of alphanumeric characters, ... |
    | name: ray zone! | labelRefs[0].name: Invalid value: "ray zone!": ... |
    | both refs name: ray.io/zone | labelRefs[1]: Duplicate value: "ray.io/zone" |
    | labels: {ray.io/accelerator-domain: static} on the group | labelRefs[0]: Forbidden: Ray label "ray.io/accelerator-domain" is also set in labels; ... |
    | rayStartParams: {labels-file: /x.yaml} (or labels) | labelRefs: Forbidden: cannot be combined with rayStartParams labels-file |
    | env: [{name: RAY_NODE_LABELS_JSON, value: "{}"}] on the worker container | labelRefs: Forbidden: cannot be combined with the RAY_NODE_LABELS_JSON env var in the pod template; ... |
    | metadata.annotations: {ray.io/overwrite-container-cmd: "true"} on the RayCluster | labelRefs: Forbidden: cannot be combined with the ray.io/overwrite-container-cmd annotation; ... |
    | command: ["ray start --block"] on the worker container | labelRefs: Forbidden: cannot be combined with a container command that runs ray start; ... |
    | operator upgraded with --set 'featureGates[0].enabled=false' | labelRefs: Forbidden: requires the NodeLabelDelivery feature gate to be enabled; the chart also stops rendering the pod webhooks |

    Field paths are shown without the spec.workerGroupSpecs[0]. prefix.

    5. Non-worker pods are not affected

    kubectl run nginx --image=nginx --restart=Never && kubectl wait pod/nginx --for=condition=Ready --timeout=60s
    

    Diff: 1747 lines (+1708 / -39) across 43 files Reviewer: ryanaoleary Review duration: 42181m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.72) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 1747 lines diff across 43 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.87 · 5 substantive comment(s)
    0.87
    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
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    37 items
    cursor[bot] cursor[bot] commented on Sep 18, 2026 02:32 UTC
    Reviewer

    <!-- BUGBOT_REVIEW -->
    <!-- BUGBOT_REVIEW_STALE -->
    Stale Bugbot comment from a previous run.

    cursor[bot] cursor[bot] commented on code on Sep 18, 2026 02:32 UTC
    Code Review
    helm-chart/kuberay-operator/templates/_helpers.tpl:1
    @@ -175,6 +175,12 @@ Create a template to ensure consistency for Role and ClusterRole.
     */}}
     {{- define "role.consistentRules" -}}
     rules:
    +- apiGroups:
    +  - ""
    +  resources:
    +  - nodes
    +  verbs:
    +  - get

    Webhooks skip single-namespace install check

    Medium Severity

    <!-- DESCRIPTION START -->
    webhooks.enabled is documented as unsupported with singleNamespaceInstall, but unlike nodeEventForwarder the chart never fails that combination. Helm still writes cluster-scoped webhook configs and puts nodes get on the namespaced Role, which cannot grant Node access, so the binding webhook cannot read node labels and topology workers never receive them.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: 402d9755-a3a9-410d-a9d5-cf32630b895f -->

    <!-- LOCATIONS START
    helm-chart/kuberay-operator/templates/_helpers.tpl#L177-L183
    helm-chart/kuberay-operator/templates/webhooks.yaml#L1-L5
    LOCATIONS END -->
    <details>
    <summary>Additional Locations (1)</summary>

  • helm-chart/kuberay-operator/templates/webhooks.yaml#L1-L5
  • </details>

    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmMwMTUwMjAyLTNiNjEtNDYzMi05NTAwLTUzZDk4YzU2ZDM1ZCIsImVuY3J5cHRpb25LZXkiOiJqeDJDLUVqN3RIWTBvX250Nk9TSnpMeUZsTVVsTzRyS2c4ZW5nQWl1MlNRIiwiYnJhbmNoIjoibGFiZWwtcHJvcC13ZWJob29rIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmMwMTUwMjAyLTNiNjEtNDYzMi05NTAwLTUzZDk4YzU2ZDM1ZCIsImVuY3J5cHRpb25LZXkiOiJqeDJDLUVqN3RIWTBvX250Nk9TSnpMeUZsTVVsTzRyS2c4ZW5nQWl1MlNRIiwiYnJhbmNoIjoibGFiZWwtcHJvcC13ZWJob29rIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwck51bWJlciI6NTMwMCwiY29tbWl0U2hhIjoiOTVlZTdmYWJjYTg2MDM2ZDVlZmJkOGZiZjYzYjFiZTNmZjdmZjc2OCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit 95ee7fabca86036d5efbd8fbf63b1be3ff7ff768. Configure here.</sup>

    win5923 win5923 commented on code on Sep 23, 2026 01:47 UTC
    Code Review
    helm-chart/kuberay-operator/templates/_helpers.tpl:1
    @@ -175,6 +175,12 @@ Create a template to ensure consistency for Role and ClusterRole.
     */}}
     {{- define "role.consistentRules" -}}
     rules:
    +- apiGroups:
    +  - ""
    +  resources:
    +  - nodes
    +  verbs:
    +  - get

    I don't think we should support this for singleNamespaceInstall, since Nodes are cluster-scoped.

    Similar to line 149.

    win5923 win5923 commented on code on Sep 23, 2026 03:30 UTC
    Code Review
    helm-chart/kuberay-operator/values.yaml:1
    @@ -154,6 +154,13 @@ configuration:
       # - topology.kubernetes.io/zone
       allowedNodeLabels: []
     
    +# Admission webhooks: validating webhooks for RayCluster, RayJob and RayService, and the pod mutating webhooks
    +# that deliver node labels to Ray workers (workerGroupSpecs[].topology, TopologyLabelDelivery feature gate).
    +webhooks:
    +  # -- Deploy the admission webhooks. Requires cert-manager in the cluster for the serving certificate and CA
    +  # injection. Creates cluster-scoped webhook configurations, so it is not supported with singleNamespaceInstall.
    +  enabled: false

    I think cert-manager shouldn't be required, users can also provide their own certificates. We could expose more fields to let users configure the webhook service as well. I think we can treat this as a follow-up.

    win5923 win5923 commented on code on Sep 23, 2026 03:36 UTC
    Code Review
    helm-chart/kuberay-operator/templates/webhooks.yaml:1

    I think it would be better to put these resources under a dedicated directory and split them into multiple files rather than keeping everything in a single file.

    For example:

    admission-webhooks/
      service.yaml
      issuer.yaml
      certificate.yaml
      mutating-webhook.yaml
      validating-webhook.yaml
    

    This would make the webhook-related resources easier to find and maintain.

    Reference: https://github.com/kubernetes/ingress-nginx/tree/main/charts/ingress-nginx/templates/admission-webhooks

    win5923 win5923 commented on code on Sep 23, 2026 09:22 UTC
    Code Review
    ray-operator/main.go:1
    @@ -377,12 +377,17 @@ func main() {
     		"unable to create controller", "controller", "RayJob")
     
     	if os.Getenv("ENABLE_WEBHOOKS") == "true" {

    	if strings.ToLower(os.Getenv("ENABLE_WEBHOOKS")) == "true" {
    

    nit

    win5923 win5923 commented on code on Sep 23, 2026 10:04 UTC
    Code Review
    ray-operator/config/webhook/manifests.yaml:1
    @@ -1,5 +1,50 @@
     ---
     apiVersion: admissionregistration.k8s.io/v1
    +kind: MutatingWebhookConfiguration
    +metadata:
    +  name: mutating-webhook-configuration
    +webhooks:
    +- admissionReviewVersions:
    +  - v1
    +  clientConfig:
    +    service:
    +      name: webhook-service
    +      namespace: system
    +      path: /mutate-v1-pod
    +  failurePolicy: Fail
    +  name: mpod.kb.io
    +  rules:
    +  - apiGroups:
    +    - ""
    +    apiVersions:
    +    - v1
    +    operations:
    +    - CREATE
    +    resources:
    +    - pods
    +  sideEffects: None
    +- admissionReviewVersions:
    +  - v1
    +  clientConfig:
    +    service:
    +      name: webhook-service
    +      namespace: system
    +      path: /mutate-v1-pod-binding
    +  failurePolicy: Ignore

    Is there a reason we use Ignore here? If the binding webhook fails, the Pod will still be bound, but without the RAY_NODE_LABELS_JSON. It will eventually fail when the container starts, right?

    win5923 win5923 commented on code on Sep 23, 2026 10:16 UTC
    Code Review
    helm-chart/kuberay-operator/templates/webhooks.yaml:1
    @@ -0,0 +1,115 @@
    +{{- if .Values.webhooks.enabled }}
    +{{- $name := include "kuberay-operator.fullname" . }}
    +{{- $service := printf "%s-webhook" $name }}
    +{{- $cert := printf "%s-serving-cert" $name }}
    +apiVersion: v1
    +kind: Service
    +metadata:
    +  name: {{ $service }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  ports:
    +    - port: 443
    +      targetPort: webhook-server
    +      protocol: TCP
    +  selector:
    +    app.kubernetes.io/name: {{ include "kuberay-operator.name" . }}
    +    app.kubernetes.io/instance: {{ .Release.Name }}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Issuer
    +metadata:
    +  name: {{ $name }}-selfsigned-issuer
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  selfSigned: {}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Certificate
    +metadata:
    +  name: {{ $cert }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  dnsNames:
    +    - {{ $service }}.{{ .Release.Namespace }}.svc
    +    - {{ $service }}.{{ .Release.Namespace }}.svc.cluster.local
    +  issuerRef:
    +    kind: Issuer
    +    name: {{ $name }}-selfsigned-issuer
    +  secretName: {{ $name }}-webhook-server-cert
    +---
    +apiVersion: admissionregistration.k8s.io/v1
    +kind: MutatingWebhookConfiguration

    I think this is only needed for TopologyLabelDelivery. Maybe we can add if condition, to only render this when the TopologyLabelDelivery feature gate is enabled.

    win5923 win5923 commented on code on Sep 23, 2026 10:20 UTC
    Code Review
    helm-chart/kuberay-operator/templates/webhooks.yaml:1
    @@ -0,0 +1,115 @@
    +{{- if .Values.webhooks.enabled }}
    +{{- $name := include "kuberay-operator.fullname" . }}
    +{{- $service := printf "%s-webhook" $name }}
    +{{- $cert := printf "%s-serving-cert" $name }}
    +apiVersion: v1
    +kind: Service
    +metadata:
    +  name: {{ $service }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  ports:
    +    - port: 443
    +      targetPort: webhook-server
    +      protocol: TCP
    +  selector:
    +    app.kubernetes.io/name: {{ include "kuberay-operator.name" . }}
    +    app.kubernetes.io/instance: {{ .Release.Name }}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Issuer
    +metadata:
    +  name: {{ $name }}-selfsigned-issuer
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  selfSigned: {}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Certificate
    +metadata:
    +  name: {{ $cert }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  dnsNames:
    +    - {{ $service }}.{{ .Release.Namespace }}.svc
    +    - {{ $service }}.{{ .Release.Namespace }}.svc.cluster.local
    +  issuerRef:
    +    kind: Issuer
    +    name: {{ $name }}-selfsigned-issuer
    +  secretName: {{ $name }}-webhook-server-cert
    +---
    +apiVersion: admissionregistration.k8s.io/v1
    +kind: MutatingWebhookConfiguration
    +metadata:
    +  name: {{ $name }}-mutating-webhook-configuration
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +  annotations:
    +    cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ $cert }}
    +webhooks:
    +  # fails closed, so scoped to Ray node pods
    +  - name: mpod.kb.io
    +    admissionReviewVersions: ["v1"]
    +    clientConfig:
    +      service:
    +        name: {{ $service }}
    +        namespace: {{ .Release.Namespace }}
    +        path: /mutate-v1-pod
    +    failurePolicy: Fail
    +    objectSelector:
    +      matchLabels:
    +        ray.io/is-ray-node: "yes"

    Maybe use ray.io/node-type: worker instead? Since we only check the workerGroup.

    ryanaoleary ryanaoleary commented on code on Sep 25, 2026 23:39 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go:1
    @@ -0,0 +1,200 @@
    +package v1
    +
    +import (
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"net/http"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	"k8s.io/apimachinery/pkg/util/sets"
    +	"k8s.io/client-go/tools/events"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	logf "sigs.k8s.io/controller-runtime/pkg/log"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    +
    +	configapi "github.com/ray-project/kuberay/ray-operator/apis/config/v1alpha1"
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +	"github.com/ray-project/kuberay/ray-operator/pkg/features"
    +)
    +
    +// NodeLabelsWithheldReason is the reason of the Warning event recorded on a pod whose node labels were not delivered
    +const NodeLabelsWithheldReason = "RequiredNodeLabelMissing"
    +
    +var podBindingLog = logf.Log.WithName("pod-binding-webhook")
    +
    +//+kubebuilder:webhook:path=/mutate-v1-pod-binding,mutating=true,failurePolicy=ignore,sideEffects=NoneOnDryRun,groups="",resources=pods/binding,verbs=create,versions=v1,name=mpodbinding.kb.io,admissionReviewVersions=v1,timeoutSeconds=5
    +//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get
    +
    +// SetupPodBindingWebhookWithManager registers the pods/binding CREATE mutating webhook, which writes the bound node's
    +// mapped labels into the Binding annotations. The API server copies them onto the pod together with spec.nodeName.
    +func SetupPodBindingWebhookWithManager(mgr ctrl.Manager, config configapi.Configuration) error {
    +	mgr.GetWebhookServer().Register("/mutate-v1-pod-binding", &webhook.Admission{Handler: &PodBindingWebhook{
    +		Client:            mgr.GetClient(),
    +		APIReader:         mgr.GetAPIReader(),
    +		Recorder:          mgr.GetEventRecorder("kuberay-pod-binding-webhook"),
    +		Decoder:           admission.NewDecoder(mgr.GetScheme()),
    +		AllowedNodeLabels: sets.New(config.AllowedNodeLabels...),
    +	}})
    +	return nil
    +}
    +
    +type PodBindingWebhook struct {
    +	// Client reads pods and RayClusters from the manager cache
    +	Client client.Reader
    +	// APIReader reads pods the cache does not hold and node metadata from the API server
    +	APIReader client.Reader
    +	// Recorder emits the Warning event when labels are withheld, may be nil
    +	Recorder events.EventRecorder
    +	Decoder  admission.Decoder
    +	// AllowedNodeLabels is the operator allowlist for topology.labelMappings
    +	AllowedNodeLabels sets.Set[string]
    +}
    +
    +// Handle implements admission.Handler
    +func (w *PodBindingWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
    +	if !features.Enabled(features.TopologyLabelDelivery) {
    +		return admission.Allowed("TopologyLabelDelivery feature gate is disabled")
    +	}
    +	binding := &corev1.Binding{}
    +	if err := w.Decoder.Decode(req, binding); err != nil {
    +		return admission.Errored(http.StatusBadRequest, err)
    +	}
    +	if _, done := binding.Annotations[utils.RayTopologyLabelsAnnotationKey]; done {
    +		// already delivered e.g. on a webhook reinvocation
    +		return admission.Allowed("node labels already set on the binding")
    +	}
    +	nodeName := binding.Target.Name
    +	podName := req.Name
    +	if nodeName == "" {
    +		return admission.Allowed("binding has no pod or node name")
    +	}
    +	log := podBindingLog.WithValues("pod", req.Namespace+"/"+podName, "node", nodeName)
    +
    +	podMeta, err := w.getPodMetadata(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName})

    The informer cache only caches Ray pods with ray.io/node-type, so getPodMetadata will hit the API server (i.e. w.APIReader.Get(ctx, key, podMeta)) every time for non-Ray Pods. That amount of GET requests isn't very scalable, we should check the RayCluster informer cache using the bindings Pod name/namespace to see if there's a matching RayCluster with label mappings set - if not then we just pass-through.

    ryanaoleary ryanaoleary commented on code on Sep 25, 2026 23:51 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go:1
    @@ -0,0 +1,200 @@
    +package v1
    +
    +import (
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"net/http"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	"k8s.io/apimachinery/pkg/util/sets"
    +	"k8s.io/client-go/tools/events"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	logf "sigs.k8s.io/controller-runtime/pkg/log"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    +
    +	configapi "github.com/ray-project/kuberay/ray-operator/apis/config/v1alpha1"
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +	"github.com/ray-project/kuberay/ray-operator/pkg/features"
    +)
    +
    +// NodeLabelsWithheldReason is the reason of the Warning event recorded on a pod whose node labels were not delivered
    +const NodeLabelsWithheldReason = "RequiredNodeLabelMissing"
    +
    +var podBindingLog = logf.Log.WithName("pod-binding-webhook")
    +
    +//+kubebuilder:webhook:path=/mutate-v1-pod-binding,mutating=true,failurePolicy=ignore,sideEffects=NoneOnDryRun,groups="",resources=pods/binding,verbs=create,versions=v1,name=mpodbinding.kb.io,admissionReviewVersions=v1,timeoutSeconds=5
    +//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get
    +
    +// SetupPodBindingWebhookWithManager registers the pods/binding CREATE mutating webhook, which writes the bound node's
    +// mapped labels into the Binding annotations. The API server copies them onto the pod together with spec.nodeName.
    +func SetupPodBindingWebhookWithManager(mgr ctrl.Manager, config configapi.Configuration) error {
    +	mgr.GetWebhookServer().Register("/mutate-v1-pod-binding", &webhook.Admission{Handler: &PodBindingWebhook{
    +		Client:            mgr.GetClient(),
    +		APIReader:         mgr.GetAPIReader(),
    +		Recorder:          mgr.GetEventRecorder("kuberay-pod-binding-webhook"),
    +		Decoder:           admission.NewDecoder(mgr.GetScheme()),
    +		AllowedNodeLabels: sets.New(config.AllowedNodeLabels...),
    +	}})
    +	return nil
    +}
    +
    +type PodBindingWebhook struct {
    +	// Client reads pods and RayClusters from the manager cache
    +	Client client.Reader
    +	// APIReader reads pods the cache does not hold and node metadata from the API server
    +	APIReader client.Reader
    +	// Recorder emits the Warning event when labels are withheld, may be nil
    +	Recorder events.EventRecorder
    +	Decoder  admission.Decoder
    +	// AllowedNodeLabels is the operator allowlist for topology.labelMappings
    +	AllowedNodeLabels sets.Set[string]
    +}
    +
    +// Handle implements admission.Handler
    +func (w *PodBindingWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
    +	if !features.Enabled(features.TopologyLabelDelivery) {
    +		return admission.Allowed("TopologyLabelDelivery feature gate is disabled")
    +	}
    +	binding := &corev1.Binding{}
    +	if err := w.Decoder.Decode(req, binding); err != nil {
    +		return admission.Errored(http.StatusBadRequest, err)
    +	}
    +	if _, done := binding.Annotations[utils.RayTopologyLabelsAnnotationKey]; done {
    +		// already delivered e.g. on a webhook reinvocation
    +		return admission.Allowed("node labels already set on the binding")
    +	}
    +	nodeName := binding.Target.Name
    +	podName := req.Name
    +	if nodeName == "" {
    +		return admission.Allowed("binding has no pod or node name")
    +	}
    +	log := podBindingLog.WithValues("pod", req.Namespace+"/"+podName, "node", nodeName)
    +
    +	podMeta, err := w.getPodMetadata(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName})
    +	if err != nil {
    +		// a prepared pod exits at container start without the annotation, so admitting is still loud
    +		log.Error(err, "cannot read pod, admitting the binding without node labels")
    +		return admission.Allowed("pod lookup failed")
    +	}
    +	if podMeta == nil || podMeta.Labels[utils.RayClusterLabelKey] == "" || podMeta.Labels[utils.RayNodeTypeLabelKey] != string(rayv1.WorkerNode) {
    +		return admission.Allowed("not a Ray worker pod")
    +	}
    +
    +	labels, err := w.resolveNodeLabels(ctx, req.Namespace, podMeta, nodeName)
    +	if err != nil {
    +		w.withhold(req, podMeta, nodeName, err)
    +		return admission.Allowed("node labels withheld")
    +	}
    +	if labels == nil {
    +		return admission.Allowed("worker group does not set topology")
    +	}
    +	encoded, err := json.Marshal(labels)
    +	if err != nil {
    +		return admission.Errored(http.StatusInternalServerError, err)
    +	}
    +	if binding.Annotations == nil {
    +		binding.Annotations = map[string]string{}
    +	}
    +	binding.Annotations[utils.RayTopologyLabelsAnnotationKey] = string(encoded)
    +	patched, err := json.Marshal(binding)
    +	if err != nil {
    +		return admission.Errored(http.StatusInternalServerError, err)
    +	}
    +	log.Info("delivering node labels", "labels", labels)
    +	return admission.PatchResponseFromRaw(req.Object.Raw, patched)
    +}
    +
    +// resolveNodeLabels returns the Ray labels to deliver, nil when the worker group has no label mappings
    +func (w *PodBindingWebhook) resolveNodeLabels(ctx context.Context, namespace string, podMeta *metav1.ObjectMeta, nodeName string) (map[string]string, error) {
    +	clusterName := podMeta.Labels[utils.RayClusterLabelKey]
    +	groupName := podMeta.Labels[utils.RayNodeGroupLabelKey]
    +	cluster := &rayv1.RayCluster{}
    +	if err := w.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, cluster); err != nil {
    +		return nil, fmt.Errorf("cannot read RayCluster %s: %w", clusterName, err)
    +	}
    +	group := findWorkerGroupSpec(&cluster.Spec, groupName)
    +	if group == nil {
    +		return nil, fmt.Errorf("worker group %s not found in RayCluster %s", groupName, clusterName)
    +	}
    +	if group.Topology == nil || len(group.Topology.LabelMappings) == 0 {
    +		return nil, nil
    +	}
    +	node := &metav1.PartialObjectMetadata{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Node"}}
    +	if err := w.APIReader.Get(ctx, types.NamespacedName{Name: nodeName}, node); err != nil {
    +		return nil, fmt.Errorf("cannot read node %s: %w", nodeName, err)
    +	}
    +	return buildTopologyLabels(node.Labels, group.Topology.LabelMappings, w.AllowedNodeLabels)
    +}
    +
    +// buildTopologyLabels maps node labels to Ray labels following the mappings. Every mapping must resolve to a
    +// non-empty allowlisted node label, otherwise the whole set fails
    +func buildTopologyLabels(nodeLabels map[string]string, mappings []rayv1.TopologyLabelMapping, allowed sets.Set[string]) (map[string]string, error) {
    +	labels := make(map[string]string, len(mappings))
    +	var errList []string
    +	for _, mapping := range mappings {
    +		value, ok := nodeLabels[mapping.NodeLabel]
    +		switch {
    +		case !allowed.Has(mapping.NodeLabel):
    +			errList = append(errList, fmt.Sprintf("node label %q is not in the operator's allowedNodeLabels", mapping.NodeLabel))
    +		case !ok:
    +			errList = append(errList, fmt.Sprintf("node lacks label %q", mapping.NodeLabel))
    +		case value == "":
    +			errList = append(errList, fmt.Sprintf("node label %q is empty", mapping.NodeLabel))

    is it correct to reject/error node labels withh empty values? is that ever a valid label

    martinlhw martinlhw commented on code on Oct 03, 2026 22:12 UTC
    Code Review
    helm-chart/kuberay-operator/templates/_helpers.tpl:1
    @@ -175,6 +175,12 @@ Create a template to ensure consistency for Role and ClusterRole.
     */}}
     {{- define "role.consistentRules" -}}
     rules:
    +- apiGroups:
    +  - ""
    +  resources:
    +  - nodes
    +  verbs:
    +  - get

    done

    martinlhw martinlhw commented on code on Oct 03, 2026 22:12 UTC
    Code Review
    helm-chart/kuberay-operator/values.yaml:1
    @@ -154,6 +154,13 @@ configuration:
       # - topology.kubernetes.io/zone
       allowedNodeLabels: []
     
    +# Admission webhooks: validating webhooks for RayCluster, RayJob and RayService, and the pod mutating webhooks
    +# that deliver node labels to Ray workers (workerGroupSpecs[].topology, TopologyLabelDelivery feature gate).
    +webhooks:
    +  # -- Deploy the admission webhooks. Requires cert-manager in the cluster for the serving certificate and CA
    +  # injection. Creates cluster-scoped webhook configurations, so it is not supported with singleNamespaceInstall.
    +  enabled: false

    sounds good

    martinlhw martinlhw commented on code on Oct 03, 2026 22:12 UTC
    Code Review
    helm-chart/kuberay-operator/templates/webhooks.yaml:1

    sounds good-- done

    martinlhw martinlhw commented on code on Oct 03, 2026 22:13 UTC
    Code Review
    ray-operator/main.go:1
    @@ -377,12 +377,17 @@ func main() {
     		"unable to create controller", "controller", "RayJob")
     
     	if os.Getenv("ENABLE_WEBHOOKS") == "true" {

    done

    cursor[bot] cursor[bot] commented on code on Oct 03, 2026 22:16 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go:1
    @@ -0,0 +1,205 @@
    +package v1
    +
    +import (
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"net/http"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	"k8s.io/apimachinery/pkg/util/sets"
    +	"k8s.io/client-go/tools/events"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	logf "sigs.k8s.io/controller-runtime/pkg/log"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    +
    +	configapi "github.com/ray-project/kuberay/ray-operator/apis/config/v1alpha1"
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +	"github.com/ray-project/kuberay/ray-operator/pkg/features"
    +)
    +
    +// NodeLabelsWithheldReason is the reason of the Warning event recorded on a pod whose node labels were not delivered
    +const NodeLabelsWithheldReason = "RequiredNodeLabelMissing"
    +
    +var podBindingLog = logf.Log.WithName("pod-binding-webhook")
    +
    +//+kubebuilder:webhook:path=/mutate-v1-pod-binding,mutating=true,failurePolicy=ignore,sideEffects=NoneOnDryRun,groups="",resources=pods/binding,verbs=create,versions=v1,name=mpodbinding.kb.io,admissionReviewVersions=v1,timeoutSeconds=5
    +//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get
    +
    +// SetupPodBindingWebhookWithManager registers the pods/binding CREATE mutating webhook, which writes the bound node's
    +// mapped labels into the Binding annotations. The API server copies them onto the pod together with spec.nodeName.
    +func SetupPodBindingWebhookWithManager(mgr ctrl.Manager, config configapi.Configuration) error {
    +	mgr.GetWebhookServer().Register("/mutate-v1-pod-binding", &webhook.Admission{Handler: &PodBindingWebhook{
    +		Client:            mgr.GetClient(),
    +		APIReader:         mgr.GetAPIReader(),
    +		Recorder:          mgr.GetEventRecorder("kuberay-pod-binding-webhook"),
    +		Decoder:           admission.NewDecoder(mgr.GetScheme()),
    +		AllowedNodeLabels: sets.New(config.AllowedNodeLabels...),
    +	}})
    +	return nil
    +}
    +
    +type PodBindingWebhook struct {
    +	// Client reads pods and RayClusters from the manager cache
    +	Client client.Reader
    +	// APIReader reads pods the cache does not hold and node metadata from the API server
    +	APIReader client.Reader
    +	// Recorder emits the Warning event when labels are withheld, may be nil
    +	Recorder events.EventRecorder
    +	Decoder  admission.Decoder
    +	// AllowedNodeLabels is the operator allowlist for labelRefs
    +	AllowedNodeLabels sets.Set[string]
    +}
    +
    +func (w *PodBindingWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
    +	if !features.Enabled(features.NodeLabelDelivery) {
    +		return admission.Allowed("NodeLabelDelivery feature gate is disabled")
    +	}
    +	binding := &corev1.Binding{}
    +	if err := w.Decoder.Decode(req, binding); err != nil {
    +		return admission.Errored(http.StatusBadRequest, err)
    +	}
    +	if _, done := binding.Annotations[utils.RayNodeLabelsAnnotationKey]; done {
    +		// already delivered e.g. on a webhook reinvocation
    +		return admission.Allowed("node labels already set on the binding")
    +	}
    +	nodeName := binding.Target.Name
    +	podName := req.Name
    +	if nodeName == "" {
    +		return admission.Allowed("binding has no target node")
    +	}
    +	log := podBindingLog.WithValues("pod", req.Namespace+"/"+podName, "node", nodeName)
    +
    +	cluster, group, err := w.labelRefsGroupForPod(ctx, req.Namespace, podName)
    +	if err != nil {
    +		log.Error(err, "cannot list RayClusters, admitting the binding without node labels")
    +		return admission.Allowed("RayCluster lookup failed")
    +	}
    +	if group == nil {
    +		return admission.Allowed("not a worker of a group with labelRefs")
    +	}
    +
    +	podMeta, err := w.getPodMetadata(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName})
    +	if err != nil {
    +		// a prepared pod exits at container start without the annotation, so admitting is still loud
    +		log.Error(err, "cannot read pod, admitting the binding without node labels")
    +		return admission.Allowed("pod lookup failed")
    +	}
    +	if podMeta == nil || podMeta.Labels[utils.RayClusterLabelKey] != cluster.Name || podMeta.Labels[utils.RayNodeGroupLabelKey] != group.GroupName {
    +		return admission.Allowed("not a worker of the matched group")
    +	}

    Prefix match can drop node labels

    Medium Severity

    <!-- DESCRIPTION START -->
    labelRefsGroupForPod returns the first RayCluster/worker group whose generated name prefix matches the pod, and a later label mismatch admits the binding with no labels and no RequiredNodeLabelMissing event. Distinct cluster/group pairs can share that prefix, including common names such as cluster prod group ray-gpu versus cluster prod-ray group gpu, or long names truncated by PodName. The create webhook still prepares those workers, so they exit before ray start and crash-loop.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: 7f852993-c3e1-4875-baf6-02e8494b9cd1 -->

    <!-- LOCATIONS START
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go#L95-L98
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go#L125-L141
    LOCATIONS END -->
    <details>
    <summary>Additional Locations (1)</summary>

  • ray-operator/pkg/webhooks/v1/pod_binding_webhook.go#L125-L141
  • </details>

    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIzZDQ1YjM0LTQzMGItNDRiNC1hOTkyLTk4ODMyZDQwMTMyOSIsImVuY3J5cHRpb25LZXkiOiJMMWl5dTVfLXByd3AxcG5WNHI2RlVnUEhHVWlBWXBuWlVYeFd6dmdIRnl3IiwiYnJhbmNoIjoibGFiZWwtcHJvcC13ZWJob29rIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjIzZDQ1YjM0LTQzMGItNDRiNC1hOTkyLTk4ODMyZDQwMTMyOSIsImVuY3J5cHRpb25LZXkiOiJMMWl5dTVfLXByd3AxcG5WNHI2RlVnUEhHVWlBWXBuWlVYeFd6dmdIRnl3IiwiYnJhbmNoIjoibGFiZWwtcHJvcC13ZWJob29rIiwicmVwb093bmVyIjoicmF5LXByb2plY3QiLCJyZXBvTmFtZSI6Imt1YmVyYXkiLCJwck51bWJlciI6NTMwMCwiY29tbWl0U2hhIjoiMTIyNGViZjNhOTdjMjYxNWU3ODMyODM2ZjkwYzk0NTZmMDNhYzE1NiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit 1224ebf3a97c2615e7832836f90c9456f03ac156. Configure here.</sup>

    cursor[bot] cursor[bot] commented on Oct 03, 2026 22:16 UTC
    Reviewer

    <!-- BUGBOT_REVIEW -->
    <!-- BUGBOT_REVIEW_STALE -->
    Stale Bugbot comment from a previous run.

    martinlhw martinlhw commented on code on Oct 03, 2026 22:26 UTC
    Code Review
    ray-operator/config/webhook/manifests.yaml:1
    @@ -1,5 +1,50 @@
     ---
     apiVersion: admissionregistration.k8s.io/v1
    +kind: MutatingWebhookConfiguration
    +metadata:
    +  name: mutating-webhook-configuration
    +webhooks:
    +- admissionReviewVersions:
    +  - v1
    +  clientConfig:
    +    service:
    +      name: webhook-service
    +      namespace: system
    +      path: /mutate-v1-pod
    +  failurePolicy: Fail
    +  name: mpod.kb.io
    +  rules:
    +  - apiGroups:
    +    - ""
    +    apiVersions:
    +    - v1
    +    operations:
    +    - CREATE
    +    resources:
    +    - pods
    +  sideEffects: None
    +- admissionReviewVersions:
    +  - v1
    +  clientConfig:
    +    service:
    +      name: webhook-service
    +      namespace: system
    +      path: /mutate-v1-pod-binding
    +  failurePolicy: Ignore

    This webhook intercepts every pods/binding in the cluster. As such, with Fail, any operator outage, even a rollout, rejects every bindings in the cluster until it is recovered. On the other hand, with Ignore, only the workers that needed labels are affected: they bind without the annotation, exit before ray start, and get a RequiredNodeLabelMissing event.

    martinlhw martinlhw commented on code on Oct 03, 2026 22:27 UTC
    Code Review
    helm-chart/kuberay-operator/templates/webhooks.yaml:1
    @@ -0,0 +1,115 @@
    +{{- if .Values.webhooks.enabled }}
    +{{- $name := include "kuberay-operator.fullname" . }}
    +{{- $service := printf "%s-webhook" $name }}
    +{{- $cert := printf "%s-serving-cert" $name }}
    +apiVersion: v1
    +kind: Service
    +metadata:
    +  name: {{ $service }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  ports:
    +    - port: 443
    +      targetPort: webhook-server
    +      protocol: TCP
    +  selector:
    +    app.kubernetes.io/name: {{ include "kuberay-operator.name" . }}
    +    app.kubernetes.io/instance: {{ .Release.Name }}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Issuer
    +metadata:
    +  name: {{ $name }}-selfsigned-issuer
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  selfSigned: {}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Certificate
    +metadata:
    +  name: {{ $cert }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  dnsNames:
    +    - {{ $service }}.{{ .Release.Namespace }}.svc
    +    - {{ $service }}.{{ .Release.Namespace }}.svc.cluster.local
    +  issuerRef:
    +    kind: Issuer
    +    name: {{ $name }}-selfsigned-issuer
    +  secretName: {{ $name }}-webhook-server-cert
    +---
    +apiVersion: admissionregistration.k8s.io/v1
    +kind: MutatingWebhookConfiguration

    done

    martinlhw martinlhw commented on code on Oct 03, 2026 22:27 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go:1
    @@ -0,0 +1,200 @@
    +package v1
    +
    +import (
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"net/http"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	"k8s.io/apimachinery/pkg/util/sets"
    +	"k8s.io/client-go/tools/events"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	logf "sigs.k8s.io/controller-runtime/pkg/log"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    +
    +	configapi "github.com/ray-project/kuberay/ray-operator/apis/config/v1alpha1"
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +	"github.com/ray-project/kuberay/ray-operator/pkg/features"
    +)
    +
    +// NodeLabelsWithheldReason is the reason of the Warning event recorded on a pod whose node labels were not delivered
    +const NodeLabelsWithheldReason = "RequiredNodeLabelMissing"
    +
    +var podBindingLog = logf.Log.WithName("pod-binding-webhook")
    +
    +//+kubebuilder:webhook:path=/mutate-v1-pod-binding,mutating=true,failurePolicy=ignore,sideEffects=NoneOnDryRun,groups="",resources=pods/binding,verbs=create,versions=v1,name=mpodbinding.kb.io,admissionReviewVersions=v1,timeoutSeconds=5
    +//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get
    +
    +// SetupPodBindingWebhookWithManager registers the pods/binding CREATE mutating webhook, which writes the bound node's
    +// mapped labels into the Binding annotations. The API server copies them onto the pod together with spec.nodeName.
    +func SetupPodBindingWebhookWithManager(mgr ctrl.Manager, config configapi.Configuration) error {
    +	mgr.GetWebhookServer().Register("/mutate-v1-pod-binding", &webhook.Admission{Handler: &PodBindingWebhook{
    +		Client:            mgr.GetClient(),
    +		APIReader:         mgr.GetAPIReader(),
    +		Recorder:          mgr.GetEventRecorder("kuberay-pod-binding-webhook"),
    +		Decoder:           admission.NewDecoder(mgr.GetScheme()),
    +		AllowedNodeLabels: sets.New(config.AllowedNodeLabels...),
    +	}})
    +	return nil
    +}
    +
    +type PodBindingWebhook struct {
    +	// Client reads pods and RayClusters from the manager cache
    +	Client client.Reader
    +	// APIReader reads pods the cache does not hold and node metadata from the API server
    +	APIReader client.Reader
    +	// Recorder emits the Warning event when labels are withheld, may be nil
    +	Recorder events.EventRecorder
    +	Decoder  admission.Decoder
    +	// AllowedNodeLabels is the operator allowlist for topology.labelMappings
    +	AllowedNodeLabels sets.Set[string]
    +}
    +
    +// Handle implements admission.Handler
    +func (w *PodBindingWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
    +	if !features.Enabled(features.TopologyLabelDelivery) {
    +		return admission.Allowed("TopologyLabelDelivery feature gate is disabled")
    +	}
    +	binding := &corev1.Binding{}
    +	if err := w.Decoder.Decode(req, binding); err != nil {
    +		return admission.Errored(http.StatusBadRequest, err)
    +	}
    +	if _, done := binding.Annotations[utils.RayTopologyLabelsAnnotationKey]; done {
    +		// already delivered e.g. on a webhook reinvocation
    +		return admission.Allowed("node labels already set on the binding")
    +	}
    +	nodeName := binding.Target.Name
    +	podName := req.Name
    +	if nodeName == "" {
    +		return admission.Allowed("binding has no pod or node name")
    +	}
    +	log := podBindingLog.WithValues("pod", req.Namespace+"/"+podName, "node", nodeName)
    +
    +	podMeta, err := w.getPodMetadata(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName})

    good point-- done

    martinlhw martinlhw commented on code on Oct 03, 2026 22:28 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go:1
    @@ -0,0 +1,200 @@
    +package v1
    +
    +import (
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"net/http"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	"k8s.io/apimachinery/pkg/util/sets"
    +	"k8s.io/client-go/tools/events"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	logf "sigs.k8s.io/controller-runtime/pkg/log"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    +
    +	configapi "github.com/ray-project/kuberay/ray-operator/apis/config/v1alpha1"
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +	"github.com/ray-project/kuberay/ray-operator/pkg/features"
    +)
    +
    +// NodeLabelsWithheldReason is the reason of the Warning event recorded on a pod whose node labels were not delivered
    +const NodeLabelsWithheldReason = "RequiredNodeLabelMissing"
    +
    +var podBindingLog = logf.Log.WithName("pod-binding-webhook")
    +
    +//+kubebuilder:webhook:path=/mutate-v1-pod-binding,mutating=true,failurePolicy=ignore,sideEffects=NoneOnDryRun,groups="",resources=pods/binding,verbs=create,versions=v1,name=mpodbinding.kb.io,admissionReviewVersions=v1,timeoutSeconds=5
    +//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get
    +
    +// SetupPodBindingWebhookWithManager registers the pods/binding CREATE mutating webhook, which writes the bound node's
    +// mapped labels into the Binding annotations. The API server copies them onto the pod together with spec.nodeName.
    +func SetupPodBindingWebhookWithManager(mgr ctrl.Manager, config configapi.Configuration) error {
    +	mgr.GetWebhookServer().Register("/mutate-v1-pod-binding", &webhook.Admission{Handler: &PodBindingWebhook{
    +		Client:            mgr.GetClient(),
    +		APIReader:         mgr.GetAPIReader(),
    +		Recorder:          mgr.GetEventRecorder("kuberay-pod-binding-webhook"),
    +		Decoder:           admission.NewDecoder(mgr.GetScheme()),
    +		AllowedNodeLabels: sets.New(config.AllowedNodeLabels...),
    +	}})
    +	return nil
    +}
    +
    +type PodBindingWebhook struct {
    +	// Client reads pods and RayClusters from the manager cache
    +	Client client.Reader
    +	// APIReader reads pods the cache does not hold and node metadata from the API server
    +	APIReader client.Reader
    +	// Recorder emits the Warning event when labels are withheld, may be nil
    +	Recorder events.EventRecorder
    +	Decoder  admission.Decoder
    +	// AllowedNodeLabels is the operator allowlist for topology.labelMappings
    +	AllowedNodeLabels sets.Set[string]
    +}
    +
    +// Handle implements admission.Handler
    +func (w *PodBindingWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
    +	if !features.Enabled(features.TopologyLabelDelivery) {
    +		return admission.Allowed("TopologyLabelDelivery feature gate is disabled")
    +	}
    +	binding := &corev1.Binding{}
    +	if err := w.Decoder.Decode(req, binding); err != nil {
    +		return admission.Errored(http.StatusBadRequest, err)
    +	}
    +	if _, done := binding.Annotations[utils.RayTopologyLabelsAnnotationKey]; done {
    +		// already delivered e.g. on a webhook reinvocation
    +		return admission.Allowed("node labels already set on the binding")
    +	}
    +	nodeName := binding.Target.Name
    +	podName := req.Name
    +	if nodeName == "" {
    +		return admission.Allowed("binding has no pod or node name")
    +	}
    +	log := podBindingLog.WithValues("pod", req.Namespace+"/"+podName, "node", nodeName)
    +
    +	podMeta, err := w.getPodMetadata(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName})
    +	if err != nil {
    +		// a prepared pod exits at container start without the annotation, so admitting is still loud
    +		log.Error(err, "cannot read pod, admitting the binding without node labels")
    +		return admission.Allowed("pod lookup failed")
    +	}
    +	if podMeta == nil || podMeta.Labels[utils.RayClusterLabelKey] == "" || podMeta.Labels[utils.RayNodeTypeLabelKey] != string(rayv1.WorkerNode) {
    +		return admission.Allowed("not a Ray worker pod")
    +	}
    +
    +	labels, err := w.resolveNodeLabels(ctx, req.Namespace, podMeta, nodeName)
    +	if err != nil {
    +		w.withhold(req, podMeta, nodeName, err)
    +		return admission.Allowed("node labels withheld")
    +	}
    +	if labels == nil {
    +		return admission.Allowed("worker group does not set topology")
    +	}
    +	encoded, err := json.Marshal(labels)
    +	if err != nil {
    +		return admission.Errored(http.StatusInternalServerError, err)
    +	}
    +	if binding.Annotations == nil {
    +		binding.Annotations = map[string]string{}
    +	}
    +	binding.Annotations[utils.RayTopologyLabelsAnnotationKey] = string(encoded)
    +	patched, err := json.Marshal(binding)
    +	if err != nil {
    +		return admission.Errored(http.StatusInternalServerError, err)
    +	}
    +	log.Info("delivering node labels", "labels", labels)
    +	return admission.PatchResponseFromRaw(req.Object.Raw, patched)
    +}
    +
    +// resolveNodeLabels returns the Ray labels to deliver, nil when the worker group has no label mappings
    +func (w *PodBindingWebhook) resolveNodeLabels(ctx context.Context, namespace string, podMeta *metav1.ObjectMeta, nodeName string) (map[string]string, error) {
    +	clusterName := podMeta.Labels[utils.RayClusterLabelKey]
    +	groupName := podMeta.Labels[utils.RayNodeGroupLabelKey]
    +	cluster := &rayv1.RayCluster{}
    +	if err := w.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, cluster); err != nil {
    +		return nil, fmt.Errorf("cannot read RayCluster %s: %w", clusterName, err)
    +	}
    +	group := findWorkerGroupSpec(&cluster.Spec, groupName)
    +	if group == nil {
    +		return nil, fmt.Errorf("worker group %s not found in RayCluster %s", groupName, clusterName)
    +	}
    +	if group.Topology == nil || len(group.Topology.LabelMappings) == 0 {
    +		return nil, nil
    +	}
    +	node := &metav1.PartialObjectMetadata{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Node"}}
    +	if err := w.APIReader.Get(ctx, types.NamespacedName{Name: nodeName}, node); err != nil {
    +		return nil, fmt.Errorf("cannot read node %s: %w", nodeName, err)
    +	}
    +	return buildTopologyLabels(node.Labels, group.Topology.LabelMappings, w.AllowedNodeLabels)
    +}
    +
    +// buildTopologyLabels maps node labels to Ray labels following the mappings. Every mapping must resolve to a
    +// non-empty allowlisted node label, otherwise the whole set fails
    +func buildTopologyLabels(nodeLabels map[string]string, mappings []rayv1.TopologyLabelMapping, allowed sets.Set[string]) (map[string]string, error) {
    +	labels := make(map[string]string, len(mappings))
    +	var errList []string
    +	for _, mapping := range mappings {
    +		value, ok := nodeLabels[mapping.NodeLabel]
    +		switch {
    +		case !allowed.Has(mapping.NodeLabel):
    +			errList = append(errList, fmt.Sprintf("node label %q is not in the operator's allowedNodeLabels", mapping.NodeLabel))
    +		case !ok:
    +			errList = append(errList, fmt.Sprintf("node lacks label %q", mapping.NodeLabel))
    +		case value == "":
    +			errList = append(errList, fmt.Sprintf("node label %q is empty", mapping.NodeLabel))

    ah good catch-- dropped this check

    martinlhw martinlhw commented on code on Oct 03, 2026 22:42 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/pod_binding_webhook.go:1
    @@ -0,0 +1,205 @@
    +package v1
    +
    +import (
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"net/http"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	apierrors "k8s.io/apimachinery/pkg/api/errors"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/types"
    +	"k8s.io/apimachinery/pkg/util/sets"
    +	"k8s.io/client-go/tools/events"
    +	ctrl "sigs.k8s.io/controller-runtime"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +	logf "sigs.k8s.io/controller-runtime/pkg/log"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook"
    +	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    +
    +	configapi "github.com/ray-project/kuberay/ray-operator/apis/config/v1alpha1"
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +	"github.com/ray-project/kuberay/ray-operator/pkg/features"
    +)
    +
    +// NodeLabelsWithheldReason is the reason of the Warning event recorded on a pod whose node labels were not delivered
    +const NodeLabelsWithheldReason = "RequiredNodeLabelMissing"
    +
    +var podBindingLog = logf.Log.WithName("pod-binding-webhook")
    +
    +//+kubebuilder:webhook:path=/mutate-v1-pod-binding,mutating=true,failurePolicy=ignore,sideEffects=NoneOnDryRun,groups="",resources=pods/binding,verbs=create,versions=v1,name=mpodbinding.kb.io,admissionReviewVersions=v1,timeoutSeconds=5
    +//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get
    +
    +// SetupPodBindingWebhookWithManager registers the pods/binding CREATE mutating webhook, which writes the bound node's
    +// mapped labels into the Binding annotations. The API server copies them onto the pod together with spec.nodeName.
    +func SetupPodBindingWebhookWithManager(mgr ctrl.Manager, config configapi.Configuration) error {
    +	mgr.GetWebhookServer().Register("/mutate-v1-pod-binding", &webhook.Admission{Handler: &PodBindingWebhook{
    +		Client:            mgr.GetClient(),
    +		APIReader:         mgr.GetAPIReader(),
    +		Recorder:          mgr.GetEventRecorder("kuberay-pod-binding-webhook"),
    +		Decoder:           admission.NewDecoder(mgr.GetScheme()),
    +		AllowedNodeLabels: sets.New(config.AllowedNodeLabels...),
    +	}})
    +	return nil
    +}
    +
    +type PodBindingWebhook struct {
    +	// Client reads pods and RayClusters from the manager cache
    +	Client client.Reader
    +	// APIReader reads pods the cache does not hold and node metadata from the API server
    +	APIReader client.Reader
    +	// Recorder emits the Warning event when labels are withheld, may be nil
    +	Recorder events.EventRecorder
    +	Decoder  admission.Decoder
    +	// AllowedNodeLabels is the operator allowlist for labelRefs
    +	AllowedNodeLabels sets.Set[string]
    +}
    +
    +func (w *PodBindingWebhook) Handle(ctx context.Context, req admission.Request) admission.Response {
    +	if !features.Enabled(features.NodeLabelDelivery) {
    +		return admission.Allowed("NodeLabelDelivery feature gate is disabled")
    +	}
    +	binding := &corev1.Binding{}
    +	if err := w.Decoder.Decode(req, binding); err != nil {
    +		return admission.Errored(http.StatusBadRequest, err)
    +	}
    +	if _, done := binding.Annotations[utils.RayNodeLabelsAnnotationKey]; done {
    +		// already delivered e.g. on a webhook reinvocation
    +		return admission.Allowed("node labels already set on the binding")
    +	}
    +	nodeName := binding.Target.Name
    +	podName := req.Name
    +	if nodeName == "" {
    +		return admission.Allowed("binding has no target node")
    +	}
    +	log := podBindingLog.WithValues("pod", req.Namespace+"/"+podName, "node", nodeName)
    +
    +	cluster, group, err := w.labelRefsGroupForPod(ctx, req.Namespace, podName)
    +	if err != nil {
    +		log.Error(err, "cannot list RayClusters, admitting the binding without node labels")
    +		return admission.Allowed("RayCluster lookup failed")
    +	}
    +	if group == nil {
    +		return admission.Allowed("not a worker of a group with labelRefs")
    +	}
    +
    +	podMeta, err := w.getPodMetadata(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName})
    +	if err != nil {
    +		// a prepared pod exits at container start without the annotation, so admitting is still loud
    +		log.Error(err, "cannot read pod, admitting the binding without node labels")
    +		return admission.Allowed("pod lookup failed")
    +	}
    +	if podMeta == nil || podMeta.Labels[utils.RayClusterLabelKey] != cluster.Name || podMeta.Labels[utils.RayNodeGroupLabelKey] != group.GroupName {
    +		return admission.Allowed("not a worker of the matched group")
    +	}

    fixed

    ryanaoleary ryanaoleary commented on code on Oct 06, 2026 19:27 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/label_refs_validation.go:1
    @@ -0,0 +1,77 @@
    +package v1
    +
    +import (
    +	"fmt"
    +	"slices"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	"k8s.io/apimachinery/pkg/util/validation/field"
    +
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +)
    +
    +// validateLabelRefs checks the labelRefs of every worker group in spec against the operator allowlist.
    +// annotations are the admitted object's metadata annotations, base is the field path of spec in that object
    +func validateLabelRefs(spec *rayv1.RayClusterSpec, annotations map[string]string, allowed []string, base *field.Path) *field.Error {
    +	for i := range spec.WorkerGroupSpecs {
    +		group := &spec.WorkerGroupSpecs[i]
    +		if len(group.LabelRefs) == 0 {
    +			continue
    +		}
    +		path := base.Child("workerGroupSpecs").Index(i).Child("labelRefs")
    +
    +		// node label delivery rewrites the KubeRay-generated ray start command, so the user must not replace it.
    +		// the annotation is read from the CR metadata and copied onto the pod template, so check both
    +		if overwritesContainerCmd(annotations) || overwritesContainerCmd(group.Template.Annotations) {
    +			return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s annotation; node label delivery needs the KubeRay-generated ray start command", utils.RayOverwriteContainerCmdAnnotationKey))
    +		}
    +		if len(group.Template.Spec.Containers) > utils.RayContainerIndex {
    +			container := group.Template.Spec.Containers[utils.RayContainerIndex]
    +			if strings.Contains(strings.Join(container.Command, " ")+" "+strings.Join(container.Args, " "), "ray start") {
    +				return field.Forbidden(path, "cannot be combined with a container command that runs ray start; node label delivery needs the KubeRay-generated ray start command")
    +			}
    +			if slices.ContainsFunc(container.Env, func(e corev1.EnvVar) bool { return e.Name == utils.RAY_NODE_LABELS_JSON }) {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s env var in the pod template; it is managed by KubeRay", utils.RAY_NODE_LABELS_JSON))
    +			}
    +		}
    +		// node label delivery passes --labels-file itself, and --labels would override the delivered keys
    +		for _, param := range []string{"labels", "labels-file"} {
    +			if _, ok := group.RayStartParams[param]; ok {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with rayStartParams %s", param))
    +			}
    +		}
    +		// check for duplicate label keys
    +		seen := make(map[string]bool, len(group.LabelRefs))
    +		for j, ref := range group.LabelRefs {
    +			refPath := path.Index(j)
    +			fieldPath := ref.ValueFrom.NodeRef.FieldPath
    +			nodeLabel, err := utils.NodeLabelKey(fieldPath)

    Should we check like IsQualifiedName or anything for the Ray or node label here? There is validation for the Ray label that will fail at runtime, but wondering if we should check anything here (i.e. disallowed chars included, must be valid k8s format, etc.) to fail fast

    ryanaoleary ryanaoleary commented on code on Oct 06, 2026 19:29 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/rayservice_webhook.go:1
    @@ -53,6 +57,10 @@ func (w *RayServiceWebhook) validateRayService(rayService *rayv1.RayService) err
     		allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("name"), rayService.Name, err.Error()))
     	}
     
    +	if err := validateLabelRefs(&rayService.Spec.RayClusterSpec, rayService.Annotations, w.AllowedNodeLabels, field.NewPath("spec").Child("rayClusterConfig")); err != nil {
    +		allErrs = append(allErrs, err)

    do we need to check features.Enabled(features.NodeLabelDelivery) here?

    ryanaoleary ryanaoleary commented on code on Oct 06, 2026 19:29 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/rayjob_webhook.go:1
    @@ -53,6 +57,12 @@ func (w *RayJobWebhook) validateRayJob(rayJob *rayv1.RayJob) error {
     		allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("name"), rayJob.Name, err.Error()))
     	}
     
    +	if rayJob.Spec.RayClusterSpec != nil {
    +		if err := validateLabelRefs(rayJob.Spec.RayClusterSpec, rayJob.Annotations, w.AllowedNodeLabels, field.NewPath("spec").Child("rayClusterSpec")); err != nil {

    same comment, should we check: features.Enabled(features.NodeLabelDelivery)

    martinlhw martinlhw commented on code on Oct 07, 2026 23:58 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/label_refs_validation.go:1
    @@ -0,0 +1,77 @@
    +package v1
    +
    +import (
    +	"fmt"
    +	"slices"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	"k8s.io/apimachinery/pkg/util/validation/field"
    +
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +)
    +
    +// validateLabelRefs checks the labelRefs of every worker group in spec against the operator allowlist.
    +// annotations are the admitted object's metadata annotations, base is the field path of spec in that object
    +func validateLabelRefs(spec *rayv1.RayClusterSpec, annotations map[string]string, allowed []string, base *field.Path) *field.Error {
    +	for i := range spec.WorkerGroupSpecs {
    +		group := &spec.WorkerGroupSpecs[i]
    +		if len(group.LabelRefs) == 0 {
    +			continue
    +		}
    +		path := base.Child("workerGroupSpecs").Index(i).Child("labelRefs")
    +
    +		// node label delivery rewrites the KubeRay-generated ray start command, so the user must not replace it.
    +		// the annotation is read from the CR metadata and copied onto the pod template, so check both
    +		if overwritesContainerCmd(annotations) || overwritesContainerCmd(group.Template.Annotations) {
    +			return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s annotation; node label delivery needs the KubeRay-generated ray start command", utils.RayOverwriteContainerCmdAnnotationKey))
    +		}
    +		if len(group.Template.Spec.Containers) > utils.RayContainerIndex {
    +			container := group.Template.Spec.Containers[utils.RayContainerIndex]
    +			if strings.Contains(strings.Join(container.Command, " ")+" "+strings.Join(container.Args, " "), "ray start") {
    +				return field.Forbidden(path, "cannot be combined with a container command that runs ray start; node label delivery needs the KubeRay-generated ray start command")
    +			}
    +			if slices.ContainsFunc(container.Env, func(e corev1.EnvVar) bool { return e.Name == utils.RAY_NODE_LABELS_JSON }) {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s env var in the pod template; it is managed by KubeRay", utils.RAY_NODE_LABELS_JSON))
    +			}
    +		}
    +		// node label delivery passes --labels-file itself, and --labels would override the delivered keys
    +		for _, param := range []string{"labels", "labels-file"} {
    +			if _, ok := group.RayStartParams[param]; ok {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with rayStartParams %s", param))
    +			}
    +		}
    +		// check for duplicate label keys
    +		seen := make(map[string]bool, len(group.LabelRefs))
    +		for j, ref := range group.LabelRefs {
    +			refPath := path.Index(j)
    +			fieldPath := ref.ValueFrom.NodeRef.FieldPath
    +			nodeLabel, err := utils.NodeLabelKey(fieldPath)

    The node label format is checked for the labels that gets written into allowedNodeLabels. Initially didn't have the check for Ray labels because I didn't see an issue with users setting whatever they want for ray labels. But if the ray start already enforce this, then it makes sense to add a check here.

    martinlhw martinlhw commented on code on Oct 08, 2026 00:11 UTC
    Code Review
    helm-chart/kuberay-operator/templates/webhooks.yaml:1
    @@ -0,0 +1,115 @@
    +{{- if .Values.webhooks.enabled }}
    +{{- $name := include "kuberay-operator.fullname" . }}
    +{{- $service := printf "%s-webhook" $name }}
    +{{- $cert := printf "%s-serving-cert" $name }}
    +apiVersion: v1
    +kind: Service
    +metadata:
    +  name: {{ $service }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  ports:
    +    - port: 443
    +      targetPort: webhook-server
    +      protocol: TCP
    +  selector:
    +    app.kubernetes.io/name: {{ include "kuberay-operator.name" . }}
    +    app.kubernetes.io/instance: {{ .Release.Name }}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Issuer
    +metadata:
    +  name: {{ $name }}-selfsigned-issuer
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  selfSigned: {}
    +---
    +apiVersion: cert-manager.io/v1
    +kind: Certificate
    +metadata:
    +  name: {{ $cert }}
    +  namespace: {{ .Release.Namespace }}
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +spec:
    +  dnsNames:
    +    - {{ $service }}.{{ .Release.Namespace }}.svc
    +    - {{ $service }}.{{ .Release.Namespace }}.svc.cluster.local
    +  issuerRef:
    +    kind: Issuer
    +    name: {{ $name }}-selfsigned-issuer
    +  secretName: {{ $name }}-webhook-server-cert
    +---
    +apiVersion: admissionregistration.k8s.io/v1
    +kind: MutatingWebhookConfiguration
    +metadata:
    +  name: {{ $name }}-mutating-webhook-configuration
    +  labels:
    +    {{- include "kuberay-operator.labels" . | nindent 4 }}
    +  annotations:
    +    cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ $cert }}
    +webhooks:
    +  # fails closed, so scoped to Ray node pods
    +  - name: mpod.kb.io
    +    admissionReviewVersions: ["v1"]
    +    clientConfig:
    +      service:
    +        name: {{ $service }}
    +        namespace: {{ .Release.Namespace }}
    +        path: /mutate-v1-pod
    +    failurePolicy: Fail
    +    objectSelector:
    +      matchLabels:
    +        ray.io/is-ray-node: "yes"

    done

    martinlhw martinlhw commented on code on Oct 08, 2026 00:12 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/rayservice_webhook.go:1
    @@ -53,6 +57,10 @@ func (w *RayServiceWebhook) validateRayService(rayService *rayv1.RayService) err
     		allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("name"), rayService.Name, err.Error()))
     	}
     
    +	if err := validateLabelRefs(&rayService.Spec.RayClusterSpec, rayService.Annotations, w.AllowedNodeLabels, field.NewPath("spec").Child("rayClusterConfig")); err != nil {
    +		allErrs = append(allErrs, err)

    sounds good-- added gates to {raycluster, rayservice, rayjob}_webhook.go

    martinlhw martinlhw commented on code on Oct 08, 2026 00:12 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/rayjob_webhook.go:1
    @@ -53,6 +57,12 @@ func (w *RayJobWebhook) validateRayJob(rayJob *rayv1.RayJob) error {
     		allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("name"), rayJob.Name, err.Error()))
     	}
     
    +	if rayJob.Spec.RayClusterSpec != nil {
    +		if err := validateLabelRefs(rayJob.Spec.RayClusterSpec, rayJob.Annotations, w.AllowedNodeLabels, field.NewPath("spec").Child("rayClusterSpec")); err != nil {

    done

    ryanaoleary ryanaoleary commented on code on Oct 08, 2026 00:29 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/label_refs_validation.go:1
    @@ -0,0 +1,77 @@
    +package v1
    +
    +import (
    +	"fmt"
    +	"slices"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	"k8s.io/apimachinery/pkg/util/validation/field"
    +
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +)
    +
    +// validateLabelRefs checks the labelRefs of every worker group in spec against the operator allowlist.
    +// annotations are the admitted object's metadata annotations, base is the field path of spec in that object
    +func validateLabelRefs(spec *rayv1.RayClusterSpec, annotations map[string]string, allowed []string, base *field.Path) *field.Error {
    +	for i := range spec.WorkerGroupSpecs {
    +		group := &spec.WorkerGroupSpecs[i]
    +		if len(group.LabelRefs) == 0 {
    +			continue
    +		}
    +		path := base.Child("workerGroupSpecs").Index(i).Child("labelRefs")
    +
    +		// node label delivery rewrites the KubeRay-generated ray start command, so the user must not replace it.
    +		// the annotation is read from the CR metadata and copied onto the pod template, so check both
    +		if overwritesContainerCmd(annotations) || overwritesContainerCmd(group.Template.Annotations) {
    +			return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s annotation; node label delivery needs the KubeRay-generated ray start command", utils.RayOverwriteContainerCmdAnnotationKey))
    +		}
    +		if len(group.Template.Spec.Containers) > utils.RayContainerIndex {
    +			container := group.Template.Spec.Containers[utils.RayContainerIndex]
    +			if strings.Contains(strings.Join(container.Command, " ")+" "+strings.Join(container.Args, " "), "ray start") {
    +				return field.Forbidden(path, "cannot be combined with a container command that runs ray start; node label delivery needs the KubeRay-generated ray start command")
    +			}
    +			if slices.ContainsFunc(container.Env, func(e corev1.EnvVar) bool { return e.Name == utils.RAY_NODE_LABELS_JSON }) {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s env var in the pod template; it is managed by KubeRay", utils.RAY_NODE_LABELS_JSON))
    +			}
    +		}
    +		// node label delivery passes --labels-file itself, and --labels would override the delivered keys
    +		for _, param := range []string{"labels", "labels-file"} {
    +			if _, ok := group.RayStartParams[param]; ok {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with rayStartParams %s", param))
    +			}
    +		}
    +		// check for duplicate label keys
    +		seen := make(map[string]bool, len(group.LabelRefs))
    +		for j, ref := range group.LabelRefs {
    +			refPath := path.Index(j)
    +			fieldPath := ref.ValueFrom.NodeRef.FieldPath
    +			nodeLabel, err := utils.NodeLabelKey(fieldPath)
    ryanaoleary ryanaoleary commented on code on Oct 08, 2026 01:18 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/rayjob_webhook.go:1
    @@ -53,6 +57,12 @@ func (w *RayJobWebhook) validateRayJob(rayJob *rayv1.RayJob) error {
     		allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("name"), rayJob.Name, err.Error()))
     	}
     
    +	if rayJob.Spec.RayClusterSpec != nil {
    +		if err := validateLabelRefs(rayJob.Spec.RayClusterSpec, rayJob.Annotations, w.AllowedNodeLabels, field.NewPath("spec").Child("rayClusterSpec")); err != nil {

    sorry think my comment was misleading, we don't want the outer feature gate check here because then labelRefs aren't validated when the feature is disabled - which they should be and rejected. Here it should be:

    if err := validateLabelRefs(&rayCluster.Spec, rayCluster.Annotations, w.AllowedNodeLabels, field.NewPath("spec")); err != nil {
        allErrs = append(allErrs, err)
    }
    

    and in label_refs_validation.gothere should be a check like:

    if !features.Enabled(features.NodeLabelDelivery) {
            return field.Forbidden(path, "requires the NodeLabelDelivery feature gate to be enabled")
        }
    

    after line 24: path := base.Child("workerGroupSpecs").Index(i).Child("labelRefs").

    The expected behavior is:
    1. No label refs -> do nothing regardless of feature gate
    2. User sets labelRefs and NodeLabelDelivery feature is disabled -> reject with message
    3. User sets labelRefs and NodeLabelDelivery feature is enabled -> validates normally, checks qualified name, etc.

    ryanaoleary ryanaoleary commented on code on Oct 08, 2026 02:15 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/label_refs_validation.go:1
    @@ -0,0 +1,81 @@
    +package v1
    +
    +import (
    +	"fmt"
    +	"slices"
    +	"strings"
    +
    +	corev1 "k8s.io/api/core/v1"
    +	"k8s.io/apimachinery/pkg/util/validation"
    +	"k8s.io/apimachinery/pkg/util/validation/field"
    +
    +	rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
    +	"github.com/ray-project/kuberay/ray-operator/controllers/ray/utils"
    +)
    +
    +// validateLabelRefs checks the labelRefs of every worker group in spec against the operator allowlist.
    +// annotations are the admitted object's metadata annotations, base is the field path of spec in that object
    +func validateLabelRefs(spec *rayv1.RayClusterSpec, annotations map[string]string, allowed []string, base *field.Path) *field.Error {
    +	for i := range spec.WorkerGroupSpecs {
    +		group := &spec.WorkerGroupSpecs[i]
    +		if len(group.LabelRefs) == 0 {
    +			continue
    +		}
    +		path := base.Child("workerGroupSpecs").Index(i).Child("labelRefs")
    +
    +		// node label delivery rewrites the KubeRay-generated ray start command, so the user must not replace it.
    +		// the annotation is read from the CR metadata and copied onto the pod template, so check both
    +		if overwritesContainerCmd(annotations) || overwritesContainerCmd(group.Template.Annotations) {
    +			return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s annotation; node label delivery needs the KubeRay-generated ray start command", utils.RayOverwriteContainerCmdAnnotationKey))
    +		}
    +		if len(group.Template.Spec.Containers) > utils.RayContainerIndex {
    +			container := group.Template.Spec.Containers[utils.RayContainerIndex]
    +			if strings.Contains(strings.Join(container.Command, " ")+" "+strings.Join(container.Args, " "), "ray start") {
    +				return field.Forbidden(path, "cannot be combined with a container command that runs ray start; node label delivery needs the KubeRay-generated ray start command")
    +			}
    +			if slices.ContainsFunc(container.Env, func(e corev1.EnvVar) bool { return e.Name == utils.RAY_NODE_LABELS_JSON }) {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with the %s env var in the pod template; it is managed by KubeRay", utils.RAY_NODE_LABELS_JSON))
    +			}
    +		}
    +		// node label delivery passes --labels-file itself, and --labels would override the delivered keys
    +		for _, param := range []string{"labels", "labels-file"} {
    +			if _, ok := group.RayStartParams[param]; ok {
    +				return field.Forbidden(path, fmt.Sprintf("cannot be combined with rayStartParams %s", param))
    +			}
    +		}
    +		// check for duplicate label keys
    +		seen := make(map[string]bool, len(group.LabelRefs))
    +		for j, ref := range group.LabelRefs {
    +			refPath := path.Index(j)
    +			fieldPath := ref.ValueFrom.NodeRef.FieldPath
    +			nodeLabel, err := utils.NodeLabelKey(fieldPath)
    +			if err != nil {
    +				return field.Invalid(refPath.Child("valueFrom", "nodeRef", "fieldPath"), fieldPath, err.Error())
    +			}

    should we do:

    if errs := validation.IsQualifiedName(nodeLabel); len(errs) > 0 {
      return field.Invalid(fieldPathRef, nodeLabel, strings.Join(errs, "; "))
    }
    

    here too

    ryanaoleary ryanaoleary approved these changes on Oct 08, 2026 04:06 UTC
    Approved Reviewer

    LGTM!

    win5923 win5923 commented on Oct 12, 2026 02:41 UTC
    Contributor

    @cursor review

    cursor[bot] cursor[bot] commented on Oct 12, 2026 02:42 UTC
    Reviewer

    <!-- BUGBOT_REVIEW -->
    <!-- BUGBOT_REVIEW_STALE -->
    Stale Bugbot comment from a previous run.

    win5923 win5923 commented on Oct 12, 2026 03:17 UTC
    Reviewer

    Sorry for the delayed review. I was down with the flu for the past few days. I've reviewed the non-webhook files, and LGTM!
    I'll finish reviewing the remaining webhook-related files today.

    Reviewers
    Assignees
    martinlhw martinlhw
    Labels
    risk: low confidence: 85.7% 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: 71.5% (HIGH) · Higher = larger blast radius
    71.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.7% · Lower = rushed or shallow review
    85.7%
    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: 10.2% · Safe to merge
    10.2%