← Back to Pull requests

fix(volcano): apply default memoryOverheadFactor to PodGroup minResources #3196

Open
Rajadi16 opened this pull request with 3505 lines diff across 20 files
View on GitHub
Rajadi16 Rajadi16 commented on Sep 24, 2026 22:34 UTC
Author

Fixes #2244

Problem


When spec.driver.memoryOverhead / spec.executor.memoryOverhead are not set (or memory itself is omitted), Volcano's PodGroup minResources under-reserved. It ignored the default memory overhead (0.1 JVM, 0.4 non-JVM, floor 384Mi) and the default 1 GiB heap, and ignored settings that only appear in sparkConf. YuniKorn already handled the overhead correctly.

Changes


  • Move internal/scheduler/yunikorn/resourceusage to internal/scheduler/resourceusage (pure rename, own commit), shared by YuniKorn and Volcano.

  • Add effective_config.go: one resolver for driver and executor memory settings, following the spark-submit argument order from buildSparkSubmitArgs.

  • - Heap: CRD > sparkConf > default 1 GiB
    - memoryOverhead: CRD > sparkConf > factor-based (max(heapfactor, 384Mi))
    - Factor: sparkConf spark.{driver,executor}.memoryOverheadFactor > sparkConf spark.kubernetes.memoryOverheadFactor > spec.memoryOverheadFactor > language default (0.1 JVM / 0.4 Python/R)
    - Factors must be finite, non-negative and <= 1000.
  • Add ToResourceList, DriverPodResourceList, ExecutorPodResourceList; Volcano uses these instead of pkg/util.GetRequestResource.

  • Honor Spark default units for unitless memory values (MiB; bytes for spark.memory.offHeap.size) via byteStringAsBytes, with int64 overflow guards.

  • util.GetInitialExecutorNumber now reads sparkConf (spark.executor.instances, dynamic allocation min/initial executors); CRD wins; negatives are clamped.

  • Apply spec.batchSchedulerOptions.resources overrides before computing anything.

  • Compute executor minResources by direct, constant-space multiplication with an overflow-safe multiplyQuantity (clear error on int64 overflow). There is no executor-count cap.

  • Use the Kubeflow license boilerplate in the new package.
  • Behavior changes (see CHANGELOG.md, Unreleased)


  • YuniKorn / Volcano: sparkConf memory, memoryOverhead and factor keys are now honored; unitless values parse as MiB; an omitted memory reserves the 1 GiB default heap (previously 0 heap + 384Mi overhead for YuniKorn).

  • Fail-fast: an unparsable memory value in sparkConf (e.g. spark.executor.memory: "2gb") now fails scheduling and aborts submission instead of running with an under-reserved PodGroup. Workaround: fix the value, or set spec.batchSchedulerOptions.resources, which bypasses the calculation. The webhook does not validate these strings by default.

  • Spark 3.3+: spark.{driver,executor}.memoryOverheadFactor (SPARK-38194) are ignored by Spark <= 3.2 but honored by the operator, which over-reserves there. Use spark.kubernetes.memoryOverheadFactor or spec.memoryOverheadFactor on older Spark.
  • Tests


  • Effective-config precedence: raw-only sparkConf, conflicting CRD vs sparkConf, per-role vs global factor, invalid values, memory omitted (client and cluster mode, JVM and Python).

  • Rounding matches Spark's integer-MiB overhead.

  • TestScheduleOverheadFactor, TestToResourceList, TestExecutorMinResources (including the overflow boundary), TestMultiplyQuantity, GetInitialExecutorNumber table, byte-string overflow boundaries.
  • Not in this PR


  • kube-scheduler still uses pkg/util.Get*RequestResource (kubescheduler/scheduler.go:90) and has the same under-reservation bug. Tracked in #XXXX.

  • The ResourceQuota webhook has its own calculation (getResourceList in resourcequota.go), not the shared package. It ignores sparkConf and dynamic allocation and uses a 0 heap when spec.memory is omitted. See #3207 for the Scala JVM-factor part.

  • Existing PodGroups are not updated on resubmission (MinResources/PriorityClassName stay stale): #3284.
  • Builds on #2262 by @kaka-zb.

    Diff: 3505 lines (+3063 / -442) across 20 files Reviewer: tariq-hasan Review duration: 99792m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.79) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.79 · 3505 lines diff across 20 files
    0.79
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    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
    48 items
    google-oss-prow[bot] google-oss-prow[bot] commented on Sep 24, 2026 22:35 UTC
    Bot

    [APPROVALNOTIFIER] This PR is NOT APPROVED

    This pull-request has been approved by:
    Once this PR has been reviewed and has the lgtm label, please assign yuchaoran2011 for approval. For more information see the Kubernetes Code Review Process.

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

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

  • OWNERS
  • 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":["yuchaoran2011"]} -->

    github-actions[bot] github-actions[bot] commented on Sep 24, 2026 22:35 UTC
    Bot

    🎉 Welcome to the Kubeflow Spark Operator! 🎉

    Thanks for opening your first PR! We're happy to have you as part of our community 🚀

    Here's what happens next:

  • If you haven't already, please check out our Contributing Guide for repo-specific guidelines and the Kubeflow Contributor Guide for general community standards.

  • Our team will review your PR soon!
  • Join the community:

  • Slack: Join our #kubeflow-spark-on-kubernetes Slack channel.
  • Feel free to ask questions in the comments if you need any help or clarification!
    Thanks again for contributing to Kubeflow! 🙏

    google-oss-prow[bot] google-oss-prow[bot] commented on Sep 24, 2026 22:39 UTC
    Bot

    @Rajadi16: Cannot trigger testing until a trusted user reviews the PR and leaves an /ok-to-test message.

    <details>

    In response to this:

    >/ok-to-test

    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/test-infra repository.

    </details>

    RobuRishabh RobuRishabh commented on Sep 29, 2026 16:03 UTC
    Contributor

    /ok-to-test

    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 00:43 UTC
    Code Review
    internal/scheduler/resourceusage/resource_usage.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2024 The Kubeflow authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    https://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 00:43 UTC
    Code Review
    internal/scheduler/resourceusage/resource_usage_test.go:1
    @@ -0,0 +1,350 @@
    +/*
    +Copyright 2024 The Kubeflow authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    https://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 01:36 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -174,6 +186,27 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	return nil
     }
     
    +// executorMinResources returns the aggregate resource requests for all initial
    +// executor pods (single-pod resources × initial executor count) with the correct
    +// memoryOverheadFactor applied.
    +func executorMinResources(app *v1beta2.SparkApplication) (corev1.ResourceList, error) {
    +	perPod, err := resourceusage.ExecutorPodResourceList(app)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	instances := util.GetInitialExecutorNumber(app)

    The present initial executor number calculation does not take spark conf into account.

    https://github.com/kubeflow/spark-operator/blob/de45190b195f662e415a3750d00f53210dc2a6b5/pkg/util/sparkapplication.go#L510-L534

    Please rewrite GetInitialExecutorNumber to form a precedence rule using both spark conf and CRD field.

    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 02:24 UTC
    Code Review
    internal/scheduler/resourceusage/java.go:1

    byteStringAsBytes returns error if there is no suffix but Spark's default behavior is to use MiB for spark.driver.memory, spark.executor.memory, spark.driver.memoryOverhead, spark.executor.memoryOverhead and bytes for spark.memory.offHeap.size when no suffix is provided.

    Let's give byteStringAsBytes a default-unit parameter so each caller can say which unit applies.

    https://github.com/kubeflow/spark-operator/blob/de45190b195f662e415a3750d00f53210dc2a6b5/internal/scheduler/yunikorn/resourceusage/java.go#L44-L56

    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 02:37 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1

    We need to check for the resource override from the user spec before we run executorMinResources.

    Let's replace

    		totalResource, err := executorMinResources(app)
    		if err != nil {
    			return fmt.Errorf("failed to calculate executor minResources: %w", err)
    		}
    
    		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
    			totalResource = app.Spec.BatchSchedulerOptions.Resources
    		}
    

    with

    		var totalResource corev1.ResourceList
    		if o := app.Spec.BatchSchedulerOptions; o != nil && len(o.Resources) > 0 {
    			totalResource = o.Resources
    		} else {
    			var err error
    			if totalResource, err = executorMinResources(app); err != nil {
    				return fmt.Errorf("failed to calculate executor minResources: %w", err)
    			}
    		}
    

    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 03:17 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -160,7 +164,15 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	// In cluster mode, the initial size of PodGroup is set to 1 in order to schedule driver pod first.
     	if _, ok := app.Spec.Driver.Annotations[v1beta1.KubeGroupNameAnnotationKey]; !ok {
     		// Both driver and executor resource will be considered.
    -		totalResource := util.SumResourceList([]corev1.ResourceList{util.GetDriverRequestResource(app), util.GetExecutorRequestResource(app)})
    +		driverRes, err := resourceusage.DriverPodResourceList(app)
    +		if err != nil {
    +			return fmt.Errorf("failed to calculate driver minResources: %w", err)
    +		}
    +		execRes, err := executorMinResources(app)
    +		if err != nil {
    +			return fmt.Errorf("failed to calculate executor minResources: %w", err)
    +		}
    +		totalResource := util.SumResourceList([]corev1.ResourceList{driverRes, execRes})
     		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
     			totalResource = app.Spec.BatchSchedulerOptions.Resources
     		}

    Same error as for client mode in terms of DriverPodResourceList and executorMinResources calculation applies here as well. Here is a suggestion:

    		var totalResource corev1.ResourceList  
    		if o := app.Spec.BatchSchedulerOptions; o != nil && len(o.Resources) > 0 {  
    			totalResource = o.Resources  
    		} else {  
    			driverRes, err := resourceusage.DriverPodResourceList(app)  
    			if err != nil {  
    				return fmt.Errorf("failed to calculate driver minResources: %w", err)  
    			}  
    			execRes, err := executorMinResources(app)  
    			if err != nil {  
    				return fmt.Errorf("failed to calculate executor minResources: %w", err)  
    			}  
    			totalResource = util.SumResourceList([]corev1.ResourceList{driverRes, execRes})  
    		}  
    

    tariq-hasan tariq-hasan requested changes on Oct 04, 2026 03:54 UTC
    Changes Requested Reviewer

    Hi @Rajadi16! Thanks for raising the PR. I have added a few suggestions for changes.

    Rajadi16 Rajadi16 commented on code on Oct 06, 2026 23:34 UTC
    Code Review
    internal/scheduler/resourceusage/resource_usage.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright 2024 The Kubeflow authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    https://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +

    Fixed in 4cda5b1. The file now uses the Kubeflow boilerplate header, and I applied it to all new and moved files under internal/scheduler/resourceusage/.

    Rajadi16 Rajadi16 commented on code on Oct 06, 2026 23:35 UTC
    Code Review
    internal/scheduler/resourceusage/resource_usage_test.go:1
    @@ -0,0 +1,350 @@
    +/*
    +Copyright 2024 The Kubeflow authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    https://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/

    Same fix as above, in 4cda5b1. The test file now uses the Kubeflow boilerplate header.

    Rajadi16 Rajadi16 commented on code on Oct 06, 2026 23:37 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -174,6 +186,27 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	return nil
     }
     
    +// executorMinResources returns the aggregate resource requests for all initial
    +// executor pods (single-pod resources × initial executor count) with the correct
    +// memoryOverheadFactor applied.
    +func executorMinResources(app *v1beta2.SparkApplication) (corev1.ResourceList, error) {
    +	perPod, err := resourceusage.ExecutorPodResourceList(app)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	instances := util.GetInitialExecutorNumber(app)

    Addressed in e7629a3, with a hardening follow-up in 0e1c704.

    GetInitialExecutorNumber now resolves spark.executor.instances, minExecutors and initialExecutors from the CRD field first, then falls back to sparkConf. I checked the precedence against buildSparkSubmitArgs: sparkConfOption is emitted before executorConfOption, and spark-submit takes the last occurrence of a repeated --conf, so the CRD value wins. The doc comment states this.

    The result follows Spark's SchedulerBackendUtils. With dynamic allocation off it is instances (default 2). With it on it is max(instances, initialExecutors, minExecutors), where initialExecutors defaults to minExecutors. Dynamic allocation can also be enabled through sparkConf alone, and that case is covered.

    Unparsable or negative sparkConf values are ignored, as IsDynamicAllocationEnabled already does for bad values. Negative CRD values are clamped to 0, so make() in executorMinResources cannot panic. The table tests cover CRD-only, sparkConf-only, both set, mixed, and invalid or negative values.

    Happy to change the ignore-invalid behavior to return an error if you prefer.

    Rajadi16 Rajadi16 commented on code on Oct 06, 2026 23:38 UTC
    Code Review
    internal/scheduler/resourceusage/java.go:1

    Done in e3512d7. byteStringAsBytes now takes a DefaultUnit parameter:

  • DefaultUnitMiB for spark.driver.memory, spark.executor.memory, spark.driver.memoryOverhead, spark.executor.memoryOverhead and spark.executor.pyspark.memory

  • DefaultUnitBytes for spark.memory.offHeap.size
  • Suffixed values behave as before. The pattern now accepts a bare number, and the old workaround that appended "m" to the pyspark value is removed. Tests cover bare numbers under both defaults, uppercase suffixes, and the existing invalid inputs.

    One side effect: unitless values that used to error in the YuniKorn path now parse using the Spark defaults above.

    Rajadi16 Rajadi16 commented on code on Oct 06, 2026 23:39 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1

    Fixed in 8701838. syncPodGroupInClientMode now checks BatchSchedulerOptions.Resources first and only calls executorMinResources when there is no override, using the structure you suggested. A spec that would fail the calculation no longer errors when an override is set.

    Rajadi16 Rajadi16 commented on code on Oct 06, 2026 23:39 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -160,7 +164,15 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	// In cluster mode, the initial size of PodGroup is set to 1 in order to schedule driver pod first.
     	if _, ok := app.Spec.Driver.Annotations[v1beta1.KubeGroupNameAnnotationKey]; !ok {
     		// Both driver and executor resource will be considered.
    -		totalResource := util.SumResourceList([]corev1.ResourceList{util.GetDriverRequestResource(app), util.GetExecutorRequestResource(app)})
    +		driverRes, err := resourceusage.DriverPodResourceList(app)
    +		if err != nil {
    +			return fmt.Errorf("failed to calculate driver minResources: %w", err)
    +		}
    +		execRes, err := executorMinResources(app)
    +		if err != nil {
    +			return fmt.Errorf("failed to calculate executor minResources: %w", err)
    +		}
    +		totalResource := util.SumResourceList([]corev1.ResourceList{driverRes, execRes})
     		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
     			totalResource = app.Spec.BatchSchedulerOptions.Resources
     		}

    Fixed in 8701838. Same change for syncPodGroupInClusterMode: the override is checked first, and the driver and executor calculations only run in the else branch, using your suggested structure.

    Rajadi16 Rajadi16 commented on Oct 06, 2026 23:40 UTC
    Author

    @tariq-hasan all four review items are addressed: license headers (4cda5b1), default units (e3512d7), sparkConf-aware initial executor count (e7629a3, 0e1c704) and override-before-compute (8701838). Build, vet, tests and lint pass locally, and CI is green apart from tide, which is waiting on lgtm/approved. Could you take another look when you have a moment?

    RobuRishabh RobuRishabh commented on code on Oct 07, 2026 15:51 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -174,6 +192,28 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	return nil
     }
     
    +// executorMinResources returns the aggregate resource requests for all initial
    +// executor pods (single-pod resources × initial executor count) with the correct
    +// memoryOverheadFactor applied.
    +func executorMinResources(app *v1beta2.SparkApplication) (corev1.ResourceList, error) {
    +	perPod, err := resourceusage.ExecutorPodResourceList(app)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	instances := util.GetInitialExecutorNumber(app)
    +
    +	// GetInitialExecutorNumber guarantees instances >= 0, so make() cannot panic.
    +	// util.SumResourceList only reads its inputs (it calls quantity.DeepCopy() on
    +	// the first occurrence of each resource name and Add() on its own accumulator
    +	// thereafter), so repeating the same perPod map in the slice is safe.
    +	resourceList := make([]corev1.ResourceList, instances)
    +	for i := range resourceList {
    +		resourceList[i] = perPod
    +	}
    +	return util.SumResourceList(resourceList), nil
    +}
    +

    validateSparkConf only denies keys it does no numeric validation and the CRD Instances field has +kubebuilder:validation:Minimum=1 with no maximum. So sparkConf: {spark.executor.instances: "2000000000"} passes every gate and the operator tries to allocate ~16 GB of slice headers, then iterate 2e9 times in SumResourceList. Even a fat-fingered "100000000" stalls the reconcile loop.

    The adjacent comment "GetInitialExecutorNumber guarantees instances >= 0, so make() cannot panic"it addresses sign, not magnitude. The slice is also unnecessary summing N copies of one map is a multiply:

    total := corev1.ResourceList{}
    for name, q := range perPod {
        total[name] = *resource.NewMilliQuantity(q.MilliValue()*int64(instances), q.Format)
    }
    return total, nil
    

    RobuRishabh RobuRishabh commented on Oct 07, 2026 16:01 UTC
    Reviewer

    @Rajadi16 please update the PR description with the current changes

    Rajadi16 Rajadi16 commented on Oct 07, 2026 23:53 UTC
    Author

    Thanks @RobuRishabh, good catch. Fixed in 88fdff3:

  • Replaced the slice + SumResourceList with a direct per-resource multiplication, so nothing scales with the executor count.

  • multiplyQuantity returns an error on int64 milli-value overflow and preserves q.Format.

  • executorMinResources rejects counts above maxExecutorInstances (10,000) with a clear error, so spark.executor.instances: "2000000000" now fails fast. It surfaces as FailedSubmission with the message in the SparkApplication status, plus an event.

  • Removed the stale make() comment and clarified the maxExecutorInstances comment in 4de8433.

  • Tests: TestExecutorMinResources (including 2000000000 and the overflow boundary) and TestMultiplyQuantity.
  • The PR description is also updated. Could you take another look and resolve this thread if it looks good?

    RobuRishabh RobuRishabh commented on code on Oct 12, 2026 14:05 UTC
    Code Review
    internal/scheduler/resourceusage/memory.go:1
    @@ -47,15 +47,17 @@ func memoryRequestBytes(podSpec *v1beta2.SparkPodSpec, memoryOverheadFactor floa
     	var memoryBytes, memoryOverheadBytes int64
     
     	if podSpec.Memory != nil {
    -		parsed, err := byteStringAsBytes(*podSpec.Memory)
    +		// spark.driver.memory / spark.executor.memory: bare number means MiB.
    +		parsed, err := byteStringAsBytes(*podSpec.Memory, DefaultUnitMiB)

    When spec.driver.memory or spec.executor.memory is omitted, memoryBytes remains zero, so this reserves only the 384 MiB overhead. Spark’s default heap is 1 GiB, meaning a default executor will request about 1,408 MiB while Volcano reserves 384 MiB. That preserves the under-reservation bug for otherwise valid applications. Could we default the heap to common.DefaultMemoryBytes and add client- and cluster-mode tests with memory omitted?

    RobuRishabh RobuRishabh commented on code on Oct 12, 2026 14:06 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -159,10 +168,21 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	// We need mark both driver and executor when submitting.
     	// In cluster mode, the initial size of PodGroup is set to 1 in order to schedule driver pod first.
     	if _, ok := app.Spec.Driver.Annotations[v1beta1.KubeGroupNameAnnotationKey]; !ok {
    -		// Both driver and executor resource will be considered.
    -		totalResource := util.SumResourceList([]corev1.ResourceList{util.GetDriverRequestResource(app), util.GetExecutorRequestResource(app)})
    -		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
    -			totalResource = app.Spec.BatchSchedulerOptions.Resources
    +		// Check the user-supplied override first so that a spec with an invalid memory
    +		// string does not error when the override would be used anyway.
    +		var totalResource corev1.ResourceList
    +		if o := app.Spec.BatchSchedulerOptions; o != nil && len(o.Resources) > 0 {
    +			totalResource = o.Resources
    +		} else {
    +			driverRes, err := resourceusage.DriverPodResourceList(app)

    This calculator does not appear to resolve memory settings using the same inputs and precedence as spark-submit. For example, with a 4 GiB executor and sparkConf["spark.kubernetes.memoryOverheadFactor"]="0.5", Volcano calculates the default 0.1 factor, while the later raw --conf makes Spark request the 0.5 result. Raw spark.driver.memory and spark.executor.memory have the same problem when the structured fields are absent. Could we introduce a shared effective-configuration resolver and add raw-only plus conflicting CRD/sparkConf tests?

    RobuRishabh RobuRishabh commented on code on Oct 12, 2026 14:07 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -174,6 +194,78 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	return nil
     }
     
    +// maxExecutorInstances is a sanity limit on the initial executor count.
    +// Instances come from unvalidated user input (the CRD has no maximum and
    +// sparkConf is a free-form string map), so we reject absurd values early
    +// with a clear error. Overflow is guarded separately in multiplyQuantity.
    +const maxExecutorInstances = 10_000
    +
    +// multiplyResourceList returns a new ResourceList whose every quantity equals
    +// q * n.  The Format of the original quantity is preserved on the result.
    +// An error is returned if the multiplication would overflow int64 in the
    +// milli-value representation (which is the finest granularity k8s uses
    +// internally).
    +func multiplyResourceList(src corev1.ResourceList, n int32) (corev1.ResourceList, error) {
    +	if n == 0 {
    +		return corev1.ResourceList{}, nil
    +	}
    +	result := make(corev1.ResourceList, len(src))
    +	for name, q := range src {
    +		scaled, err := multiplyQuantity(q, int64(n))
    +		if err != nil {
    +			return nil, fmt.Errorf("overflow multiplying resource %s by %d: %w", name, n, err)
    +		}
    +		result[name] = scaled
    +	}
    +	return result, nil
    +}
    +
    +// multiplyQuantity returns q*n while preserving q.Format.
    +// It errors on int64 milli-value overflow.
    +func multiplyQuantity(q resource.Quantity, n int64) (resource.Quantity, error) {
    +	milli := q.MilliValue()
    +	if milli != 0 {
    +		// Overflow guard: milli*n overflows when n > MaxInt64/|milli|.
    +		if milli > 0 && n > math.MaxInt64/milli {
    +			return resource.Quantity{}, fmt.Errorf("milli-value %d × %d overflows int64", milli, n)
    +		}
    +		if milli < 0 && n > math.MaxInt64/(-milli) {
    +			return resource.Quantity{}, fmt.Errorf("milli-value %d × %d overflows int64", milli, n)
    +		}
    +	}
    +	// Build the result from the scaled milli-value, then restore the original
    +	// Format so binary-SI quantities (e.g. Gi) remain binary-SI.
    +	scaled := resource.NewMilliQuantity(milli*n, q.Format)
    +	return *scaled, nil
    +}
    +
    +// executorMinResources returns the aggregate resource requests for all initial
    +// executor pods (single-pod resources × initial executor count) with the correct
    +// memoryOverheadFactor applied.
    +//
    +// instances is unbounded user input (no CRD maximum, sparkConf is a free-form
    +// string map).  We multiply per-resource directly instead of building a slice of
    +// length instances, to avoid O(instances) allocation and iteration.  Absurd
    +// values are rejected by the maxExecutorInstances guard; int64 overflow is
    +// handled inside multiplyQuantity.
    +func executorMinResources(app *v1beta2.SparkApplication) (corev1.ResourceList, error) {
    +	perPod, err := resourceusage.ExecutorPodResourceList(app)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	instances := util.GetInitialExecutorNumber(app)
    +	if instances == 0 {
    +		return corev1.ResourceList{}, nil
    +	}
    +	if instances > maxExecutorInstances {

    This introduces a new Volcano-only failure for applications with more than 10,000 initial executors, although neither the CRD nor Spark currently defines that limit. Since the new multiplication is constant-space and overflow is checked separately, could we remove this cap? If it is an intentional product limit, please make it configurable or schema-validated and document the compatibility change.

    RobuRishabh RobuRishabh requested changes on Oct 12, 2026 14:08 UTC
    Changes Requested Reviewer

    Hi @Rajadi16 thanks for the contribution, I left some comments, PTAL

    Rajadi16 Rajadi16 commented on code on Oct 13, 2026 23:51 UTC
    Code Review
    internal/scheduler/resourceusage/memory.go:1
    @@ -47,15 +47,17 @@ func memoryRequestBytes(podSpec *v1beta2.SparkPodSpec, memoryOverheadFactor floa
     	var memoryBytes, memoryOverheadBytes int64
     
     	if podSpec.Memory != nil {
    -		parsed, err := byteStringAsBytes(*podSpec.Memory)
    +		// spark.driver.memory / spark.executor.memory: bare number means MiB.
    +		parsed, err := byteStringAsBytes(*podSpec.Memory, DefaultUnitMiB)

    Fixed in 826eb25. When memory is unset in both the CRD and sparkConf, the heap now defaults to common.DefaultMemoryBytes (1 GiB), so a default executor reserves 1408 MiB. Tests for client and cluster mode with memory omitted are in 35c472d.

    Rajadi16 Rajadi16 commented on code on Oct 13, 2026 23:52 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -159,10 +168,21 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	// We need mark both driver and executor when submitting.
     	// In cluster mode, the initial size of PodGroup is set to 1 in order to schedule driver pod first.
     	if _, ok := app.Spec.Driver.Annotations[v1beta1.KubeGroupNameAnnotationKey]; !ok {
    -		// Both driver and executor resource will be considered.
    -		totalResource := util.SumResourceList([]corev1.ResourceList{util.GetDriverRequestResource(app), util.GetExecutorRequestResource(app)})
    -		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
    -			totalResource = app.Spec.BatchSchedulerOptions.Resources
    +		// Check the user-supplied override first so that a spec with an invalid memory
    +		// string does not error when the override would be used anyway.
    +		var totalResource corev1.ResourceList
    +		if o := app.Spec.BatchSchedulerOptions; o != nil && len(o.Resources) > 0 {
    +			totalResource = o.Resources
    +		} else {
    +			driverRes, err := resourceusage.DriverPodResourceList(app)

    Added effective_config.go (6606c66), a single resolver for driver and executor with the precedence taken from buildSparkSubmitArgs: the CRD wins for heap and overhead, and sparkConf wins for the factor keys. Per-role spark.{driver,executor}.memoryOverheadFactor support is in 560d1ed. Tests cover raw-only sparkConf, conflicting CRD vs sparkConf, and your 4g + 0.5 scenario (6144 MiB) in 35c472d.

    Rajadi16 Rajadi16 commented on code on Oct 13, 2026 23:52 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -174,6 +194,78 @@ func (s *Scheduler) syncPodGroupInClusterMode(app *v1beta2.SparkApplication) err
     	return nil
     }
     
    +// maxExecutorInstances is a sanity limit on the initial executor count.
    +// Instances come from unvalidated user input (the CRD has no maximum and
    +// sparkConf is a free-form string map), so we reject absurd values early
    +// with a clear error. Overflow is guarded separately in multiplyQuantity.
    +const maxExecutorInstances = 10_000
    +
    +// multiplyResourceList returns a new ResourceList whose every quantity equals
    +// q * n.  The Format of the original quantity is preserved on the result.
    +// An error is returned if the multiplication would overflow int64 in the
    +// milli-value representation (which is the finest granularity k8s uses
    +// internally).
    +func multiplyResourceList(src corev1.ResourceList, n int32) (corev1.ResourceList, error) {
    +	if n == 0 {
    +		return corev1.ResourceList{}, nil
    +	}
    +	result := make(corev1.ResourceList, len(src))
    +	for name, q := range src {
    +		scaled, err := multiplyQuantity(q, int64(n))
    +		if err != nil {
    +			return nil, fmt.Errorf("overflow multiplying resource %s by %d: %w", name, n, err)
    +		}
    +		result[name] = scaled
    +	}
    +	return result, nil
    +}
    +
    +// multiplyQuantity returns q*n while preserving q.Format.
    +// It errors on int64 milli-value overflow.
    +func multiplyQuantity(q resource.Quantity, n int64) (resource.Quantity, error) {
    +	milli := q.MilliValue()
    +	if milli != 0 {
    +		// Overflow guard: milli*n overflows when n > MaxInt64/|milli|.
    +		if milli > 0 && n > math.MaxInt64/milli {
    +			return resource.Quantity{}, fmt.Errorf("milli-value %d × %d overflows int64", milli, n)
    +		}
    +		if milli < 0 && n > math.MaxInt64/(-milli) {
    +			return resource.Quantity{}, fmt.Errorf("milli-value %d × %d overflows int64", milli, n)
    +		}
    +	}
    +	// Build the result from the scaled milli-value, then restore the original
    +	// Format so binary-SI quantities (e.g. Gi) remain binary-SI.
    +	scaled := resource.NewMilliQuantity(milli*n, q.Format)
    +	return *scaled, nil
    +}
    +
    +// executorMinResources returns the aggregate resource requests for all initial
    +// executor pods (single-pod resources × initial executor count) with the correct
    +// memoryOverheadFactor applied.
    +//
    +// instances is unbounded user input (no CRD maximum, sparkConf is a free-form
    +// string map).  We multiply per-resource directly instead of building a slice of
    +// length instances, to avoid O(instances) allocation and iteration.  Absurd
    +// values are rejected by the maxExecutorInstances guard; int64 overflow is
    +// handled inside multiplyQuantity.
    +func executorMinResources(app *v1beta2.SparkApplication) (corev1.ResourceList, error) {
    +	perPod, err := resourceusage.ExecutorPodResourceList(app)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	instances := util.GetInitialExecutorNumber(app)
    +	if instances == 0 {
    +		return corev1.ResourceList{}, nil
    +	}
    +	if instances > maxExecutorInstances {

    Removed maxExecutorInstances in 55a2d5a. The multiplication is O(1) and multiplyQuantity returns a clear error on int64 overflow, so Volcano no longer has its own limit.

    rishabhsai rishabhsai commented on Oct 15, 2026 04:59 UTC
    Contributor

    Heads up on an overlap: #3207 adds a shared util.IsJVMApp and replaces the private isJavaApp in the yunikorn memory.go, which this PR moves into internal/scheduler/resourceusage. Whichever lands first, I'm happy to rebase #3207 onto this and point the new isJavaApp here at the shared helper, or drop that part if you'd rather keep yours. Just flagging so neither of us hits a surprise conflict.

    Rajadi16 Rajadi16 commented on Oct 16, 2026 20:57 UTC
    Author

    @rishabhsai thanks so much for the heads up, really appreciate you flagging it early and offering to rebase! 🙏 To keep things stable while this is in review, I'll leave isJavaApp as is for now. If #3207 lands first, I'll happily rebase and switch it to util.IsJVMApp. If this one lands first, please feel free to rebase onto it and drop the private helper in resourceusage/memory.go. Either order works for me, and I'm glad to help if any conflicts come up.

    Rajadi16 Rajadi16 commented on Oct 16, 2026 20:58 UTC
    Author

    @RobuRishabh thank you for the detailed reviews, they really improved the PR! All three items are addressed: default heap (826eb25), the shared effective-config resolver (6606c66), and the cap removal (55a2d5a), plus per-role factor keys in 560d1ed. The PR description is updated too. Whenever you get a chance, could you take another look? Happy to adjust anything else.

    RobuRishabh RobuRishabh commented on Oct 20, 2026 15:20 UTC
    Contributor

    @Rajadi16 with enable-resource-quota-enforcement=true, the webhook's quota math (getSparkPodMemoryRequests) uses 0-byte heap when spec.memory is omitted and ignores sparkConf entirely, while PodGroup minResources now reserves a 1GiB default heap and honors sparkConf. Quota admission and gang reservation can now disagree for the same app. Is converging the webhook onto the new resourceusage package planned as a follow-up?

    RobuRishabh RobuRishabh commented on code on Oct 20, 2026 15:22 UTC
    Code Review
    internal/scheduler/yunikorn/scheduler.go:1
    @@ -26,7 +26,7 @@ import (
     
     	"github.com/kubeflow/spark-operator/v2/api/v1beta2"
     	"github.com/kubeflow/spark-operator/v2/internal/scheduler"
    -	"github.com/kubeflow/spark-operator/v2/internal/scheduler/yunikorn/resourceusage"
    +	"github.com/kubeflow/spark-operator/v2/internal/scheduler/resourceusage"

    This import swap changes YuniKorn behavior beyond the PR's stated scope ("YuniKorn already handled the overhead correctly"):

  • sparkConf memory/overhead/factor are now honored (previously ignored)

  • bare numbers like 2048 now parse as MiB (previously errored)

  • memory-omitted specs now reserve 1GiB heap (previously 0 heap + 384Mi overhead)
  • All improvements IMO, but existing YuniKorn users will see different reservations worth a release-note callout.

    RobuRishabh RobuRishabh commented on code on Oct 20, 2026 15:23 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -141,10 +144,16 @@ func (s *Scheduler) Cleanup(app *v1beta2.SparkApplication) error {
     func (s *Scheduler) syncPodGroupInClientMode(app *v1beta2.SparkApplication) error {
     	// We only care about the executor pods in client mode
     	if _, ok := app.Spec.Executor.Annotations[v1beta1.KubeGroupNameAnnotationKey]; !ok {
    -		totalResource := util.GetExecutorRequestResource(app)
    -
    -		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
    -			totalResource = app.Spec.BatchSchedulerOptions.Resources
    +		// Check the user-supplied override first so that a spec with an invalid memory
    +		// string does not error when the override would be used anyway.
    +		var totalResource corev1.ResourceList
    +		if o := app.Spec.BatchSchedulerOptions; o != nil && len(o.Resources) > 0 {
    +			totalResource = o.Resources
    +		} else {
    +			var err error
    +			if totalResource, err = executorMinResources(app); err != nil {
    +				return fmt.Errorf("failed to calculate executor minResources: %w", err)

    Behavior change to flag: an invalid memory string in sparkConf (e.g. spark.executor.memory=2gb) now fails Schedule, and the controller aborts submission (controller.go:1009). The webhook doesn't validate memory strings by default (enable-resource-quota-enforcement defaults to false), so specs with typos that previously ran (under-reserved) now hard-fail at submission. Defensible fail-fast, but suggest a changelog/release-note entry.

    RobuRishabh RobuRishabh commented on code on Oct 20, 2026 15:24 UTC
    Code Review
    pkg/common/spark.go:1
    @@ -198,6 +198,16 @@ const (
     	// SparkKubernetesMemoryOverheadFactor is the Spark configuration key for specifying memory overhead factor used for Non-JVM memory.
     	SparkKubernetesMemoryOverheadFactor = "spark.kubernetes.memoryOverheadFactor"
     
    +	// SparkDriverMemoryOverheadFactor is the per-driver memory overhead factor key (Spark 3.3+).
    +	// It takes precedence over SparkKubernetesMemoryOverheadFactor when both are set.
    +	// https://spark.apache.org/docs/latest/configuration.html#application-properties
    +	SparkDriverMemoryOverheadFactor = "spark.driver.memoryOverheadFactor"
    +
    +	// SparkExecutorMemoryOverheadFactor is the per-executor memory overhead factor key (Spark 3.3+).
    +	// It takes precedence over SparkKubernetesMemoryOverheadFactor when both are set.
    +	// https://spark.apache.org/docs/latest/configuration.html#application-properties
    +	SparkExecutorMemoryOverheadFactor = "spark.executor.memoryOverheadFactor"
    +

    Worth documenting: these per-role keys are Spark 3.3+ (SPARK-38194). On Spark ≤3.2, Spark itself ignores them but the operator honors them → PodGroup over-reserves overhead. Minor, but a note on the minimum supported Spark version would help users on older distros. Also make the comments little small, its too much verbose.

    RobuRishabh RobuRishabh requested changes on Oct 20, 2026 15:26 UTC
    Changes Requested Reviewer

    @Rajadi16 Small correction to the PR description: the webhook does not call pkg/util.GetRequestResource it has its own math in getResourceList (resourcequota.go:52). The only remaining caller of the old functions is kubescheduler/scheduler.go:90.

    And kubescheduler/scheduler.go:90 still calls the old GetRequestResource functions, so the under-reservation bug remains there (acknowledged in the PR description). Could you open a tracking issue so it isn't lost after merge?

    rishabhsai rishabhsai commented on Oct 20, 2026 20:46 UTC
    Contributor

    Related: #3207 fixes the other half of the webhook mismatch. getMemoryRequests treats Scala apps as non-JVM and charges them the 0.4 overhead factor, and that PR moves the JVM check into a shared helper. Once this lands I'll rebase it onto internal/scheduler/resourceusage so the webhook and PodGroup math run through the same code. I can fold the sparkConf and default-heap convergence into that same follow-up if nobody else is picking it up.

    Rajadi16 Rajadi16 commented on code on Nov 08, 2026 06:46 UTC
    Code Review
    internal/scheduler/yunikorn/scheduler.go:1
    @@ -26,7 +26,7 @@ import (
     
     	"github.com/kubeflow/spark-operator/v2/api/v1beta2"
     	"github.com/kubeflow/spark-operator/v2/internal/scheduler"
    -	"github.com/kubeflow/spark-operator/v2/internal/scheduler/yunikorn/resourceusage"
    +	"github.com/kubeflow/spark-operator/v2/internal/scheduler/resourceusage"

    Agreed, these are intentional improvements. Added a "Behavior Changes" entry to CHANGELOG.md (d9e3382) covering sparkConf keys now honored, unitless values parsed as MiB, and the 1 GiB default heap when memory is omitted. Also summarized in the PR description.

    Rajadi16 Rajadi16 commented on code on Nov 08, 2026 06:46 UTC
    Code Review
    internal/scheduler/volcano/scheduler.go:1
    @@ -141,10 +144,16 @@ func (s *Scheduler) Cleanup(app *v1beta2.SparkApplication) error {
     func (s *Scheduler) syncPodGroupInClientMode(app *v1beta2.SparkApplication) error {
     	// We only care about the executor pods in client mode
     	if _, ok := app.Spec.Executor.Annotations[v1beta1.KubeGroupNameAnnotationKey]; !ok {
    -		totalResource := util.GetExecutorRequestResource(app)
    -
    -		if app.Spec.BatchSchedulerOptions != nil && len(app.Spec.BatchSchedulerOptions.Resources) > 0 {
    -			totalResource = app.Spec.BatchSchedulerOptions.Resources
    +		// Check the user-supplied override first so that a spec with an invalid memory
    +		// string does not error when the override would be used anyway.
    +		var totalResource corev1.ResourceList
    +		if o := app.Spec.BatchSchedulerOptions; o != nil && len(o.Resources) > 0 {
    +			totalResource = o.Resources
    +		} else {
    +			var err error
    +			if totalResource, err = executorMinResources(app); err != nil {
    +				return fmt.Errorf("failed to calculate executor minResources: %w", err)

    Fail-fast is intentional. Documented in CHANGELOG.md under "Fail-fast on invalid memory" (d9e3382) and in the PR description, including the workaround (fix the value, or set spec.batchSchedulerOptions.resources, which is checked first and skips this path) and that the webhook doesn't validate these strings by default.

    Rajadi16 Rajadi16 commented on code on Nov 08, 2026 06:46 UTC
    Code Review
    pkg/common/spark.go:1
    @@ -198,6 +198,16 @@ const (
     	// SparkKubernetesMemoryOverheadFactor is the Spark configuration key for specifying memory overhead factor used for Non-JVM memory.
     	SparkKubernetesMemoryOverheadFactor = "spark.kubernetes.memoryOverheadFactor"
     
    +	// SparkDriverMemoryOverheadFactor is the per-driver memory overhead factor key (Spark 3.3+).
    +	// It takes precedence over SparkKubernetesMemoryOverheadFactor when both are set.
    +	// https://spark.apache.org/docs/latest/configuration.html#application-properties
    +	SparkDriverMemoryOverheadFactor = "spark.driver.memoryOverheadFactor"
    +
    +	// SparkExecutorMemoryOverheadFactor is the per-executor memory overhead factor key (Spark 3.3+).
    +	// It takes precedence over SparkKubernetesMemoryOverheadFactor when both are set.
    +	// https://spark.apache.org/docs/latest/configuration.html#application-properties
    +	SparkExecutorMemoryOverheadFactor = "spark.executor.memoryOverheadFactor"
    +

    Trimmed the per-role factor comments to one line each and cited SPARK-38194. The <=3.2 over-reservation caveat and workaround (spark.kubernetes.memoryOverheadFactor or spec.memoryOverheadFactor) are in CHANGELOG.md under "Spark 3.3+ note", and the duplicated precedence docs in memory.go now just point to effective_config.go.

    Rajadi16 Rajadi16 commented on Nov 08, 2026 06:47 UTC
    Author

    Corrected the description: the webhook has its own math in getResourceList, and only kubescheduler/scheduler.go:90 still calls pkg/util.Get*RequestResource. Opened a tracking issue for it: #<your number>.

    Rajadi16 Rajadi16 commented on Nov 08, 2026 06:47 UTC
    Author

    @RobuRishabh @tariq-hasan all threads are addressed (CHANGELOG + description updated, d9e3382). Could you take another look? Also requesting /lgtm and an OWNERS /approve when you're happy.

    vjanelle vjanelle commented on code on Dec 01, 2026 22:22 UTC
    Code Review
    internal/scheduler/resourceusage/effective_config.go:1
    @@ -0,0 +1,259 @@
    +/*
    +Copyright The Kubeflow Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package resourceusage
    +
    +import (
    +	"fmt"
    +	"math"
    +	"strconv"
    +
    +	"github.com/kubeflow/spark-operator/v2/api/v1beta2"
    +	"github.com/kubeflow/spark-operator/v2/pkg/common"
    +)
    +
    +// effectiveMemoryConfig holds the resolved memory configuration for a single pod
    +// (driver or executor) after applying the CRD-vs-sparkConf precedence rules
    +// documented below.
    +type effectiveMemoryConfig struct {
    +	// heapBytes is the effective spark.driver.memory / spark.executor.memory in bytes.
    +	heapBytes int64
    +	// memoryOverheadBytes is non-zero only when an explicit memoryOverhead is set;
    +	// zero means the factor-based calculation should be used.
    +	memoryOverheadBytes int64
    +	// overheadExplicit is true when memoryOverheadBytes was sourced from an
    +	// explicit field rather than the default factor.
    +	overheadExplicit bool
    +	// overheadFactor is the effective memoryOverheadFactor to apply when
    +	// overheadExplicit is false.
    +	overheadFactor float64
    +}
    +
    +// totalBytes returns heapBytes + overhead bytes, where overhead is either the
    +// explicit value or max(heap*factor, MinMemoryOverhead).
    +//
    +// Spark computes overhead in whole MiB: max(int(heapMiB * factor), 384).
    +// We compute in bytes and floor the total at the end (in bytesToMi), which
    +// produces the same integer-MiB result because:
    +//
    +//	int64(heapBytes * factor) / 1024 / 1024  ==  int(heapMiB * factor)
    +//
    +// for any heap that is an exact number of MiB (which all Spark memory
    +// strings produce).  bytesToMi then floors the grand total, matching Spark.
    +func (e *effectiveMemoryConfig) totalBytes() int64 {
    +	if e.overheadExplicit {
    +		return e.heapBytes + e.memoryOverheadBytes
    +	}
    +	overhead := int64(float64(e.heapBytes) * e.overheadFactor)
    +	if overhead < common.MinMemoryOverhead {
    +		overhead = common.MinMemoryOverhead
    +	}
    +	return e.heapBytes + overhead
    +}
    +
    +// Precedence rules, verified against
    +// internal/controller/sparkapplication/submission.go buildSparkSubmitArgs:
    +//
    +//	Option order: memoryOverheadFactorOption(10) → sparkConfOption(12) →
    +//	              driverConfOption(15) → executorConfOption(19)
    +//
    +// Spark CLI processes --conf flags in order and the LAST occurrence wins.
    +// Therefore:
    +//
    +//   - spark.driver.memory / spark.executor.memory: CRD field wins over sparkConf
    +//     (driverConfOption/executorConfOption run after sparkConfOption).
    +//
    +//   - spark.driver.memoryOverhead / spark.executor.memoryOverhead: CRD field wins.
    +//
    +//   - Factor keys (highest to lowest priority for the factor):
    +//       1. sparkConf[spark.driver.memoryOverheadFactor] (driver) or
    +//          sparkConf[spark.executor.memoryOverheadFactor] (executor)  — Spark 3.3+,
    +//          per-role key, wins over the cluster-wide key.
    +//       2. sparkConf[spark.kubernetes.memoryOverheadFactor] — cluster-wide key,
    +//          wins over the CRD structured field (sparkConfOption runs after
    +//          memoryOverheadFactorOption).
    +//       3. spec.MemoryOverheadFactor — structured CRD field.
    +//       4. Language default: 0.1 for JVM (Java/Scala), 0.4 for non-JVM (Python/R).
    +
    +// effectiveDriverConfig returns the resolved memory configuration for the driver.
    +func effectiveDriverConfig(app *v1beta2.SparkApplication) (*effectiveMemoryConfig, error) {
    +	return effectivePodConfig(
    +		app,
    +		app.Spec.Driver.Memory,
    +		app.Spec.Driver.MemoryOverhead,
    +		common.SparkDriverMemory,
    +		common.SparkDriverMemoryOverhead,
    +		common.SparkDriverMemoryOverheadFactor,
    +	)
    +}
    +
    +// effectiveExecutorConfig returns the resolved memory configuration for an executor.
    +func effectiveExecutorConfig(app *v1beta2.SparkApplication) (*effectiveMemoryConfig, error) {
    +	return effectivePodConfig(
    +		app,
    +		app.Spec.Executor.Memory,
    +		app.Spec.Executor.MemoryOverhead,
    +		common.SparkExecutorMemory,
    +		common.SparkExecutorMemoryOverhead,
    +		common.SparkExecutorMemoryOverheadFactor,
    +	)
    +}
    +
    +// effectivePodConfig is the shared resolver for driver and executor.
    +//
    +// Precedence for heap:
    +//  1. CRD structured field (Memory *string) — if non-nil it is used as-is.
    +//  2. sparkConf[heapKey] — raw string from spec.SparkConf.
    +//  3. Default: common.DefaultMemoryBytes (1 GiB, matching Spark's own default).
    +//
    +// Precedence for overhead:
    +//  1. CRD structured field (MemoryOverhead *string) — explicit, factor not applied.
    +//  2. sparkConf[overheadKey] — raw string; explicit, factor not applied.
    +//  3. Default: apply overheadFactor (resolved below).
    +//
    +// Precedence for overheadFactor (see effectiveOverheadFactor):
    +//  1. sparkConf[perRoleFactorKey] — per-role key (spark.driver/executor.memoryOverheadFactor).
    +//  2. sparkConf[spark.kubernetes.memoryOverheadFactor] — cluster-wide key.
    +//  3. spec.MemoryOverheadFactor — structured CRD field.
    +//  4. Language default (0.1 JVM / 0.4 non-JVM).
    +func effectivePodConfig(
    +	app *v1beta2.SparkApplication,
    +	crdMemory *string,
    +	crdOverhead *string,
    +	heapKey string,
    +	overheadKey string,
    +	perRoleFactorKey string,
    +) (*effectiveMemoryConfig, error) {
    +	cfg := &effectiveMemoryConfig{}
    +
    +	// --- Heap ---
    +	switch {
    +	case crdMemory != nil:
    +		b, err := byteStringAsBytes(*crdMemory, DefaultUnitMiB)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to parse %s CRD field %q: %w", heapKey, *crdMemory, err)
    +		}
    +		cfg.heapBytes = b
    +	case app.Spec.SparkConf[heapKey] != "":
    +		b, err := byteStringAsBytes(app.Spec.SparkConf[heapKey], DefaultUnitMiB)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to parse sparkConf %s=%q: %w",
    +				heapKey, app.Spec.SparkConf[heapKey], err)
    +		}
    +		cfg.heapBytes = b
    +	default:
    +		cfg.heapBytes = common.DefaultMemoryBytes
    +	}
    +
    +	// --- Overhead ---
    +	switch {
    +	case crdOverhead != nil:
    +		b, err := byteStringAsBytes(*crdOverhead, DefaultUnitMiB)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to parse %s CRD field %q: %w", overheadKey, *crdOverhead, err)
    +		}
    +		cfg.memoryOverheadBytes = b
    +		cfg.overheadExplicit = true
    +	case app.Spec.SparkConf[overheadKey] != "":
    +		b, err := byteStringAsBytes(app.Spec.SparkConf[overheadKey], DefaultUnitMiB)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to parse sparkConf %s=%q: %w",
    +				overheadKey, app.Spec.SparkConf[overheadKey], err)
    +		}
    +		cfg.memoryOverheadBytes = b
    +		cfg.overheadExplicit = true
    +	default:
    +		factor, err := effectiveOverheadFactor(app, perRoleFactorKey)
    +		if err != nil {
    +			return nil, err
    +		}
    +		cfg.overheadFactor = factor
    +	}
    +
    +	return cfg, nil
    +}
    +
    +// effectiveOverheadFactor returns the memory overhead factor to use.
    +//
    +// Precedence:
    +//  1. sparkConf[perRoleFactorKey] — spark.driver.memoryOverheadFactor or
    +//     spark.executor.memoryOverheadFactor (Spark 3.3+, role-specific, highest priority).
    +//  2. sparkConf[spark.kubernetes.memoryOverheadFactor] — cluster-wide key;
    +//     wins over the CRD field because sparkConfOption runs after
    +//     memoryOverheadFactorOption in buildSparkSubmitArgs.
    +//  3. spec.MemoryOverheadFactor — structured CRD field.
    +//  4. Language default: 0.1 for JVM (Java/Scala), 0.4 for non-JVM (Python/R).
    +//
    +// The resolved factor must be a finite non-negative number; NaN, Inf, and
    +// negative values return an error.
    +func effectiveOverheadFactor(app *v1beta2.SparkApplication, perRoleFactorKey string) (float64, error) {
    +	// 1. Per-role sparkConf key (highest priority).
    +	if raw, ok := app.Spec.SparkConf[perRoleFactorKey]; ok && raw != "" {
    +		f, err := strconv.ParseFloat(raw, 64)
    +		if err != nil {
    +			return 0, fmt.Errorf("failed to parse sparkConf %s=%q: %w", perRoleFactorKey, raw, err)
    +		}
    +		if err := validateFactor(f, perRoleFactorKey); err != nil {
    +			return 0, err
    +		}
    +		return f, nil
    +	}
    +	// 2. Cluster-wide sparkConf key.
    +	if raw, ok := app.Spec.SparkConf[common.SparkKubernetesMemoryOverheadFactor]; ok && raw != "" {
    +		f, err := strconv.ParseFloat(raw, 64)

    You're doing this a lot, probably good to just break it into a function to make it easier to read.

    vjanelle vjanelle commented on code on Dec 01, 2026 22:22 UTC
    Code Review
    internal/scheduler/resourceusage/effective_config_test.go:1
    @@ -0,0 +1,567 @@
    +/*
    +Copyright The Kubeflow Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package resourceusage
    +
    +import (
    +	"fmt"
    +	"testing"
    +
    +	"github.com/stretchr/testify/assert"
    +	"github.com/stretchr/testify/require"
    +	corev1 "k8s.io/api/core/v1"
    +	"k8s.io/apimachinery/pkg/api/resource"
    +	"k8s.io/utils/ptr"
    +
    +	"github.com/kubeflow/spark-operator/v2/api/v1beta2"
    +	"github.com/kubeflow/spark-operator/v2/pkg/common"
    +)
    +
    +// TestEffectiveConfigPrecedence verifies the resolver honours the real
    +// spark-submit arg-builder precedence:
    +//
    +//   - CRD memory fields   > sparkConf memory fields    > default 1 GiB
    +//   - CRD overhead fields > sparkConf overhead fields  > factor calculation
    +//   - sparkConf factor    > CRD MemoryOverheadFactor   > language default
    +//
    +// (See effective_config.go for the full precedence rationale.)
    +func TestEffectiveConfigPrecedence(t *testing.T) {

    Use gingko please

    vjanelle vjanelle commented on code on Dec 01, 2026 22:24 UTC
    Code Review
    internal/scheduler/resourceusage/java.go:1
    @@ -0,0 +1,103 @@
    +/*
    +Copyright The Kubeflow Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package resourceusage
    +
    +import (
    +	"fmt"
    +	"math"
    +	"regexp"
    +	"strconv"
    +	"strings"
    +)
    +
    +// DefaultUnit specifies the unit Spark uses when a memory value has no suffix.
    +// Spark uses MiB for most memory settings and bytes for spark.memory.offHeap.size.
    +type DefaultUnit int
    +
    +const (
    +	// DefaultUnitMiB is used for spark.driver.memory, spark.executor.memory,
    +	// spark.driver.memoryOverhead, spark.executor.memoryOverhead, and
    +	// spark.executor.pyspark.memory.
    +	DefaultUnitMiB DefaultUnit = iota
    +	// DefaultUnitBytes is used for spark.memory.offHeap.size.
    +	DefaultUnitBytes
    +)
    +
    +var (

    this should probably go into common?

    vjanelle vjanelle commented on code on Dec 01, 2026 22:25 UTC
    Code Review
    internal/scheduler/resourceusage/java_test.go:1
    @@ -0,0 +1,122 @@
    +/*
    +Copyright The Kubeflow Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package resourceusage
    +
    +import (
    +	"testing"
    +
    +	"github.com/stretchr/testify/assert"
    +)
    +
    +func TestByteStringAsMb(t *testing.T) {

    Use gingko

    vjanelle vjanelle commented on code on Dec 01, 2026 22:26 UTC
    Code Review
    internal/scheduler/volcano/scheduler_test.go:1
    @@ -302,3 +312,742 @@ func TestSchedule(t *testing.T) {
     		})
     	}
     }
    +
    +// TestScheduleOverheadFactor is the regression test for issue #2244.
    +// It verifies that Volcano PodGroup minResources includes the default
    +// memoryOverheadFactor (0.1 for JVM, 0.4 for non-JVM) when no explicit
    +// memoryOverhead is set on the SparkApplication.
    +func TestScheduleOverheadFactor(t *testing.T) {

    these are fine asis since the original file isn't using gingko

    Reviewers
    Assignees
    Rajadi16 Rajadi16
    Labels
    risk: low confidence: 89.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: 78.5% (HIGH) · Higher = larger blast radius
    78.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: 89.7% · Lower = rushed or shallow review
    89.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: 8.1% · Safe to merge
    8.1%