Skip to content

feat(chart): add HPA and topology spread - #677

Merged
uniqueg merged 5 commits into
devfrom
feat/627-chart-hpa-spread
Nov 4, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/627-chart-hpa-spread

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #627.

Adds a Horizontal Pod Autoscaler and topology spread rules to the Helm library chart foca-common:

  • New template file _hpa.tpl, which an app chart uses with foca-common.hpa (see examples/petstore/chart/templates/hpa.yaml). With autoscaling.enabled, the Deployment is rendered without replicas.
  • topologySpreadConstraints for the app's pods. labelSelector defaults to the selector of the pods, also where it is empty, as an empty selector counts all pods of the namespace.
  • Checks in the schema and, for charts without the schema, in the templates.
  • CI step "Check autoscaler": the release with autoscaling reaches minReplicas ready pods.
  • Docs: docs/helm-chart.md, docs/migration-0.21.md.

foca-common stays at version 0.5.0, as that isn't released yet.

Verification

  • pytest charts/foca-common/tests: 355 passed.
  • Reviewers rendered the checks with helm template 3.22.1 directly.
  • Not run locally: there is no kind here, so the install and the "Check autoscaler" step run in CI only. That the HPA raises replicas without metrics is known from the HPA controller, and CI is its first real test.

Declined review findings

  • Emit the HPA from the Deployment template automatically: the issue asks for a new template file, the docs say that without hpa.yaml the app has one pod, and the gateway example has no hpa.yaml.
  • A helper for maxReplicas symmetrical to minReplicas: optional, no behaviour.
  • The Pod Disruption Budget uses minReplicas only: maxReplicas says 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:

  • Add optional Horizontal Pod Autoscaler support for application deployments, including CPU and memory utilization targets.
  • Add configurable topology spread constraints for application pods with sensible selector defaults.

Enhancements:

  • Integrate autoscaling with deployment replica handling and PodDisruptionBudget generation.
  • Validate autoscaling and topology spread values for charts with and without the current values schema.

CI:

  • Verify in CI that releases with autoscaling create an autoscaler and reach the configured minimum number of ready pods.

Documentation:

  • Document autoscaling, topology spreading, and migration requirements for app charts.

Tests:

  • Add comprehensive template coverage for autoscaling defaults, metrics, disruption budgets, topology selectors, and invalid values.

uniqueg and others added 3 commits November 4, 2026 06:26
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]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds 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 rendering

sequenceDiagram
    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
Loading

Flow diagram for autoscaling-aware chart rendering

flowchart 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"]
Loading

File-Level Changes

Change Details Files
Adds optional HPA rendering with autoscaling-aware Deployment and PodDisruptionBudget behavior.
  • Introduces the reusable foca-common.hpa template using autoscaling/v2.
  • Omits Deployment replicas when autoscaling is enabled and derives PDB eligibility from minReplicas.
  • Supports configurable min/max replicas and CPU/memory utilization targets with CPU-80% defaults.
charts/foca-common/templates/_hpa.tpl
charts/foca-common/templates/_deployment.tpl
charts/foca-common/templates/_poddisruptionbudget.tpl
charts/foca-common/templates/_helpers.tpl
charts/foca-common/app-values.schema.json
examples/petstore/chart/templates/hpa.yaml
Adds configurable topology spread constraints to application pod templates with selector defaults.
  • Renders user-provided constraints on the Deployment pod template.
  • Fills missing or empty selectors with the app pod selector while preserving non-empty selectors.
  • Validates constraint structure and required fields both through schema and template fallbacks.
charts/foca-common/templates/_deployment.tpl
charts/foca-common/templates/_helpers.tpl
charts/foca-common/app-values.schema.json
examples/petstore/chart/values.yaml
Extends validation and regression coverage for autoscaling and topology spread settings.
  • Adds positive-integer, type, range, and compatibility validation for charts without the updated schema.
  • Tests HPA defaults, metric combinations, PDB behavior, selector filling, unchanged legacy behavior, and invalid values.
charts/foca-common/templates/_helpers.tpl
charts/foca-common/templates/_hpa.tpl
charts/foca-common/tests/test_templates.py
charts/foca-common/app-values.schema.json
examples/petstore/chart/values.schema.json
Updates the petstore example, documentation, and migration guidance for the new opt-in features.
  • Enables autoscaling and topology spreading in CI test values and adds the example HPA template.
  • Documents configuration, defaults, metrics-server/resource-request requirements, upgrade caveats, and pre-0.5.0 chart migration steps.
examples/petstore/chart/ci/test-values.yaml
examples/petstore/chart/templates/hpa.yaml
examples/petstore/chart/values.yaml
docs/helm-chart.md
docs/migration-0.21.md
charts/foca-common/Chart.yaml
Adds CI verification that an autoscaled release creates an HPA and reaches its configured minimum ready replicas.
  • Checks that exactly one HPA exists in the installed namespace.
  • Waits for the HPA target Deployment to report two ready replicas.
.github/actions/install-chart/action.yml

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3986da8) to head (53abeb9).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #677   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           58        58           
  Lines         7499      7499           
=========================================
  Hits          7499      7499           
Flag Coverage Δ
test_unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 06:06

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@uniqueg
uniqueg merged commit a1c04d0 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/627-chart-hpa-spread branch November 4, 2026 07:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(chart): add HPA and topology spread

1 participant