fix(api): refuse minReplicas above maxReplicas on GPU class pools

CAPI starts a new pool at its min-size annotation without comparing it
with the max, so a KubernetesNodes pool whose minReplicas is above
maxReplicas has no consistent size. With class entries that also breaks
the count times maxReplicas GPUs the pool is meant to hold, so the
write is refused before it is stored.

Pools without class entries keep being admitted as before, and no
released pool can carry class entries. The check runs on the apps API
write path, so it holds for clients that never render the chart.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
Aleksei Sviridkin committed 2026-11-28 07:18:08 +03:00
1 parent 2d8af2bfe8
commit a42db84ec3
2 files changed
+163 -16

No files matched your search

+77 -16
View File
@@ -23,6 +23,7 @@ import (
"math"
"slices"
"sort"
"strconv"
"strings"
"sync"
@@ -63,6 +64,76 @@ type gpuValues struct {
MaxReplicas *int64 `json:"maxReplicas"`
}
// decodeGPUValues reads the GPU-related values of an application with the
// chart defaults applied.
func decodeGPUValues(kind string, raw []byte) (gpuValues, error) {
var v gpuValues
values := map[string]any{}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &values); err != nil {
return v, fmt.Errorf("decode %s values: %w", kind, err)
}
}
if s, ok := specSchemas.Load(kind); ok {
if err := defaultLikeKubernetes(&values, s.(*structuralschema.Structural)); err != nil {
return v, fmt.Errorf("default %s values: %w", kind, err)
}
}
defaulted, err := json.Marshal(values)
if err != nil {
return v, err
}
if err := json.Unmarshal(defaulted, &v); err != nil {
return v, fmt.Errorf("decode %s gpus: %w", kind, err)
}
return v, nil
}
// workerReplicaBounds refuses minReplicas above maxReplicas on a pool with
// class entries: CAPI starts a new pool at its min-size annotation without
// comparing it with the max, so the pool would run more GPUs than count
// times maxReplicas. minReplicas is read apart from gpuDemand's values so
// that an unreadable one cannot hide the pool's GPU demand, and a value that
// is not a whole number is refused rather than read as in range.
func workerReplicaBounds(raw []byte) field.ErrorList {
values, err := decodeGPUValues(kubernetesNodesKind, raw)
if err != nil || values.MaxReplicas == nil {
return nil
}
var bounds struct {
MinReplicas any `json:"minReplicas"`
}
if json.Unmarshal(raw, &bounds) != nil || bounds.MinReplicas == nil {
return nil
}
path := field.NewPath("spec", "minReplicas")
lowest, ok := wholeNumber(bounds.MinReplicas)
if !ok {
return field.ErrorList{field.Invalid(path, bounds.MinReplicas, "must be a whole number")}
}
if lowest <= *values.MaxReplicas {
return nil
}
return field.ErrorList{field.Invalid(path, lowest,
fmt.Sprintf("must not exceed maxReplicas (%d) on a pool with GPU class entries", *values.MaxReplicas))}
}
// wholeNumber reads a decoded JSON number, or a string of digits, as the
// integer the chart renders; 5 and 5.0 are the same value to it.
func wholeNumber(v any) (int64, bool) {
switch n := v.(type) {
case float64:
if n != math.Trunc(n) || math.Abs(n) > 1<<53 {
return 0, false
}
return int64(n), true
case string:
i, err := strconv.ParseInt(n, 10, 64)
return i, err == nil
}
return 0, false
}
// gpuDemand returns the GPU budget units an application's values reserve,
// by budget key: every class entry reserves its count under its class key
// and under the all-class key, times maxReplicas for a worker pool. Raw
@@ -71,25 +142,10 @@ func gpuDemand(kind string, raw []byte) (map[string]int64, error) {
if kind != vmInstanceKind && kind != kubernetesNodesKind {
return nil, nil
}
values := map[string]any{}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &values); err != nil {
return nil, fmt.Errorf("decode %s values: %w", kind, err)
}
}
if s, ok := specSchemas.Load(kind); ok {
if err := defaultLikeKubernetes(&values, s.(*structuralschema.Structural)); err != nil {
return nil, fmt.Errorf("default %s values: %w", kind, err)
}
}
defaulted, err := json.Marshal(values)
v, err := decodeGPUValues(kind, raw)
if err != nil {
return nil, err
}
var v gpuValues
if err := json.Unmarshal(defaulted, &v); err != nil {
return nil, fmt.Errorf("decode %s gpus: %w", kind, err)
}
classEntries := slices.ContainsFunc(v.GPUs, func(e gpuEntry) bool { return e.ClassName != "" })
replicas := int64(1)
if kind == kubernetesNodesKind && classEntries {
@@ -211,6 +267,11 @@ func (r *REST) validateGPUBudget(ctx context.Context, app, old *appsv1alpha1.App
if err != nil {
return field.ErrorList{field.Invalid(fldPath, "", err.Error())}
}
if r.kindName == kubernetesNodesKind && len(demand) > 0 {
if errs := workerReplicaBounds(specRaw(app)); len(errs) > 0 {
return errs
}
}
var previous map[string]int64
if old != nil {
// The stored values passed this check before, so a read failure
@@ -0,0 +1,86 @@
/*
Copyright 2026 The Cozystack 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 application
import (
"strings"
"testing"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
)
// CAPI starts a new pool at its min-size annotation without comparing it with
// the max, so a pool with class entries whose minReplicas is above maxReplicas
// would run more GPUs than count times maxReplicas. Pools without class
// entries keep admitting min above max.
func TestWorkerMinReplicasAboveMaxIsRefused(t *testing.T) {
registerTestSchemas(t)
for _, tc := range []struct {
name, raw string
refused bool
}{
{name: "class pool min above max", raw: `{"minReplicas":50,"maxReplicas":1,"gpus":[{"className":"h100"}]}`, refused: true},
{name: "class pool min above default max", raw: `{"minReplicas":11,"gpus":[{"className":"h100"}]}`, refused: true},
{name: "pool without GPUs keeps min above max", raw: `{"minReplicas":3,"maxReplicas":2}`},
{name: "raw-name pool keeps min above max", raw: `{"minReplicas":3,"maxReplicas":2,"gpus":[{"name":"nvidia.com/GH100_H100"}]}`},
{name: "whole-valued float min above max", raw: `{"minReplicas":5.0,"maxReplicas":1,"gpus":[{"className":"h100"}]}`, refused: true},
{name: "string min above max", raw: `{"minReplicas":"5","maxReplicas":1,"gpus":[{"className":"h100"}]}`, refused: true},
{name: "fractional min", raw: `{"minReplicas":4.5,"maxReplicas":10,"gpus":[{"className":"h100"}]}`, refused: true},
{name: "non-numeric min", raw: `{"minReplicas":"x","maxReplicas":10,"gpus":[{"className":"h100"}]}`, refused: true},
{name: "whole-valued float min equal max", raw: `{"minReplicas":3.0,"maxReplicas":3,"gpus":[{"className":"h100"}]}`},
{name: "string min below max", raw: `{"minReplicas":"1","maxReplicas":3,"gpus":[{"className":"h100"}]}`},
{name: "min equal max", raw: `{"minReplicas":2,"maxReplicas":2,"gpus":[{"className":"h100"}]}`},
{name: "min below max", raw: `{"minReplicas":1,"maxReplicas":2,"gpus":[{"className":"h100"}]}`},
{name: "defaults", raw: `{"gpus":[{"className":"h100"}]}`},
} {
t.Run(tc.name, func(t *testing.T) {
r := newAppREST(t, kubernetesNodesKind, "kubernetes-nodes-", "kubernetesnodes", tenantHelmRelease(t, "root", rootTenantNamespace, nil))
app := &appsv1alpha1.Application{
ObjectMeta: metav1.ObjectMeta{Name: "pool", Namespace: rootTenantNamespace},
Spec: &apiextv1.JSON{Raw: []byte(tc.raw)},
}
errs := r.validateGPUBudget(t.Context(), app, nil)
if !tc.refused {
if len(errs) > 0 {
t.Fatalf("refused: %v", errs)
}
return
}
if len(errs) == 0 || !strings.Contains(errs.ToAggregate().Error(), "minReplicas") {
t.Fatalf("errs = %v, want a minReplicas refusal", errs)
}
})
}
}
// A minReplicas the bounds check cannot read must not hide the pool's GPU
// demand from the pool accounting.
func TestStoredPoolWithUnreadableMinReplicasStillCounts(t *testing.T) {
registerTestSchemas(t)
stored := `{"minReplicas":"1","maxReplicas":3,"gpus":[{"className":"h100"}]}`
got, err := gpuDemand(kubernetesNodesKind, []byte(stored))
if err != nil || got[h100Key] != 3 {
t.Fatalf("gpuDemand = %v, %v; want %s reserved 3", got, err, h100Key)
}
root := tenantHelmRelease(t, "root", rootTenantNamespace, map[string]string{h100Key: "4"})
r := newVMInstanceREST(t, root, nodesRelease(t, "pool", rootTenantNamespace, stored))
errs := r.validateGPUBudget(t.Context(), vmApplication("vm", rootTenantNamespace, `{"gpus":[{"className":"h100","count":2}]}`), nil)
expectGPUErrs(t, errs, "3 is already reserved")
}