fix(volcano): apply default memoryOverheadFactor to PodGroup minResources #3196
[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:
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"]} -->
🎉 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:
Join the community:
Feel free to ask questions in the comments if you need any help or clarification!
Thanks again for contributing to Kubeflow! 🙏
@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>
/ok-to-test
Please use this template instead.
The present initial executor number calculation does not take spark conf into account.
Please rewrite GetInitialExecutorNumber to form a precedence rule using both spark conf and CRD field.
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.
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)
}
}
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})
}
Hi @Rajadi16! Thanks for raising the PR. I have added a few suggestions for changes.
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/.
Same fix as above, in 4cda5b1. The test file now uses the Kubeflow boilerplate header.
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.
Done in e3512d7. byteStringAsBytes now takes a DefaultUnit parameter:
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.
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.
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.
@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?
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
@Rajadi16 please update the PR description with the current changes
Thanks @RobuRishabh, good catch. Fixed in 88fdff3:
The PR description is also updated. Could you take another look and resolve this thread if it looks good?
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?
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?
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.
Hi @Rajadi16 thanks for the contribution, I left some comments, PTAL
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.
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.
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.
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.
@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.
@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.
@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?
This import swap changes YuniKorn behavior beyond the PR's stated scope ("YuniKorn already handled the overhead correctly"):
All improvements IMO, but existing YuniKorn users will see different reservations worth a release-note callout.
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.
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.
@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?
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.
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.
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.
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.
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>.
@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.
You're doing this a lot, probably good to just break it into a function to make it easier to read.
Use gingko please
this should probably go into common?
Use gingko
these are fine asis since the original file isn't using gingko
tariq-hasan
Rajadi16
Fixes #2244
Problem
When
spec.driver.memoryOverhead/spec.executor.memoryOverheadare not set (or memory itself is omitted), Volcano's PodGroupminResourcesunder-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 insparkConf. YuniKorn already handled the overhead correctly.Changes
internal/scheduler/yunikorn/resourceusagetointernal/scheduler/resourceusage(pure rename, own commit), shared by YuniKorn and Volcano.effective_config.go: one resolver for driver and executor memory settings, following the spark-submit argument order frombuildSparkSubmitArgs.- Heap: CRD > sparkConf > default 1 GiB
- memoryOverhead: CRD > sparkConf > factor-based (
max(heapfactor, 384Mi))- Factor: sparkConf
spark.{driver,executor}.memoryOverheadFactor> sparkConfspark.kubernetes.memoryOverheadFactor>spec.memoryOverheadFactor> language default (0.1 JVM / 0.4 Python/R)- Factors must be finite, non-negative and <= 1000.
ToResourceList,DriverPodResourceList,ExecutorPodResourceList; Volcano uses these instead ofpkg/util.GetRequestResource.spark.memory.offHeap.size) viabyteStringAsBytes, with int64 overflow guards.util.GetInitialExecutorNumbernow reads sparkConf (spark.executor.instances, dynamic allocation min/initial executors); CRD wins; negatives are clamped.spec.batchSchedulerOptions.resourcesoverrides before computing anything.minResourcesby direct, constant-space multiplication with an overflow-safemultiplyQuantity(clear error on int64 overflow). There is no executor-count cap.Behavior changes (see CHANGELOG.md, Unreleased)
memoryreserves the 1 GiB default heap (previously 0 heap + 384Mi overhead for YuniKorn).spark.executor.memory: "2gb") now fails scheduling and aborts submission instead of running with an under-reserved PodGroup. Workaround: fix the value, or setspec.batchSchedulerOptions.resources, which bypasses the calculation. The webhook does not validate these strings by default.spark.{driver,executor}.memoryOverheadFactor(SPARK-38194) are ignored by Spark <= 3.2 but honored by the operator, which over-reserves there. Usespark.kubernetes.memoryOverheadFactororspec.memoryOverheadFactoron older Spark.Tests
TestScheduleOverheadFactor,TestToResourceList,TestExecutorMinResources(including the overflow boundary),TestMultiplyQuantity,GetInitialExecutorNumbertable, byte-string overflow boundaries.Not in this PR
pkg/util.Get*RequestResource(kubescheduler/scheduler.go:90) and has the same under-reservation bug. Tracked in #XXXX.getResourceListinresourcequota.go), not the shared package. It ignores sparkConf and dynamic allocation and uses a 0 heap whenspec.memoryis omitted. See #3207 for the Scala JVM-factor part.Builds on #2262 by @kaka-zb.