Repository navigation
feat(chart): add HPA and topology spread - #677
Conversation
Add autoscaling per app values key, in the names of `helm create`, on CPU and memory, instead of replicas, and topologySpreadConstraints with labelSelector filled in if omitted. The budget counts minReplicas with autoscaling. Closes #627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refuse spread rules without their required fields, and fill in empty labelSelector, which would mean all pods of the namespace. Correct the docs for charts without the template and for scaling to 0. CI checks that the autoscaler raises the Deployment to minReplicas. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fill in the selector of the app's pods also for selectors with empty matchLabels or matchExpressions, as they select the whole namespace. Check the fields of the rules in the schema, and refuse a maxSkew of 0 and non-map selectors in charts without it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAdds opt-in HPA and topology spread support to the shared Helm library, including autoscaling-aware Deployment/PDB rendering, selector and schema validation, comprehensive tests and documentation, an updated petstore example, and CI installation coverage. Sequence diagram for HPA-managed deployment renderingsequenceDiagram
participant Helm
participant HPA as HorizontalPodAutoscaler
participant Deployment
participant Kubernetes
Helm->>Helm: autoscalingEnabled
Helm->>Deployment: Render without replicas
Helm->>HPA: foca-common.hpa
HPA->>Deployment: Scale between minReplicas and maxReplicas
Kubernetes->>Deployment: Schedule pods using topologySpreadConstraints
Flow diagram for autoscaling-aware chart renderingflowchart TD
Start["Render app chart"] --> Enabled{"autoscaling.enabled?"}
Enabled -->|No| Replicas["Render Deployment replicas"]
Enabled -->|Yes| Omit["Omit Deployment replicas"]
Omit --> HPA["Render HorizontalPodAutoscaler"]
HPA --> Bounds["Use minReplicas and maxReplicas"]
Replicas --> PDB["Render PDB from replicas when applicable"]
Bounds --> PDB2["Render PDB from minReplicas when applicable"]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #677 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 58 58
Lines 7499 7499
=========================================
Hits 7499 7499
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="charts/foca-common/templates/_helpers.tpl" line_range="234" />
<code_context>
+{{- $selector := include "foca-common.selectorLabels" (dict "root" $root "component" "app") | fromYaml -}}
+{{- $filled := list -}}
+{{- range $constraints -}}
+{{- if not (and (kindIs "map" .) .maxSkew .topologyKey .whenUnsatisfiable) -}}
+{{- fail (printf "%s.topologySpreadConstraints must be a list of TopologySpreadConstraint, each with maxSkew of at least 1, topologyKey and whenUnsatisfiable" $key) -}}
+{{- end -}}
</code_context>
<issue_to_address>
**Invalid spread rules reach Kubernetes**
When a chart uses the template validation path without the updated values schema and supplies a truthy but invalid required field, `foca-common.topologySpreadConstraints` checks only truthiness, so invalid values such as a fractional or string `maxSkew` or unsupported `whenUnsatisfiable` are rendered; Kubernetes rejects the Deployment and the Helm install or upgrade fails.
Validate the required fields’ types and allowed values in the template before rendering the constraint.
Also at `charts/foca-common/templates/_helpers.tpl:235`, `charts/foca-common/templates/_helpers.tpl:240`.
</issue_to_address>
### Comment 2
<location path="charts/foca-common/templates/_helpers.tpl" line_range="240-241" />
<code_context>
+{{- $constraint := deepCopy . -}}
+{{- $given := $constraint.labelSelector -}}
+{{- if not (or (kindIs "invalid" $given) (kindIs "map" $given)) -}}
+{{- fail (printf "%s.topologySpreadConstraints: labelSelector must be a map" $key) -}}
+{{- end -}}
+{{- if not (and $given (or $given.matchLabels $given.matchExpressions)) -}}
+{{- $_ := set $constraint "labelSelector" (dict "matchLabels" $selector) -}}
</code_context>
<issue_to_address>
**Malformed selectors pass chart validation**
When a chart supplies a nonempty selector object whose nested `matchLabels` or `matchExpressions` fields are malformed, a nonempty `labelSelector` map with an invalid nested structure, such as a non-string `matchLabels` value, passes the map check and is emitted; Kubernetes rejects the Deployment when the chart is installed or upgraded.
Validate the nested selector structure in the schema and in the helper for charts without the updated schema.
</issue_to_address>
### Comment 3
<location path="charts/foca-common/templates/_deployment.tpl" line_range="22-24" />
<code_context>
{{- include "foca-common.labels" (dict "root" $root "component" "app") | nindent 4 }}
spec:
progressDeadlineSeconds: 600
+ {{- if ne (include "foca-common.autoscalingEnabled" .) "true" }}
replicas: {{ include "foca-common.replicas" . }}
+ {{- end }}
revisionHistoryLimit: 10
selector:
</code_context>
<issue_to_address>
**Failed upgrades leave one pod**
When a non-atomic Helm install or upgrade is interrupted, or HPA creation fails, after the Deployment is applied but before the HPA is created, `foca-common.deployment` has already omitted `replicas`, so Kubernetes defaults the Deployment to one replica while no HPA exists; a non-atomic Helm operation leaves that partial state in place, and users see reduced capacity until a later successful release.
Keep the configured replicas during the transition until the HPA exists, or require atomic Helm operations when enabling autoscaling.
</issue_to_address>Linked issues
#627 feat(chart): add HPA and topology spread · 7 of 8 met · 1 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add autoscaling under each app values key while keeping replicas | ✅ Met | The new settings use the app values key; replicas remains available when autoscaling is disabled. |
| 2 | Render an HPA for CPU and memory autoscaling, without Deployment replicas when enabled | ✅ Met | The HPA template supports CPU and memory targets, with CPU at 80% as the fallback, and the Deployment omits replicas when autoscaling is enabled. |
| 3 | Pass through topology spread constraints and default the labelSelector to the app pods | ✅ Met | The helper preserves nonempty selectors and supplies the app pod selector when the selector is absent or empty. |
| 4 | Add the HPA template, petstore example files, and schema | ✅ Met | The change adds the shared HPA template, the petstore HPA template and values, and schema updates for both charts. |
| 5 | Document the metrics-server requirement and startup-work caveat | ✅ Met | The Helm chart documentation describes both. |
| 6 | Document that app charts need to add the new template file | ✅ Met | The migration guide and Helm chart documentation explain the template-file requirement. |
| 7 | Test unchanged default rendering, omitted replicas with HPA, and spread selector defaulting | ✅ Met | Tests cover default rendering, HPA rendering without Deployment replicas, and defaulting selectors for absent and empty selectors. |
| 8 | Pass the kind install of petstore with autoscaling enabled | 👀 Check by hand (runtime) | The CI action now checks that the installed release has an HPA and reaches two ready replicas, but a person must confirm the kind CI run passes. |
Sourcery assessment
Approval pending. 3 findings to address first.
Blocking findings: charts/foca-common/templates/_helpers.tpl:234, charts/foca-common/templates/_helpers.tpl:241, charts/foca-common/templates/_deployment.tpl:24
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="charts/foca-common/templates/_helpers.tpl" line_range="234-235" />
<code_context>
+{{- $selector := include "foca-common.selectorLabels" (dict "root" $root "component" "app") | fromYaml -}}
+{{- $filled := list -}}
+{{- range $constraints -}}
+{{- if not (and (kindIs "map" .) .maxSkew .topologyKey .whenUnsatisfiable) -}}
+{{- fail (printf "%s.topologySpreadConstraints must be a list of TopologySpreadConstraint, each with maxSkew of at least 1, topologyKey and whenUnsatisfiable" $key) -}}
+{{- end -}}
+{{- $constraint := deepCopy . -}}
</code_context>
<issue_to_address>
**Invalid spread constraints reach Kubernetes**
When an app chart without the updated schema supplies truthy but invalid constraint fields, the `topologySpreadConstraints` helper checks required fields for truthiness and `labelSelector` for being a map, but does not validate their types, ranges, or selector fields. Invalid values pass through to the Deployment, Kubernetes rejects it, and the install or upgrade fails.
Validate the required fields and selector structure before emitting each constraint.
Also at `charts/foca-common/templates/_helpers.tpl:239-240`.
</issue_to_address>
### Comment 2
<location path="charts/foca-common/templates/_helpers.tpl" line_range="172" />
<code_context>
+*/}}
+{{- define "foca-common.checkPositive" -}}
+{{- $integer := or (kindIs "int" .value) (kindIs "int64" .value) (and (kindIs "float64" .value) (eq .value (floor .value))) -}}
+{{- if not (and $integer (ge (int .value) 1)) -}}
+{{- fail (printf "%s must be a whole number of at least 1" .key) -}}
+{{- end -}}
</code_context>
<issue_to_address>
**Oversized HPA values fail installation**
When an HPA replica count or utilization target exceeds 2147483647, `checkPositive` rejects nonpositive and nonintegral values but has no upper bound, so oversized `minReplicas`, `maxReplicas`, or utilization targets render into the HPA. Kubernetes represents these fields as int32 and rejects values above 2147483647, so the release cannot install or upgrade.
Reject values above 2147483647 in both the schema and `checkPositive`.
</issue_to_address>
### Comment 3
<location path=".github/actions/install-chart/action.yml" line_range="135" />
<code_context>
+ target="$(kubectl get hpa -n "${NAMESPACE}" -o json \
+ | jq -r '.items[0].spec.scaleTargetRef.name')"
+ kubectl wait "deployment/${target}" -n "${NAMESPACE}" \
+ --for=jsonpath='{.status.readyReplicas}'=2 --timeout=300s
# The release of `ci/gateway-values.yaml` via the Gateway (port
# forwarding to the Envoy proxy's Service): HTTP is redirected to HTTPS,
</code_context>
<issue_to_address>
**Chart CI waits for unavailable replicas**
When the kind cluster has no metrics-server, the HPA cannot obtain CPU metrics and leaves the Deployment at one replica, so `kubectl wait` for two ready replicas times out and chart-install and release CI fail.
Provide metrics-server in the kind cluster or change the CI check so it does not wait for HPA-driven replicas when metrics are unavailable.
</issue_to_address>
### Comment 4
<location path=".github/actions/install-chart/action.yml" line_range="135" />
<code_context>
+ target="$(kubectl get hpa -n "${NAMESPACE}" -o json \
+ | jq -r '.items[0].spec.scaleTargetRef.name')"
+ kubectl wait "deployment/${target}" -n "${NAMESPACE}" \
+ --for=jsonpath='{.status.readyReplicas}'=2 --timeout=300s
# The release of `ci/gateway-values.yaml` via the Gateway (port
# forwarding to the Envoy proxy's Service): HTTP is redirected to HTTPS,
</code_context>
<issue_to_address>
**Autoscaler check misses readiness**
When CPU metrics are available and the HPA scales directly to its maximum before the check observes exactly two ready replicas, `kubectl wait` requires `readyReplicas` to equal 2; if the HPA scales to 3 before the wait observes exactly 2 ready pods, the check times out even though the minimum is met.
Poll until `readyReplicas` is greater than or equal to the configured minimum instead of waiting for equality.
</issue_to_address>
### Comment 5
<location path="charts/foca-common/templates/_poddisruptionbudget.tpl" line_range="4" />
<code_context>
PodDisruptionBudget of the app, if `<valuesKey>.podDisruptionBudget.enabled`
-(true if not set) and the app has more than one pod (`<valuesKey>.replicas`):
+(true if not set) and the app has more than one pod (`<valuesKey>.replicas`,
+or at least with autoscaling, `minReplicas`):
voluntary disruptions (e.g., node drains) evict at most `maxUnavailable` pods
at once (1 if neither it nor `minAvailable` is set), or keep at least
</code_context>
<issue_to_address>
**Schema misstates budget condition**
When autoscaling is enabled with `minReplicas` greater than one and fixed `replicas` is one, `foca-common.podDisruptionBudget` renders a budget when autoscaling is enabled and `minReplicas` is greater than one, even if fixed `replicas` is one. The copied app-values schema still tells chart users the budget depends on `replicas`, so its published description misleads consumers configuring autoscaling.
Update the `podDisruptionBudget.enabled` schema description to mention `minReplicas` when autoscaling is enabled.
</issue_to_address>Linked issues
#627 feat(chart): add HPA and topology spread · 6 of 7 met · 1 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add per-app autoscaling settings in the helm create shape while keeping replicas available. |
✅ Met | The app values and schema define autoscaling and retain replicas; autoscaling is disabled by default. |
| 2 | Render an HPA on CPU and memory, and omit Deployment replicas when autoscaling is enabled. |
✅ Met | The HPA template renders autoscaling/v2 with CPU and/or memory targets and the documented defaults; the Deployment conditionally omits replicas. |
| 3 | Pass through topology spread constraints and fill in the app pod selector when labelSelector is omitted or empty. |
✅ Met | The helper supplies the app selector for absent and empty selectors, and the tests cover both cases. |
| 4 | Add the HPA template, petstore example and schema, and validation for the new values. | ✅ Met | The example includes an HPA template and autoscaling/spread values; both schemas define the new settings, and templates validate values for charts without the updated schema. |
| 5 | Document metrics-server and startup-work considerations, and explain the app-chart migration. | ✅ Met | The Helm chart docs cover metrics-server, startup work, and adding the HPA template; the migration guide covers the schema and template updates. |
| 6 | Test unchanged default rendering, HPA replica omission, and spread selector defaulting. | ✅ Met | New chart tests cover the default feature state, omission of Deployment replicas with autoscaling, and selector defaulting. |
| 7 | Pass the kind install of petstore with autoscaling enabled. | 👀 Check by hand (runtime) | The install action now checks that the autoscaler exists and its Deployment reaches two ready replicas, but a person must confirm that the kind install CI run passes. |
Sourcery assessment
Needs a human reviewer. 4 findings to address first, and when autoscaling is enabled, the Deployment no longer declares a replica count and the HPA controls pod capacity from available CPU or memory metrics. If its targets or cluster metrics lead to too few pods, the app can become unavailable before reverting removes the HPA; reverting cannot undo downtime that has already occurred.
Blocking findings: charts/foca-common/templates/_helpers.tpl:235, charts/foca-common/templates/_helpers.tpl:172, .github/actions/install-chart/action.yml:135, .github/actions/install-chart/action.yml:135
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #627.
Adds a Horizontal Pod Autoscaler and topology spread rules to the Helm library chart
foca-common:_hpa.tpl, which an app chart uses withfoca-common.hpa(seeexamples/petstore/chart/templates/hpa.yaml). Withautoscaling.enabled, the Deployment is rendered withoutreplicas.topologySpreadConstraintsfor the app's pods.labelSelectordefaults to the selector of the pods, also where it is empty, as an empty selector counts all pods of the namespace.minReplicasready pods.docs/helm-chart.md,docs/migration-0.21.md.foca-commonstays at version 0.5.0, as that isn't released yet.Verification
pytest charts/foca-common/tests: 355 passed.helm template3.22.1 directly.Declined review findings
hpa.yamlthe app has one pod, and the gateway example has nohpa.yaml.maxReplicassymmetrical tominReplicas: optional, no behaviour.minReplicasonly:maxReplicassays nothing about what is available.🤖 Generated with Claude Code
Summary by Sourcery
Enable application autoscaling and topology-aware pod spreading in the shared Helm chart.
New Features:
Enhancements:
CI:
Documentation:
Tests: