diff --git a/.github/test_topology_spread_constraints.py b/.github/test_topology_spread_constraints.py new file mode 100644 index 00000000..c37d99ee --- /dev/null +++ b/.github/test_topology_spread_constraints.py @@ -0,0 +1,171 @@ +"""Render checks for topologySpreadConstraints selectors and override order.""" + +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +sys.dont_write_bytecode = True + +OPTION_FILE = "charts/retool/ci/test-topology-spread-constraints-option.yaml" +# Deployments that read the global list in the option file. +SPREAD_DEPLOYMENTS = ( + "retool", + "retool-workflow-backend", + "retool-workflow-worker", + "retool-agent-worker", + "retool-agent-eval-worker", +) +CODE_EXECUTOR = "retool-code-executor" +ZONE = "topology.kubernetes.io/zone" +HOSTNAME = "kubernetes.io/hostname" + + +def render(*extra_values): + """Render the chart with the install values, the option file, and extra YAML snippets.""" + command = [ + "helm", "template", "retool", "charts/retool", + "--values", "charts/retool/ci/test-install-values.yaml", + "--values", OPTION_FILE, + ] + with tempfile.TemporaryDirectory() as tmp: + for index, snippet in enumerate(extra_values): + path = Path(tmp) / f"extra-{index}.yaml" + path.write_text(snippet) + command.extend(("--values", str(path))) + return subprocess.check_output(command, cwd=ROOT, text=True) + + +def deployments(output): + """Map Deployment name to its manifest text.""" + found = {} + for document in output.split("\n---\n"): + if "\nkind: Deployment\n" not in f"\n{document}\n": + continue + metadata = document.split("\nmetadata:\n", 1)[1] + name = next(line.split(":", 1)[1].strip() for line in metadata.splitlines() if line.startswith(" name:")) + found[name] = document + return found + + +def block(text, header, indent): + """Return the lines nested under `header` (deeper than `indent` spaces).""" + lines = text.splitlines() + start = lines.index(header) + 1 + nested = [] + for line in lines[start:]: + if line.strip() and len(line) - len(line.lstrip()) <= indent: + break + nested.append(line) + return nested + + +def labels(lines): + return dict(line.strip().split(": ", 1) for line in lines if line.strip()) + + +def selector(deployment): + return labels(block(deployment, " matchLabels:", 4)) + + +def constraints(deployment): + """Parse the pod's topologySpreadConstraints into dicts with a matchLabels entry.""" + if " topologySpreadConstraints:" not in deployment.splitlines(): + return [] + entries = [] + for line in block(deployment, " topologySpreadConstraints:", 6): + if line.startswith(" - "): + entries.append([]) + line = " " + line[len(" - "):] + entries[-1].append(line) + parsed = [] + for entry in entries: + text = "\n".join(entry) + item = { + line.strip().split(": ", 1)[0]: line.strip().split(": ", 1)[1] + for line in entry + if line.startswith(" ") and not line.startswith(" ") and ": " in line + } + item["matchLabels"] = labels(block(text, " matchLabels:", 12)) if "matchLabels:" in text else {} + parsed.append(item) + return parsed + + +class TopologySpreadConstraintsTests(unittest.TestCase): + def test_default_renders_no_constraints(self): + output = subprocess.check_output( + ["helm", "template", "retool", "charts/retool", + "--values", "charts/retool/ci/test-install-values.yaml", + "--set", "workflows.enabled=true", "--set", "agents.enabled=true", + "--set", "codeExecutor.enabled=true"], + cwd=ROOT, text=True, + ) + self.assertNotIn("topologySpreadConstraints", output) + + def test_global_list_selects_each_component_own_pods(self): + rendered = deployments(render()) + for name in SPREAD_DEPLOYMENTS: + with self.subTest(deployment=name): + deployment = rendered[name] + spread = constraints(deployment) + self.assertEqual([c["topologyKey"] for c in spread], [ZONE, HOSTNAME]) + self.assertEqual([c["whenUnsatisfiable"] for c in spread], ["DoNotSchedule", "ScheduleAnyway"]) + for constraint in spread: + self.assertEqual(constraint["matchLabels"], selector(deployment)) + selectors = [tuple(sorted(selector(rendered[name]).items())) for name in SPREAD_DEPLOYMENTS] + self.assertEqual(len(set(selectors)), len(selectors), "components must not share a selector") + + def test_explicit_label_selector_is_kept(self): + spread = constraints(deployments(render())[CODE_EXECUTOR]) + self.assertEqual(len(spread), 1) + self.assertEqual(spread[0]["whenUnsatisfiable"], "ScheduleAnyway") + self.assertEqual(spread[0]["matchLabels"], {"example.com/spread-group": "code-executor"}) + + def test_worker_override_applies_to_that_worker_only(self): + rendered = deployments(render( + "agents:\n" + " evalWorker:\n" + " topologySpreadConstraints:\n" + " - maxSkew: 3\n" + " topologyKey: kubernetes.io/hostname\n" + " whenUnsatisfiable: ScheduleAnyway\n" + )) + eval_worker = constraints(rendered["retool-agent-eval-worker"]) + self.assertEqual([(c["topologyKey"], c["maxSkew"]) for c in eval_worker], [(HOSTNAME, "3")]) + self.assertEqual(eval_worker[0]["matchLabels"], selector(rendered["retool-agent-eval-worker"])) + for name in ("retool-agent-worker", "retool-workflow-worker"): + with self.subTest(deployment=name): + self.assertEqual([c["topologyKey"] for c in constraints(rendered[name])], [ZONE, HOSTNAME]) + + def test_parent_override_applies_to_its_workers(self): + rendered = deployments(render( + "agents:\n" + " topologySpreadConstraints:\n" + " - maxSkew: 4\n" + " topologyKey: topology.kubernetes.io/zone\n" + " whenUnsatisfiable: DoNotSchedule\n" + )) + for name in ("retool-agent-worker", "retool-agent-eval-worker"): + with self.subTest(deployment=name): + self.assertEqual([c["maxSkew"] for c in constraints(rendered[name])], ["4"]) + self.assertEqual([c["maxSkew"] for c in constraints(rendered["retool-workflow-worker"])], ["1", "2"]) + + def test_empty_override_disables_constraints(self): + rendered = deployments(render( + "agents:\n" + " evalWorker:\n" + " topologySpreadConstraints: []\n" + "codeExecutor:\n" + " topologySpreadConstraints: []\n" + )) + for name in ("retool-agent-eval-worker", CODE_EXECUTOR): + with self.subTest(deployment=name): + self.assertEqual(constraints(rendered[name]), []) + self.assertEqual(len(constraints(rendered["retool-agent-worker"])), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bc778163..8f47b311 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -111,6 +111,8 @@ jobs: python3 .github/test_global_pod_scheduling.py - name: Verify js-executor capabilities and iptables env by version run: python3 .github/test_js_executor_capabilities.py + - name: Verify topologySpreadConstraints selectors and override order + run: python3 .github/test_topology_spread_constraints.py kubeconform-chart: if: needs.changed.outputs.run == 'true' diff --git a/charts/retool/Chart.yaml b/charts/retool/Chart.yaml index 224769fa..af622cf9 100644 --- a/charts/retool/Chart.yaml +++ b/charts/retool/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: retool description: Deploy self-hosted Retool on Kubernetes. type: application -version: 6.14.2 +version: 6.14.3 maintainers: - name: Retool Engineering email: engineering+helm@retool.com diff --git a/charts/retool/ci/test-topology-spread-constraints-option.yaml b/charts/retool/ci/test-topology-spread-constraints-option.yaml new file mode 100644 index 00000000..4f1b5e2e --- /dev/null +++ b/charts/retool/ci/test-topology-spread-constraints-option.yaml @@ -0,0 +1,22 @@ +workflows: + enabled: true +agents: + enabled: true +codeExecutor: + enabled: true + # Component override with an explicit labelSelector, which is kept as-is. + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + example.com/spread-group: code-executor +# Global list without labelSelector: each component gets its own selector labels. +topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: DoNotSchedule + - maxSkew: 2 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway diff --git a/charts/retool/templates/_helpers.tpl b/charts/retool/templates/_helpers.tpl index 7c334a56..9a3df117 100644 --- a/charts/retool/templates/_helpers.tpl +++ b/charts/retool/templates/_helpers.tpl @@ -1915,3 +1915,38 @@ Usage: (include "retool.jsExecutor.requireNetAdminAndInstallIptables" .) {{- fail (printf "rr.jsExecutor.requireNetAdminAndInstallIptables must be true, false, or null (got %s)" (kindOf $flag)) -}} {{- end -}} {{- end -}} + +{{/* +Render the topologySpreadConstraints of one component. +"sources" lists the values blocks to read, most specific first (for example +the worker block, then its parent block, then .Values). The first block that +sets the topologySpreadConstraints key wins, so an explicit empty list +disables constraints for that component. Blocks without the key fall through. +A constraint that sets no labelSelector gets the component's selector labels, +so a single list (for example the global .Values.topologySpreadConstraints) +spreads each component on its own pods only. +Renders nothing when the resolved list is empty. +Usage: + include "retool.topologySpreadConstraints" (dict "sources" (list .Values.workflows .Values) "selectorLabels" (include "retool.workflowBackend.selectorLabels" . | fromYaml)) +*/}} +{{- define "retool.topologySpreadConstraints" -}} +{{- $constraints := list -}} +{{- $found := false -}} +{{- range $source := .sources -}} +{{- if and (not $found) (kindIs "map" $source) (hasKey $source "topologySpreadConstraints") -}} +{{- $constraints = $source.topologySpreadConstraints | default list -}} +{{- $found = true -}} +{{- end -}} +{{- end -}} +{{- $out := list -}} +{{- range $constraints -}} +{{- $c := deepCopy . -}} +{{- if not (hasKey $c "labelSelector") -}} +{{- $_ := set $c "labelSelector" (dict "matchLabels" $.selectorLabels) -}} +{{- end -}} +{{- $out = append $out $c -}} +{{- end -}} +{{- if $out -}} +{{- toYaml $out -}} +{{- end -}} +{{- end -}} diff --git a/charts/retool/templates/_workers.tpl b/charts/retool/templates/_workers.tpl index 3433ccbf..9c238273 100644 --- a/charts/retool/templates/_workers.tpl +++ b/charts/retool/templates/_workers.tpl @@ -446,6 +446,11 @@ spec: {{- if $affinity }} affinity: {{ toYaml $affinity | indent 8 }} + {{- end }} + {{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list $workerValues $parentValues $.Values) "selectorLabels" (include (printf "retool.%sWorker.selectorLabels" $workerType) $ | fromYaml)) }} + {{- if $topologySpreadConstraints }} + topologySpreadConstraints: +{{ $topologySpreadConstraints | indent 8 }} {{- end }} {{- if $.Values.nodeSelector }} nodeSelector: diff --git a/charts/retool/templates/deployment_backend.yaml b/charts/retool/templates/deployment_backend.yaml index 033f2fc5..ad944ad2 100644 --- a/charts/retool/templates/deployment_backend.yaml +++ b/charts/retool/templates/deployment_backend.yaml @@ -442,6 +442,11 @@ spec: {{- if .Values.affinity }} affinity: {{ toYaml .Values.affinity | indent 8 }} + {{- end }} + {{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list .Values) "selectorLabels" (include "retool.selectorLabels" . | fromYaml)) }} + {{- if $topologySpreadConstraints }} + topologySpreadConstraints: +{{ $topologySpreadConstraints | indent 8 }} {{- end }} {{- if .Values.nodeSelector }} nodeSelector: diff --git a/charts/retool/templates/deployment_code_executor.yaml b/charts/retool/templates/deployment_code_executor.yaml index a89aace2..0cce88e3 100644 --- a/charts/retool/templates/deployment_code_executor.yaml +++ b/charts/retool/templates/deployment_code_executor.yaml @@ -260,6 +260,11 @@ spec: affinity: {{ toYaml .Values.codeExecutor.affinity | indent 8 }} {{- end }} +{{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list .Values.codeExecutor .Values) "selectorLabels" (include "retool.codeExecutor.selectorLabels" . | fromYaml)) }} +{{- if $topologySpreadConstraints }} + topologySpreadConstraints: +{{ $topologySpreadConstraints | indent 8 }} +{{- end }} {{- if .Values.nodeSelector }} nodeSelector: {{ toYaml .Values.nodeSelector | indent 8 }} diff --git a/charts/retool/templates/deployment_workflows.yaml b/charts/retool/templates/deployment_workflows.yaml index 8e0bfc9f..9c46ef84 100644 --- a/charts/retool/templates/deployment_workflows.yaml +++ b/charts/retool/templates/deployment_workflows.yaml @@ -338,6 +338,11 @@ spec: {{- if .Values.affinity }} affinity: {{ toYaml .Values.affinity | indent 8 }} + {{- end }} + {{- $topologySpreadConstraints := include "retool.topologySpreadConstraints" (dict "sources" (list .Values.workflows.backend .Values.workflows .Values) "selectorLabels" (include "retool.workflowBackend.selectorLabels" . | fromYaml)) }} + {{- if $topologySpreadConstraints }} + topologySpreadConstraints: +{{ $topologySpreadConstraints | indent 8 }} {{- end }} {{- if .Values.nodeSelector }} nodeSelector: diff --git a/charts/retool/values.yaml b/charts/retool/values.yaml index 5b46beee..72338ed5 100644 --- a/charts/retool/values.yaml +++ b/charts/retool/values.yaml @@ -463,6 +463,31 @@ affinity: # @schema hidden tolerations: [] +# Topology spread constraints for pod assignment. Applies to the main backend, +# the workflow backend, the workflow and agent workers, and the code executor. +# A constraint without a labelSelector gets the selector labels of the pod's own +# component, so a single list spreads each component independently. +# Per-component overrides. The most specific block that sets the key wins and +# replaces this list. Set an override to [] to disable constraints for that +# component; leave it unset to inherit: +# workflows.topologySpreadConstraints (workflow backend and workflow workers) +# workflows.backend.topologySpreadConstraints +# workflows.worker.topologySpreadConstraints +# agents.topologySpreadConstraints (agent and agent eval workers) +# agents.worker.topologySpreadConstraints +# agents.evalWorker.topologySpreadConstraints +# codeExecutor.topologySpreadConstraints +# Ref: https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/ +# Not yet annotated: excluded from values.schema.json and README.md. +# @schema hidden +topologySpreadConstraints: [] +# - maxSkew: 1 +# topologyKey: topology.kubernetes.io/zone +# whenUnsatisfiable: DoNotSchedule +# - maxSkew: 2 +# topologyKey: kubernetes.io/hostname +# whenUnsatisfiable: ScheduleAnyway + # Node labels for pod assignment # Ref: https://kubernetes.io/docs/user-guide/node-selection/ # Not yet annotated: excluded from values.schema.json and README.md. diff --git a/values.yaml b/values.yaml index 5b46beee..72338ed5 100644 --- a/values.yaml +++ b/values.yaml @@ -463,6 +463,31 @@ affinity: # @schema hidden tolerations: [] +# Topology spread constraints for pod assignment. Applies to the main backend, +# the workflow backend, the workflow and agent workers, and the code executor. +# A constraint without a labelSelector gets the selector labels of the pod's own +# component, so a single list spreads each component independently. +# Per-component overrides. The most specific block that sets the key wins and +# replaces this list. Set an override to [] to disable constraints for that +# component; leave it unset to inherit: +# workflows.topologySpreadConstraints (workflow backend and workflow workers) +# workflows.backend.topologySpreadConstraints +# workflows.worker.topologySpreadConstraints +# agents.topologySpreadConstraints (agent and agent eval workers) +# agents.worker.topologySpreadConstraints +# agents.evalWorker.topologySpreadConstraints +# codeExecutor.topologySpreadConstraints +# Ref: https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/ +# Not yet annotated: excluded from values.schema.json and README.md. +# @schema hidden +topologySpreadConstraints: [] +# - maxSkew: 1 +# topologyKey: topology.kubernetes.io/zone +# whenUnsatisfiable: DoNotSchedule +# - maxSkew: 2 +# topologyKey: kubernetes.io/hostname +# whenUnsatisfiable: ScheduleAnyway + # Node labels for pod assignment # Ref: https://kubernetes.io/docs/user-guide/node-selection/ # Not yet annotated: excluded from values.schema.json and README.md.