From 38465b6e8bf961bb6abbd03ae8eed1810a7f38c2 Mon Sep 17 00:00:00 2001 From: Shai Shmuel Date: Mon, 9 Nov 2026 09:44:52 +0200 Subject: [PATCH 1/3] ci(helm): reuse chart dependencies that already match the lock The helm task built the chart dependencies before every lint, template, package, install and upgrade. Helm downloads each archive again on a build even when it is already in charts/, so one CI / Helm run fetched the ten dependencies about nine times, most of them from GitHub release assets, and the chart cache restored by the job was never used. The task now skips that implicit build when charts/ holds exactly the archives Chart.lock pins: nothing missing and nothing left over from another version. Any other state builds as before, and an explicit `mise run helm -- dependencies` always builds. CI / Python built the dependencies for the collector privacy tests on every run. It now restores the same chart cache as CI / Helm and builds only on a miss. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 13 +++- tools/ci/tests/test_helm_task.py | 102 +++++++++++++++++++++++++++++++ tools/mise_tasks/helm.py | 44 ++++++++++++- 3 files changed, 155 insertions(+), 4 deletions(-) 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..b8b1a195d 100644 --- a/tools/ci/tests/test_helm_task.py +++ b/tools/ci/tests/test_helm_task.py @@ -26,6 +26,108 @@ 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 helm.locked_dependency_archives() == expected + + +@pytest.fixture +def locked_chart(tmp_path: Path, monkeypatch) -> Path: + """A chart whose lock pins two dependencies, both present in charts/.""" + chart = tmp_path / "deploy/helm/sie-cluster" + (chart / "charts").mkdir(parents=True) + (chart / "Chart.yaml").write_text( + "apiVersion: v2\nname: sie-cluster\nversion: 0.8.1\ndependencies:\n" + " - name: keda\n repository: https://example.test/charts\n version: 2.14.x\n" + " - name: cert-manager\n repository: https://example.test/charts\n version: 1.16.x\n" + ) + (chart / "Chart.lock").write_text( + "dependencies:\n" + "- name: keda\n repository: https://example.test/charts\n version: 2.14.3\n" + '- name: cert-manager\n repository: https://example.test/charts\n version: "v1.16.5"\n' + "digest: sha256:0000\n" + 'generated: "2026-01-01T00:00:00Z"\n' + ) + for archive in ("keda-2.14.3.tgz", "cert-manager-v1.16.5.tgz"): + (chart / "charts" / archive).write_bytes(b"archive") + monkeypatch.setattr(helm, "resolve_project_root", lambda: tmp_path) + return chart + + +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_dependency_archives() == {"keda-2.14.3.tgz", "cert-manager-v1.16.5.tgz"} + assert helm.locked_dependencies_present() + + +@pytest.mark.parametrize("state", ["missing", "other-version", "leftover", "directory", "no-charts", "no-lock"]) +def test_dependencies_are_absent_unless_charts_match_the_lock_exactly(locked_chart: Path, state: str) -> None: + """Anything short of an exact match sends the task back to a full build.""" + charts = locked_chart / "charts" + if state == "missing": + (charts / "keda-2.14.3.tgz").unlink() + elif state == "other-version": + (charts / "keda-2.14.3.tgz").rename(charts / "keda-2.14.2.tgz") + elif state == "leftover": + (charts / "keda-2.14.2.tgz").write_bytes(b"archive") + elif state == "directory": + (charts / "keda-2.14.3.tgz").unlink() + (charts / "keda-2.14.3.tgz").mkdir() + elif state == "no-charts": + for archive in charts.iterdir(): + archive.unlink() + charts.rmdir() + else: + (locked_chart / "Chart.lock").unlink() + assert not helm.locked_dependencies_present() + + +@pytest.fixture +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 -- ` would.""" + monkeypatch.setattr(helm, "get_usage_flag", lambda _: command) + monkeypatch.setattr(helm.sys, "argv", ["helm.py", command]) + return helm.main() + + +@pytest.mark.parametrize("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.""" + (locked_chart / "charts" / "keda-2.14.3.tgz").unlink() + assert run_task(monkeypatch, "lint") == 0 + assert [call[:2] for call in helm_calls] == [ + ["repo", "add"], + ["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 + assert [call[:2] for call in helm_calls] == [["repo", "add"], ["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..5a7155887 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 Chart.lock - Linting the Helm chart - Rendering templates locally - Installing/upgrading/uninstalling releases @@ -151,6 +153,42 @@ def dependency_repository_commands() -> list[list[str]]: ] +def locked_dependency_archives() -> set[str] | None: + """Return the archive names Chart.lock pins, or None when they are unknown.""" + lock = resolve_project_root() / CHART_DIR / "Chart.lock" + if not lock.is_file(): + return None + names: list[str] = [] + versions: list[str] = [] + for line in lock.read_text().splitlines(): + key, _, value = line.strip().removeprefix("- ").partition(":") + value = value.strip().strip("\"'") + if key == "name": + names.append(value) + elif key == "version": + versions.append(value) + if not names or len(names) != len(versions): + return None + return {f"{name}-{version}.tgz" for name, version in zip(names, versions, strict=True)} + + +def locked_dependencies_present() -> bool: + """Return whether charts/ holds exactly the archives Chart.lock pins. + + Helm downloads every dependency again on each build, even when the + archive is already there. A directory that matches the lock exactly, with + nothing missing and nothing left over from another version, needs no + build. + """ + expected = locked_dependency_archives() + charts = resolve_project_root() / CHART_DIR / "charts" + if expected is None or not charts.is_dir(): + return False + return {entry.name for entry in charts.iterdir()} == expected and all( + (charts / name).is_file() for name in expected + ) + + 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 +462,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 only when charts/ does not already match the lock. + 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() From 0447c2490820dd91f932f2ff15da55f155fde120 Mon Sep 17 00:00:00 2001 From: Shai Shmuel Date: Mon, 9 Nov 2026 12:52:09 +0200 Subject: [PATCH 2/3] fix(helm): reuse chart archives only when the lock is current The task skipped the dependency build whenever charts/ held the archives Chart.lock names. A Chart.yaml whose dependencies changed without a new lock was then linted and rendered against the old archives, where `helm dependency build` would have refused it. The task now computes the lock digest the way Helm does and compares it with the one stored in Chart.lock. On a mismatch, or when the digest cannot be computed, the build runs as before and Helm reports the stale lock. Co-Authored-By: Claude Fable 5.1 --- tools/ci/tests/test_helm_task.py | 84 ++++++++++++++++------------ tools/mise_tasks/helm.py | 95 +++++++++++++++++++++++++------- 2 files changed, 123 insertions(+), 56 deletions(-) diff --git a/tools/ci/tests/test_helm_task.py b/tools/ci/tests/test_helm_task.py index b8b1a195d..f0985bd5f 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 @@ -34,54 +36,64 @@ def test_locked_archives_follow_the_checked_in_lock() -> None: assert 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() + + @pytest.fixture def locked_chart(tmp_path: Path, monkeypatch) -> Path: - """A chart whose lock pins two dependencies, both present in charts/.""" - chart = tmp_path / "deploy/helm/sie-cluster" + """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) - (chart / "Chart.yaml").write_text( - "apiVersion: v2\nname: sie-cluster\nversion: 0.8.1\ndependencies:\n" - " - name: keda\n repository: https://example.test/charts\n version: 2.14.x\n" - " - name: cert-manager\n repository: https://example.test/charts\n version: 1.16.x\n" - ) - (chart / "Chart.lock").write_text( - "dependencies:\n" - "- name: keda\n repository: https://example.test/charts\n version: 2.14.3\n" - '- name: cert-manager\n repository: https://example.test/charts\n version: "v1.16.5"\n' - "digest: sha256:0000\n" - 'generated: "2026-01-01T00:00:00Z"\n' - ) - for archive in ("keda-2.14.3.tgz", "cert-manager-v1.16.5.tgz"): - (chart / "charts" / archive).write_bytes(b"archive") + 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"]: + (chart / "charts" / f"{entry['name']}-{entry['version']}.tgz").write_bytes(b"archive") monkeypatch.setattr(helm, "resolve_project_root", lambda: tmp_path) return chart +def a_locked_archive(chart: Path) -> Path: + """Return one of the archives the fixture placed in charts/.""" + return min((chart / "charts").iterdir()) + + 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_dependency_archives() == {"keda-2.14.3.tgz", "cert-manager-v1.16.5.tgz"} assert helm.locked_dependencies_present() -@pytest.mark.parametrize("state", ["missing", "other-version", "leftover", "directory", "no-charts", "no-lock"]) -def test_dependencies_are_absent_unless_charts_match_the_lock_exactly(locked_chart: Path, state: str) -> None: - """Anything short of an exact match sends the task back to a full build.""" +@pytest.mark.parametrize( + "state", ["missing", "other-version", "leftover", "directory", "no-charts", "no-lock", "stale-lock", "tags"] +) +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 = a_locked_archive(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": - (charts / "keda-2.14.3.tgz").unlink() + archive.unlink() elif state == "other-version": - (charts / "keda-2.14.3.tgz").rename(charts / "keda-2.14.2.tgz") + archive.rename(charts / f"{archive.stem}-older.tgz") elif state == "leftover": - (charts / "keda-2.14.2.tgz").write_bytes(b"archive") + (charts / f"{archive.stem}-older.tgz").write_bytes(b"archive") elif state == "directory": - (charts / "keda-2.14.3.tgz").unlink() - (charts / "keda-2.14.3.tgz").mkdir() + archive.unlink() + archive.mkdir() elif state == "no-charts": - for archive in charts.iterdir(): - archive.unlink() - charts.rmdir() - else: + 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)) + 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() @@ -112,20 +124,20 @@ def test_render_commands_reuse_dependencies_that_match_the_lock(helm_calls, monk 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.""" - (locked_chart / "charts" / "keda-2.14.3.tgz").unlink() + a_locked_archive(locked_chart).unlink() assert run_task(monkeypatch, "lint") == 0 - assert [call[:2] for call in helm_calls] == [ - ["repo", "add"], - ["dependency", "build"], - ["lint", "deploy/helm/sie-cluster"], - ] + 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 - assert [call[:2] for call in helm_calls] == [["repo", "add"], ["dependency", "build"]] + 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: diff --git a/tools/mise_tasks/helm.py b/tools/mise_tasks/helm.py index 5a7155887..fbcda1cb0 100755 --- a/tools/mise_tasks/helm.py +++ b/tools/mise_tasks/helm.py @@ -9,7 +9,7 @@ This task handles: - Preparing the locked chart dependencies, reusing the archives in charts/ - when they already match Chart.lock + when they already match a Chart.lock that is current for Chart.yaml - Linting the Helm chart - Rendering templates locally - Installing/upgrading/uninstalling releases @@ -20,6 +20,7 @@ import argparse import fcntl import hashlib +import json import os import shutil import stat @@ -153,36 +154,90 @@ 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() -> set[str] | None: """Return the archive names Chart.lock pins, or None when they are unknown.""" lock = resolve_project_root() / CHART_DIR / "Chart.lock" - if not lock.is_file(): - return None - names: list[str] = [] - versions: list[str] = [] - for line in lock.read_text().splitlines(): - key, _, value = line.strip().removeprefix("- ").partition(":") - value = value.strip().strip("\"'") - if key == "name": - names.append(value) - elif key == "version": - versions.append(value) - if not names or len(names) != len(versions): + 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"{name}-{version}.tgz" for name, version in zip(names, versions, strict=True)} + return {f"{entry['name']}-{entry['version']}.tgz" for entry in locked} def locked_dependencies_present() -> bool: - """Return whether charts/ holds exactly the archives Chart.lock pins. + """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. A directory that matches the lock exactly, with - nothing missing and nothing left over from another version, needs no - build. + archive is already there. No build is needed when the lock is still the + one generated from Chart.yaml and charts/ matches it exactly, with nothing + missing and nothing left over from another version. """ expected = locked_dependency_archives() charts = resolve_project_root() / CHART_DIR / "charts" - if expected is None or not charts.is_dir(): + if expected is None or not charts.is_dir() or not lock_matches_chart(): return False return {entry.name for entry in charts.iterdir()} == expected and all( (charts / name).is_file() for name in expected @@ -463,7 +518,7 @@ def main() -> int: needs_configs = command in ("lint", "template", "package", "install", "upgrade") if needs_configs: # An explicit `dependencies` always builds. Before the other commands - # the build runs only when charts/ does not already match the lock. + # 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: From 823e7b5331147e922e0f8a118bf86c003f6983bf Mon Sep 17 00:00:00 2001 From: Shai Shmuel Date: Mon, 9 Nov 2026 13:04:35 +0200 Subject: [PATCH 3/3] fix(helm): check what each reused chart archive declares Reuse was decided from file names alone. An archive named after the locked version but holding another version, or one that could not be read, was accepted, and Helm then rendered whatever it contained. Each archive's own Chart.yaml must now declare the chart name and version Chart.lock pins. Anything else falls back to the build, which replaces the archive. Co-Authored-By: Claude Fable 5.1 --- tools/ci/tests/test_helm_task.py | 47 ++++++++++++++++++++++++++------ tools/mise_tasks/helm.py | 36 +++++++++++++++++++----- 2 files changed, 68 insertions(+), 15 deletions(-) diff --git a/tools/ci/tests/test_helm_task.py b/tools/ci/tests/test_helm_task.py index f0985bd5f..9717b613c 100644 --- a/tools/ci/tests/test_helm_task.py +++ b/tools/ci/tests/test_helm_task.py @@ -33,7 +33,7 @@ def test_locked_archives_follow_the_checked_in_lock() -> None: 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 helm.locked_dependency_archives() == expected + assert set(helm.locked_dependency_archives()) == expected def test_lock_digest_is_computed_the_way_helm_writes_it() -> None: @@ -41,6 +41,15 @@ def test_lock_digest_is_computed_the_way_helm_writes_it() -> None: 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)) + + @pytest.fixture def locked_chart(tmp_path: Path, monkeypatch) -> Path: """A copy of the checked-in chart and lock, with every pinned archive in charts/.""" @@ -50,14 +59,16 @@ def locked_chart(tmp_path: Path, monkeypatch) -> Path: 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"]: - (chart / "charts" / f"{entry['name']}-{entry['version']}.tgz").write_bytes(b"archive") + 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_archive(chart: Path) -> Path: - """Return one of the archives the fixture placed in charts/.""" - return min((chart / "charts").iterdir()) +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: @@ -66,12 +77,25 @@ def test_dependencies_are_present_when_charts_match_the_lock(locked_chart: Path) @pytest.mark.parametrize( - "state", ["missing", "other-version", "leftover", "directory", "no-charts", "no-lock", "stale-lock", "tags"] + "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 = a_locked_archive(locked_chart) + 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: ).*$") @@ -91,6 +115,13 @@ def test_dependencies_are_absent_unless_charts_match_a_current_lock(locked_chart 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)) @@ -124,7 +155,7 @@ def test_render_commands_reuse_dependencies_that_match_the_lock(helm_calls, monk 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_archive(locked_chart).unlink() + 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")} diff --git a/tools/mise_tasks/helm.py b/tools/mise_tasks/helm.py index fbcda1cb0..561c00e0c 100755 --- a/tools/mise_tasks/helm.py +++ b/tools/mise_tasks/helm.py @@ -28,6 +28,7 @@ import sys import tarfile import tempfile +import zlib from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path @@ -218,13 +219,33 @@ def lock_matches_chart() -> bool: return f"digest: sha256:{digest}" in lock.read_text().splitlines() -def locked_dependency_archives() -> set[str] | None: - """Return the archive names Chart.lock pins, or None when they are unknown.""" +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" for entry in locked} + 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: @@ -232,15 +253,16 @@ def locked_dependencies_present() -> bool: 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, with nothing - missing and nothing left over from another version. + 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()} == expected and all( - (charts / name).is_file() for name in expected + return {entry.name for entry in charts.iterdir()} == set(expected) and all( + _archive_identity(charts / name) == identity for name, identity in expected.items() )