Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

ci(helm): reuse chart dependencies that already match the lock (#930)

Shai Shmuelbc015e0a373e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a155779e9..232b16fb3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -125,10 +125,17 @@ jobs:
mise exec -- uv run --frozen ruff format --check .
mise exec -- uv run --frozen ruff check .
mise exec -- uv run --frozen pytest -q
+ - name: Restore the chart dependencies
+ id: helm-charts
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: deploy/helm/sie-cluster/charts
+ key: helm-charts-${{ hashFiles('deploy/helm/sie-cluster/Chart.yaml', 'deploy/helm/sie-cluster/Chart.lock') }}
+ # The collector privacy tests render the chart with its dependencies.
+ - if: steps.helm-charts.outputs.cache-hit != 'true'
+ run: mise run helm -- dependencies
- name: Pinned collector privacy
- run: |
- mise run helm -- dependencies
- mise exec -- uv run --frozen --project . --no-sync pytest -q -m docker tools/ci/tests/test_collector_*privacy.py
+ run: mise exec -- uv run --frozen --project . --no-sync pytest -q -m docker tools/ci/tests/test_collector_*privacy.py
bundle-resolution:
name: CI / Bundle resolution
diff --git a/tools/ci/tests/test_helm_task.py b/tools/ci/tests/test_helm_task.py
index 5dbce8b98..9717b613c 100644
--- a/tools/ci/tests/test_helm_task.py
+++ b/tools/ci/tests/test_helm_task.py
@@ -1,6 +1,8 @@
from __future__ import annotations
import io
+import re
+import shutil
import subprocess
import tarfile
from pathlib import Path
@@ -26,6 +28,149 @@ def test_dependency_repositories_are_derived_and_idempotent() -> None:
assert all(not url.startswith("oci://") for url in urls)
+def test_locked_archives_follow_the_checked_in_lock() -> None:
+ """The task's line parser and a YAML parser agree on the pinned archives."""
+ lock = yaml.safe_load((helm.resolve_project_root() / helm.CHART_DIR / "Chart.lock").read_text())
+ expected = {f"{entry['name']}-{entry['version']}.tgz" for entry in lock["dependencies"]}
+ assert expected
+ assert set(helm.locked_dependency_archives()) == expected
+
+
+def test_lock_digest_is_computed_the_way_helm_writes_it() -> None:
+ """The digest Helm wrote into the checked-in lock is reproduced exactly."""
+ assert helm.lock_matches_chart()
+
+
+def write_chart_archive(archive: Path, name: str, version: str) -> None:
+ """Write a chart archive that declares the given name and version."""
+ manifest = f"apiVersion: v2\nname: {name}\nversion: {version}\n".encode()
+ member = tarfile.TarInfo(f"{name}/Chart.yaml")
+ member.size = len(manifest)
+ with tarfile.open(archive, "w:gz") as chart:
+ chart.addfile(member, io.BytesIO(manifest))
+
+
+def locked_chart(tmp_path: Path, monkeypatch) -> Path:
+ """A copy of the checked-in chart and lock, with every pinned archive in charts/."""
+ source = helm.resolve_project_root() / helm.CHART_DIR
+ chart = tmp_path / helm.CHART_DIR
+ (chart / "charts").mkdir(parents=True)
+ for name in ("Chart.yaml", "Chart.lock"):
+ shutil.copy2(source / name, chart / name)
+ for entry in yaml.safe_load((chart / "Chart.lock").read_text())["dependencies"]:
+ archive = chart / "charts" / f"{entry['name']}-{entry['version']}.tgz"
+ write_chart_archive(archive, entry["name"], entry["version"])
+ monkeypatch.setattr(helm, "resolve_project_root", lambda: tmp_path)
+ return chart
+
+
+def a_locked_dependency(chart: Path) -> tuple[Path, str, str]:
+ """Return one pinned dependency: its archive in charts/, its name and its version."""
+ entry = yaml.safe_load((chart / "Chart.lock").read_text())["dependencies"][0]
+ return chart / "charts" / f"{entry['name']}-{entry['version']}.tgz", entry["name"], entry["version"]
+
+
+def test_dependencies_are_present_when_charts_match_the_lock(locked_chart: Path) -> None:
+ """Every pinned archive on disk and nothing else means no build is needed."""
+ assert helm.locked_dependencies_present()
+
+
+ "state",
+ [
+ "missing",
+ "other-version",
+ "leftover",
+ "directory",
+ "no-charts",
+ "no-lock",
+ "stale-lock",
+ "tags",
+ "declares-other-version",
+ "declares-other-chart",
+ "unreadable",
+ ],
+)
+def test_dependencies_are_absent_unless_charts_match_a_current_lock(locked_chart: Path, state: str) -> None:
+ """Anything short of an exact match with a current lock sends the task back to a full build."""
+ charts = locked_chart / "charts"
+ archive, name, version = a_locked_dependency(locked_chart)
+ manifest = locked_chart / "Chart.yaml"
+ # The first dependency's version line: the chart's own version is not indented.
+ constraint = re.compile(r"(?m)^( version: ).*$")
+ if state == "missing":
+ archive.unlink()
+ elif state == "other-version":
+ archive.rename(charts / f"{archive.stem}-older.tgz")
+ elif state == "leftover":
+ (charts / f"{archive.stem}-older.tgz").write_bytes(b"archive")
+ elif state == "directory":
+ archive.unlink()
+ archive.mkdir()
+ elif state == "no-charts":
+ shutil.rmtree(charts)
+ elif state == "no-lock":
+ (locked_chart / "Chart.lock").unlink()
+ elif state == "stale-lock":
+ # Chart.yaml asks for another version and the lock was not regenerated.
+ manifest.write_text(constraint.sub(r"\g<1>0.0.x", manifest.read_text(), count=1))
+ elif state == "declares-other-version":
+ # The file name matches the lock, the chart inside does not.
+ write_chart_archive(archive, name, "0.0.0")
+ elif state == "declares-other-chart":
+ write_chart_archive(archive, "another-chart", version)
+ elif state == "unreadable":
+ archive.write_bytes(b"not an archive")
+ else:
+ # A field the task does not read: the digest cannot be confirmed.
+ manifest.write_text(constraint.sub(r"\g<0>\n tags:\n - extra", manifest.read_text(), count=1))
+ assert not helm.locked_dependencies_present()
+
+
+def helm_calls(locked_chart: Path, monkeypatch) -> list[list[str]]:
+ """Record the Helm commands one task run issues, without running Helm."""
+ calls: list[list[str]] = []
+ monkeypatch.setattr(helm, "check_helm", lambda: True)
+ monkeypatch.setattr(helm, "run_helm", lambda args: calls.append(args) or 0)
+ monkeypatch.setattr(helm, "_sync_configs_to_helm", lambda: None)
+ monkeypatch.setattr(helm, "_cleanup_helm_configs", lambda: None)
+ return calls
+
+
+def run_task(monkeypatch, command: str) -> int:
+ """Run the task's entry point as `mise run helm -- <command>` would."""
+ monkeypatch.setattr(helm, "get_usage_flag", lambda _: command)
+ monkeypatch.setattr(helm.sys, "argv", ["helm.py", command])
+ return helm.main()
+
+
[email protected]("command", ["lint", "template"])
+def test_render_commands_reuse_dependencies_that_match_the_lock(helm_calls, monkeypatch, command: str) -> None:
+ """A render command downloads nothing when charts/ already matches the lock."""
+ assert run_task(monkeypatch, command) == 0
+ assert [call[0] for call in helm_calls] == [command]
+
+
+def test_render_commands_build_dependencies_that_do_not_match(locked_chart: Path, helm_calls, monkeypatch) -> None:
+ """A missing archive brings back the full build before the command runs."""
+ a_locked_dependency(locked_chart)[0].unlink()
+ assert run_task(monkeypatch, "lint") == 0
+ commands = [call[:2] for call in helm_calls]
+ assert set(map(tuple, commands[:-2])) == {("repo", "add")}
+ assert commands[-2:] == [["dependency", "build"], ["lint", "deploy/helm/sie-cluster"]]
+
+
+def test_explicit_dependencies_always_build(helm_calls, monkeypatch) -> None:
+ """`dependencies` rebuilds even when charts/ already matches the lock."""
+ assert helm.locked_dependencies_present()
+ assert run_task(monkeypatch, "dependencies") == 0
+ commands = [call[:2] for call in helm_calls]
+ assert set(map(tuple, commands[:-1])) == {("repo", "add")}
+ assert commands[-1] == ["dependency", "build"]
+
+
def test_validation_defaults_disable_payload_store(monkeypatch) -> None:
calls: list[list[str]] = []
monkeypatch.setattr(helm, "run_helm", lambda args: calls.append(args) or 0)
diff --git a/tools/mise_tasks/helm.py b/tools/mise_tasks/helm.py
index 03090ab96..561c00e0c 100755
--- a/tools/mise_tasks/helm.py
+++ b/tools/mise_tasks/helm.py
@@ -8,6 +8,8 @@
"""Helm chart operations for SIE cluster deployment.
This task handles:
+- Preparing the locked chart dependencies, reusing the archives in charts/
+ when they already match a Chart.lock that is current for Chart.yaml
- Linting the Helm chart
- Rendering templates locally
- Installing/upgrading/uninstalling releases
@@ -18,6 +20,7 @@ from __future__ import annotations
import argparse
import fcntl
import hashlib
+import json
import os
import shutil
import stat
@@ -25,6 +28,7 @@ import subprocess
import sys
import tarfile
import tempfile
+import zlib
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
@@ -151,6 +155,117 @@ def dependency_repository_commands() -> list[list[str]]:
]
+# A dependency's fields, in the order Helm writes them for the lock digest.
+_DEPENDENCY_FIELDS = ("name", "version", "repository", "condition", "alias")
+
+
+def _dependency_entries(path: Path) -> list[dict[str, str]] | None:
+ """Return the ``dependencies`` entries of Chart.yaml or Chart.lock.
+
+ Only plain ``key: value`` fields are read. Anything else under the list,
+ such as tags, gives None, and the caller then treats the lock as unknown.
+ """
+ entries: list[dict[str, str]] = []
+ inside = False
+ for raw in path.read_text().splitlines():
+ line = raw.split(" #", maxsplit=1)[0].rstrip()
+ if not line.strip() or line.lstrip().startswith("#"):
+ continue
+ if not line.startswith((" ", "-")):
+ inside = line == "dependencies:"
+ continue
+ if not inside:
+ continue
+ item = line.strip()
+ if item.startswith("- "):
+ entries.append({})
+ item = item[2:].strip()
+ key, separator, value = item.partition(":")
+ if not separator or not entries or key not in _DEPENDENCY_FIELDS:
+ return None
+ entries[-1][key] = value.strip().strip("\"'")
+ return entries
+
+
+def _as_helm_writes(entry: dict[str, str]) -> dict[str, str]:
+ """Return one dependency the way Helm serializes it: ordered, empty optional fields left out."""
+ return {key: entry.get(key, "") for key in _DEPENDENCY_FIELDS if key in ("name", "repository") or entry.get(key)}
+
+
+def lock_matches_chart() -> bool:
+ """Return whether Chart.lock was generated from the current Chart.yaml.
+
+ Helm stores a digest of both dependency lists in the lock and refuses to
+ build once Chart.yaml has changed without a new lock. The same digest is
+ computed here the way Helm does it: SHA-256 over the JSON of the two lists.
+ A digest that cannot be computed counts as no match.
+ """
+ chart = resolve_project_root() / CHART_DIR
+ lock = chart / "Chart.lock"
+ if not lock.is_file() or not (chart / "Chart.yaml").is_file():
+ return False
+ requested = _dependency_entries(chart / "Chart.yaml")
+ locked = _dependency_entries(lock)
+ if requested is None or locked is None:
+ return False
+ payload = json.dumps(
+ [[_as_helm_writes(entry) for entry in requested], [_as_helm_writes(entry) for entry in locked]],
+ separators=(",", ":"),
+ ensure_ascii=False,
+ )
+ for char in "&<>": # Go's JSON encoder escapes these three.
+ payload = payload.replace(char, f"\\u{ord(char):04x}")
+ digest = hashlib.sha256(payload.encode()).hexdigest()
+ return f"digest: sha256:{digest}" in lock.read_text().splitlines()
+
+
+def locked_dependency_archives() -> dict[str, tuple[str, str]] | None:
+ """Return each archive Chart.lock pins with its chart name and version, or None when unknown."""
+ lock = resolve_project_root() / CHART_DIR / "Chart.lock"
+ locked = _dependency_entries(lock) if lock.is_file() else None
+ if not locked or not all(entry.get("name") and entry.get("version") for entry in locked):
+ return None
+ return {f"{entry['name']}-{entry['version']}.tgz": (entry["name"], entry["version"]) for entry in locked}
+
+
+def _archive_identity(archive: Path) -> tuple[str, str] | None:
+ """Return the chart name and version an archive declares, or None when it cannot be read."""
+ try:
+ with tarfile.open(archive, "r:gz") as chart:
+ for member in chart:
+ if member.isfile() and member.name.count("/") == 1 and member.name.endswith("/Chart.yaml"):
+ manifest = chart.extractfile(member).read().decode()
+ break
+ else:
+ return None
+ except (OSError, EOFError, tarfile.TarError, zlib.error, UnicodeDecodeError):
+ return None
+ declared: dict[str, str] = {}
+ for line in manifest.splitlines():
+ key, separator, value = line.partition(":")
+ if separator and key in ("name", "version") and key not in declared:
+ declared[key] = value.split(" #", maxsplit=1)[0].strip().strip("\"'")
+ return declared.get("name", ""), declared.get("version", "")
+
+
+def locked_dependencies_present() -> bool:
+ """Return whether charts/ holds exactly what the current Chart.yaml locks.
+
+ Helm downloads every dependency again on each build, even when the
+ archive is already there. No build is needed when the lock is still the
+ one generated from Chart.yaml and charts/ matches it exactly: nothing
+ missing, nothing left over from another version, and every archive
+ declaring the chart name and version the lock pins.
+ """
+ expected = locked_dependency_archives()
+ charts = resolve_project_root() / CHART_DIR / "charts"
+ if expected is None or not charts.is_dir() or not lock_matches_chart():
+ return False
+ return {entry.name for entry in charts.iterdir()} == set(expected) and all(
+ _archive_identity(charts / name) == identity for name, identity in expected.items()
+ )
+
+
def validation_args(extra_args: list[str]) -> list[str]:
"""Provide deterministic, non-secret values for local chart validation."""
return [*DEFAULT_VALIDATION_ARGS, *extra_args]
@@ -424,7 +539,11 @@ def main() -> int:
# Commands that render templates need bundle/model configs in files/
needs_configs = command in ("lint", "template", "package", "install", "upgrade")
if needs_configs:
- if cmd_dependencies([]) != 0:
+ # An explicit `dependencies` always builds. Before the other commands
+ # the build runs unless charts/ already holds what Chart.yaml locks.
+ if locked_dependencies_present():
+ log(f"[helm] Locked dependencies already present for: {CHART_DIR}")
+ elif cmd_dependencies([]) != 0:
return 1
with _helm_config_sync_lock():
_sync_configs_to_helm()