From 3d9e330674ccf7f7eed0e929f405330455002122 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 16 Nov 2026 13:55:24 -0700 Subject: [PATCH 1/3] CI/CD - Freeze and validate Ansible dependency profiles Separate legacy and modern collection inputs, freeze the Python dependency closure, and validate effective plugin versions after application installation. Keep Galaxy recovery bounded and cover real collection operations and runner failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .azure-pipelines/ansible-integration-test.yml | 3 +- .azure-pipelines/cpu-unit-test.yml | 5 +- .azure-pipelines/cuda-unit-test.yml | 4 +- .github/workflows/ansible-dependencies.yml | 51 ++++++ Makefile | 6 +- dockerfile/cuda11.1.1.dockerfile | 3 +- dockerfile/cuda12.9.dockerfile | 2 +- dockerfile/cuda13.0.dockerfile | 2 +- dockerfile/cuda13.4.dockerfile | 2 +- dockerfile/rocm6.3.x.dockerfile | 2 +- dockerfile/rocm6.4.x.dockerfile | 2 +- docs/developer-guides/development.md | 53 +++++- requirements/ansible-legacy.yml | 8 + requirements/ansible-modern.yml | 8 + requirements/ansible.in | 12 ++ requirements/ansible.txt | 88 ++++++++++ scripts/install_ansible.py | 151 ++++++++++++++++++ setup.py | 8 +- tests/ansible/test_dependencies.py | 136 ++++++++++++++++ tests/ansible/test_dependencies.yaml | 78 +++++++++ tests/runner/test_ansible.py | 15 ++ 21 files changed, 620 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/ansible-dependencies.yml create mode 100644 requirements/ansible-legacy.yml create mode 100644 requirements/ansible-modern.yml create mode 100644 requirements/ansible.in create mode 100644 requirements/ansible.txt create mode 100644 scripts/install_ansible.py create mode 100644 tests/ansible/test_dependencies.py create mode 100644 tests/ansible/test_dependencies.yaml diff --git a/.azure-pipelines/ansible-integration-test.yml b/.azure-pipelines/ansible-integration-test.yml index 9c8550966..678c5bbd7 100644 --- a/.azure-pipelines/ansible-integration-test.yml +++ b/.azure-pipelines/ansible-integration-test.yml @@ -23,7 +23,8 @@ steps: echo "##vso[task.prependpath]$HOME/.local/bin" displayName: Export path - script: | - python3 -m pip install .[test] + set -e + python3 -m pip install -c requirements/ansible.txt .[test] make postinstall displayName: Install Ansible dependencies - script: | diff --git a/.azure-pipelines/cpu-unit-test.yml b/.azure-pipelines/cpu-unit-test.yml index ee71e4956..efdb7615b 100644 --- a/.azure-pipelines/cpu-unit-test.yml +++ b/.azure-pipelines/cpu-unit-test.yml @@ -26,10 +26,13 @@ steps: echo "##vso[task.prependpath]$HOME/.local/bin" displayName: Export path - script: | + set -e + apt-get update + apt-get install -y --no-install-recommends openssh-client rsync if python3 -c "import sys; exit(0 if sys.version_info < (3, 11) else 1)"; then python3 -m pip install --upgrade setuptools==65.7 fi - python3 -m pip install --no-cache-dir .[test,cpuworker] + python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[test,cpuworker] make postinstall displayName: Install dependencies - script: | diff --git a/.azure-pipelines/cuda-unit-test.yml b/.azure-pipelines/cuda-unit-test.yml index be06491e8..b024d5ff7 100644 --- a/.azure-pipelines/cuda-unit-test.yml +++ b/.azure-pipelines/cuda-unit-test.yml @@ -25,9 +25,9 @@ steps: "apt-get update -y -q && \ yes '' | apt-get install -y -q sudo && \ apt-get install -y -q \ - ffmpeg libavcodec-dev libavformat-dev libavutil-dev libboost-program-options-dev libswresample-dev" + ffmpeg libavcodec-dev libavformat-dev libavutil-dev libboost-program-options-dev libswresample-dev openssh-client rsync" python3 -m pip install --upgrade setuptools==65.7 - python3 -m pip install .[test,nvworker] + python3 -m pip install -c requirements/ansible.txt .[test,nvworker] make postinstall displayName: Install dependencies - script: | diff --git a/.github/workflows/ansible-dependencies.yml b/.github/workflows/ansible-dependencies.yml new file mode 100644 index 000000000..ec3bdc197 --- /dev/null +++ b/.github/workflows/ansible-dependencies.yml @@ -0,0 +1,51 @@ +name: Ansible Dependencies + +on: + pull_request: + paths: + - .github/workflows/ansible-dependencies.yml + - requirements/ansible* + - scripts/install_ansible.py + - setup.py + - Makefile + - superbench/runner/** + - tests/ansible/** + push: + branches: + - main + - release/* + paths: + - .github/workflows/ansible-dependencies.yml + - requirements/ansible* + - scripts/install_ansible.py + - setup.py + - Makefile + - superbench/runner/** + - tests/ansible/** + +permissions: + contents: read + +jobs: + collections: + name: Ansible Python ${{ matrix.python }} + runs-on: ubuntu-22.04 + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + python: ['3.7', '3.8', '3.10', '3.11', '3.12', '3.13'] + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ matrix.python }} + - name: Install local test tools + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends openssh-client rsync + - name: Install and exercise the dependency profile + run: | + python3 scripts/install_ansible.py + python3 -m unittest discover -s tests/ansible -p test_dependencies.py -v + python3 scripts/install_ansible.py --check diff --git a/Makefile b/Makefile index a7b8f05d1..d749b3132 100644 --- a/Makefile +++ b/Makefile @@ -21,8 +21,4 @@ thirdparty: cd ./third_party/ && make all postinstall: -ifeq ($(shell which ansible-galaxy),) - $(error 'Cannot find ansible-galaxy') -else - ansible-galaxy collection install ansible.posix ansible.utils community.crypto -endif + python3 scripts/install_ansible.py diff --git a/dockerfile/cuda11.1.1.dockerfile b/dockerfile/cuda11.1.1.dockerfile index 8518533ce..9126d8393 100644 --- a/dockerfile/cuda11.1.1.dockerfile +++ b/dockerfile/cuda11.1.1.dockerfile @@ -47,6 +47,7 @@ RUN apt-get update && \ openssh-client \ openssh-server \ pciutils \ + rsync \ sudo \ util-linux \ vim \ @@ -166,7 +167,7 @@ RUN curl https://sh.rustup.rs -sSf | sh -s -- -y && \ ADD . . RUN python3 -m pip install --upgrade setuptools==65.7 importlib_metadata==6.8.0 && \ - python3 -m pip install --no-cache-dir .[nvworker] && \ + python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ make cppbuild && \ make postinstall && \ rm -rf .git diff --git a/dockerfile/cuda12.9.dockerfile b/dockerfile/cuda12.9.dockerfile index 3c2c92000..1c2853b1d 100644 --- a/dockerfile/cuda12.9.dockerfile +++ b/dockerfile/cuda12.9.dockerfile @@ -189,7 +189,7 @@ RUN make -C third_party cuda_with_msccl ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ - python3 -m pip install --no-cache-dir .[nvworker] && \ + python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ make cppbuild && \ make postinstall && \ rm -rf .git diff --git a/dockerfile/cuda13.0.dockerfile b/dockerfile/cuda13.0.dockerfile index 520920afa..7588de7fa 100644 --- a/dockerfile/cuda13.0.dockerfile +++ b/dockerfile/cuda13.0.dockerfile @@ -156,7 +156,7 @@ RUN make -C third_party cuda ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ - python3 -m pip install --no-cache-dir .[nvworker] && \ + python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ make cppbuild && \ make postinstall && \ rm -rf .git diff --git a/dockerfile/cuda13.4.dockerfile b/dockerfile/cuda13.4.dockerfile index 09d85889c..b5fe246ba 100644 --- a/dockerfile/cuda13.4.dockerfile +++ b/dockerfile/cuda13.4.dockerfile @@ -200,7 +200,7 @@ RUN f=${SB_MICRO_PATH}/bin/streamOlympus; \ ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ - python3 -m pip install --no-cache-dir .[nvworker] && \ + python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ make cppbuild && \ make postinstall && \ rm -rf .git diff --git a/dockerfile/rocm6.3.x.dockerfile b/dockerfile/rocm6.3.x.dockerfile index a03c53bff..dae4a4bf3 100644 --- a/dockerfile/rocm6.3.x.dockerfile +++ b/dockerfile/rocm6.3.x.dockerfile @@ -143,7 +143,7 @@ RUN make RCCL_HOME=/opt/rocm ROCBLAS_BRANCH=release-staging/rocm-rel-6.3 HIPBLAS ADD . . ENV USE_HIP_DATATYPE=1 ENV USE_HIPBLAS_COMPUTETYPE=1 -RUN python3 -m pip install --no-build-isolation .[amdworker] && \ +RUN python3 -m pip install --no-build-isolation -c requirements/ansible.txt .[amdworker] && \ CXX=/opt/rocm/bin/hipcc make cppbuild && \ make postinstall && \ rm -rf .git diff --git a/dockerfile/rocm6.4.x.dockerfile b/dockerfile/rocm6.4.x.dockerfile index cd7670e9a..6c45b0a6d 100644 --- a/dockerfile/rocm6.4.x.dockerfile +++ b/dockerfile/rocm6.4.x.dockerfile @@ -245,7 +245,7 @@ RUN python3 -c "import transformer_engine.pytorch; print('TE installed successfu ADD . . ENV USE_HIP_DATATYPE=1 ENV USE_HIPBLAS_COMPUTETYPE=1 -RUN python3 -m pip install .[amdworker] && \ +RUN python3 -m pip install -c requirements/ansible.txt .[amdworker] && \ CXX=/opt/rocm/bin/hipcc make cppbuild && \ make postinstall && \ rm -rf .git diff --git a/docs/developer-guides/development.md b/docs/developer-guides/development.md index e6b749485..86784941f 100644 --- a/docs/developer-guides/development.md +++ b/docs/developer-guides/development.md @@ -19,9 +19,60 @@ Follow [System Requirements](../getting-started/installation.mdx). git clone --recurse-submodules -j8 https://github.com/microsoft/superbenchmark cd superbenchmark -python3 -m pip install -e .[develop] +python3 scripts/install_ansible.py +python3 -m pip install -c requirements/ansible.txt -e .[develop] +python3 scripts/install_ansible.py --check ``` +The POSIX control environment also needs `openssh-client` and `rsync`. +Use a clean Python environment; do not install the bundled `ansible` distribution +alongside `ansible-base` or `ansible-core`. + +### Ansible Dependency Profiles + +The Python freeze in `requirements/ansible.txt` includes the engine, runner and +their transitive Python dependencies. Collections are pinned separately: + +| Control Python | Engine | Runner | Collections | +| --- | --- | --- | --- | +| 3.7-3.10 | ansible-base 2.10.17 | 2.3.1 | `ansible-legacy.yml` | +| 3.11 | ansible-core 2.19.15 | 2.4.3 | `ansible-modern.yml` | +| 3.12 | ansible-core 2.21.6 | 2.4.3 | `ansible-modern.yml` | +| 3.13+ | ansible-core 2.22.0 | 2.4.3 | `ansible-modern.yml` | + +These are deployment inputs, not a promise that every future Python release is +supported. The old 2.10 engine is end-of-life; retaining it is a compatibility +bridge for existing images, not a long-term support solution. Engine and Python +support lifetimes must be reviewed when updating profiles. Control Python and +managed-host Python have separate compatibility requirements. + +`make postinstall` installs and checks the selected profile. The installer uses +the current Python interpreter, checks collection engine requirements, and +reports the paths of the plugins actually loaded. `--check` is read-only and +does not contact Galaxy. Use it after installing SuperBench to detect dependency +drift or a different collection shadowing the pinned copy. + +Only the Galaxy acquisition command has an external retry loop: at most three +attempts, each limited to 300 seconds, with 10- and 20-second waits. Logs are +preserved and exhaustion fails the build. Pip retains its own network handling; +do not add another retry around the entire Docker build or workflow. + +To update dependencies, edit `requirements/ansible.in`, regenerate the Python +freeze, update the collection requirements, and validate every affected profile: + +```bash +uv pip compile --universal --python-version 3.7 requirements/ansible.in --output-file requirements/ansible.txt +python3 scripts/install_ansible.py +python3 -m pytest -q tests/ansible/test_dependencies.py tests/runner/test_ansible.py +``` + +The local collection test generates disposable keys without logging private key +contents, checks rank lookup and idempotency, and exercises the production +result-fetch playbook on local files. It does not replace remote deployment, +container-internal `--no-docker`, or GPU image validation. +Version pins and cache reuse do not make a cold build offline. Hash-verified +offline artifacts and broader image reproducibility are outside this change. + ## Lint and Test Format code using yapf. diff --git a/requirements/ansible-legacy.yml b/requirements/ansible-legacy.yml new file mode 100644 index 000000000..853465fcf --- /dev/null +++ b/requirements/ansible-legacy.yml @@ -0,0 +1,8 @@ +--- +collections: + - name: ansible.posix + version: 1.5.4 + - name: ansible.utils + version: 2.12.0 + - name: community.crypto + version: 2.16.0 diff --git a/requirements/ansible-modern.yml b/requirements/ansible-modern.yml new file mode 100644 index 000000000..b467c543d --- /dev/null +++ b/requirements/ansible-modern.yml @@ -0,0 +1,8 @@ +--- +collections: + - name: ansible.posix + version: 2.2.2 + - name: ansible.utils + version: 6.1.1 + - name: community.crypto + version: 3.5.1 diff --git a/requirements/ansible.in b/requirements/ansible.in new file mode 100644 index 000000000..4d0d5a3d4 --- /dev/null +++ b/requirements/ansible.in @@ -0,0 +1,12 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# Preserve the existing Python <= 3.10 control runtime while legacy images remain supported. +ansible-base==2.10.17; python_version < "3.11" +ansible-runner==2.3.1; python_version < "3.11" +Jinja2<3.1; python_version < "3.11" + +ansible-core==2.19.15; python_version == "3.11" +ansible-core==2.21.6; python_version == "3.12" +ansible-core==2.22.0; python_version >= "3.13" +ansible-runner==2.4.3; python_version >= "3.11" diff --git a/requirements/ansible.txt b/requirements/ansible.txt new file mode 100644 index 000000000..5eee672a4 --- /dev/null +++ b/requirements/ansible.txt @@ -0,0 +1,88 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile --universal --python-version 3.7 requirements/ansible.in --output-file requirements/ansible.txt +ansible-base==2.10.17 ; python_full_version < '3.11' + # via -r requirements/ansible.in +ansible-core==2.19.15 ; python_full_version == '3.11.*' + # via -r requirements/ansible.in +ansible-core==2.21.6 ; python_full_version == '3.12.*' + # via -r requirements/ansible.in +ansible-core==2.22.0 ; python_full_version >= '3.13' + # via -r requirements/ansible.in +ansible-runner==2.3.1 ; python_full_version < '3.11' + # via -r requirements/ansible.in +ansible-runner==2.4.3 ; python_full_version >= '3.11' + # via -r requirements/ansible.in +cffi==1.15.1 ; python_full_version < '3.8' and platform_python_implementation != 'PyPy' + # via cryptography +cffi==1.17.1 ; python_full_version == '3.8.*' and platform_python_implementation != 'PyPy' + # via cryptography +cffi==2.0.0 ; python_full_version == '3.9.*' and platform_python_implementation != 'PyPy' + # via cryptography +cffi==2.1.1 ; python_full_version >= '3.10' and platform_python_implementation != 'PyPy' + # via cryptography +cryptography==45.0.7 ; python_full_version < '3.8' + # via ansible-base +cryptography==47.0.0 ; python_full_version >= '3.8' and python_full_version <= '3.9' + # via ansible-base +cryptography==50.0.2 ; python_full_version > '3.9' + # via + # ansible-base + # ansible-core +jinja2==3.0.3 ; python_full_version < '3.11' + # via + # -r requirements/ansible.in + # ansible-base +jinja2==3.1.6 ; python_full_version >= '3.11' + # via + # -r requirements/ansible.in + # ansible-core +lockfile==0.12.2 + # via python-daemon +markupsafe==2.1.5 ; python_full_version < '3.9' + # via jinja2 +markupsafe==3.0.4 ; python_full_version >= '3.9' + # via jinja2 +packaging==24.0 ; python_full_version < '3.8' + # via + # ansible-base + # ansible-runner +packaging==26.2 ; python_full_version == '3.8.*' + # via + # ansible-base + # ansible-runner +packaging==26.3 ; python_full_version >= '3.9' + # via + # ansible-base + # ansible-core + # ansible-runner +pexpect==4.9.0 + # via ansible-runner +ptyprocess==0.7.0 + # via pexpect +pycparser==2.21 ; python_full_version < '3.8' and platform_python_implementation != 'PyPy' + # via cffi +pycparser==2.23 ; (python_full_version == '3.9.*' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy') or (python_full_version == '3.8.*' and platform_python_implementation != 'PyPy') + # via cffi +pycparser==3.11 ; python_full_version == '3.10.*' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pycparser==3.12 ; python_full_version >= '3.11' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +python-daemon==3.1.2 + # via ansible-runner +pyyaml==6.0.1 ; python_full_version < '3.8' + # via + # ansible-base + # ansible-runner +pyyaml==6.0.3 ; python_full_version >= '3.8' + # via + # ansible-base + # ansible-core + # ansible-runner +resolvelib==1.2.1 ; python_full_version >= '3.11' + # via ansible-core +six==1.17.0 ; python_full_version < '3.11' + # via ansible-runner +typing-extensions==4.13.2 ; python_full_version == '3.8.*' + # via cryptography +typing-extensions==4.16.0 ; python_full_version >= '3.9' and python_full_version < '3.11' + # via cryptography diff --git a/scripts/install_ansible.py b/scripts/install_ansible.py new file mode 100644 index 000000000..a9e88ac17 --- /dev/null +++ b/scripts/install_ansible.py @@ -0,0 +1,151 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Install or check the frozen Ansible environment without importing SuperBench.""" + +import argparse +import json +import re +import shutil +import subprocess +import sys +import sysconfig +import time +from pathlib import Path + +REQUIREMENTS = Path(__file__).resolve().parents[1] / 'requirements' + + +def ansible_command(name): + """Run an Ansible entry point with the same interpreter as the application.""" + script = Path(sysconfig.get_path('scripts')) / name + if not script.is_file(): + found = shutil.which(name) + if not found: + raise RuntimeError('Cannot find {} for {}.'.format(name, sys.executable)) + script = Path(found) + return [sys.executable, str(script)] + + +def install_collections(command): + """Retry collection acquisition at most three times within a bounded budget.""" + for attempt in range(1, 4): + try: + result = subprocess.run(command, timeout=300) + returncode = result.returncode + except subprocess.TimeoutExpired: + print('Collection installation exceeded 300 seconds.', file=sys.stderr, flush=True) + returncode = 124 + if returncode == 0: + return + print( + 'Collection installation attempt {}/3 failed (exit {}).'.format(attempt, returncode), + file=sys.stderr, + flush=True, + ) + if attempt == 3: + raise subprocess.CalledProcessError(returncode, command) + delay = attempt * 10 + print('Retrying in {} seconds.'.format(delay), file=sys.stderr, flush=True) + time.sleep(delay) + + +def installed_packages(): + """Read installed distribution metadata without importing the engine.""" + packages = json.loads( + subprocess.check_output( + [sys.executable, '-m', 'pip', 'list', '--format=json', '--disable-pip-version-check'], text=True + ) + ) + return {re.sub(r'[-_.]+', '-', package['name']).lower(): package['version'] for package in packages} + + +def check_python(): + """Fail if application installation changed any frozen Python dependency.""" + from packaging.requirements import Requirement + from packaging.utils import canonicalize_name + + installed = installed_packages() + if 'ansible' in installed or ('ansible-base' in installed and 'ansible-core' in installed): + raise RuntimeError('Use a clean environment: do not mix ansible, ansible-base and ansible-core distributions.') + for line in (REQUIREMENTS / 'ansible.txt').read_text().splitlines(): + if not line.strip() or line.lstrip().startswith('#'): + continue + requirement = Requirement(line) + if requirement.marker and not requirement.marker.evaluate(): + continue + version = installed.get(canonicalize_name(requirement.name)) + if version is None or not requirement.specifier.contains(version): + raise RuntimeError('{} is required, but {} is installed.'.format(requirement, version)) + print('{}=={}'.format(requirement.name, version)) + + +def check_collections(requirements): + """Check the versions, engine support and paths of the plugins actually loaded.""" + import yaml + from ansible.release import __version__ as engine_version + from packaging.specifiers import SpecifierSet + + expected = {item['name']: str(item['version']) for item in yaml.safe_load(requirements.read_text())['collections']} + plugins = [ + ('module', 'community.crypto.openssh_keypair'), + ('module', 'ansible.posix.synchronize'), + ('lookup', 'ansible.utils.index_of'), + ] + for plugin_type, plugin in plugins: + command = ansible_command('ansible-doc') + ['--json', '-t', plugin_type, plugin] + documentation = json.loads(subprocess.check_output(command, text=True)) + if plugin not in documentation: + raise RuntimeError('Cannot load required plugin {}.'.format(plugin)) + collection = Path(documentation[plugin]['doc']['filename']).resolve().parents[2] + metadata = json.loads((collection / 'MANIFEST.json').read_text())['collection_info'] + name = '{}.{}'.format(metadata['namespace'], metadata['name']) + if metadata['version'] != expected[name]: + raise RuntimeError( + '{}: expected {}, loaded {} from {}.'.format(name, expected[name], metadata['version'], collection) + ) + runtime = yaml.safe_load((collection / 'meta' / 'runtime.yml').read_text()) + if not SpecifierSet(runtime['requires_ansible']).contains(engine_version): + raise RuntimeError( + '{} requires Ansible {}, not {}.'.format(name, runtime['requires_ansible'], engine_version) + ) + for dependency, versions in metadata['dependencies'].items(): + if dependency not in expected or not SpecifierSet(versions).contains(expected[dependency]): + raise RuntimeError('Pin the {} dependency of {} in {}.'.format(dependency, name, requirements)) + print('{}=={} ({})'.format(name, metadata['version'], collection)) + + +def main(): + """Install the selected profile, or verify it without network access.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + '--check', action='store_true', help='Check installed versions and effective plugin paths only.' + ) + args = parser.parse_args() + profile = 'legacy' if sys.version_info[:2] < (3, 11) else 'modern' + collections = REQUIREMENTS / 'ansible-{}.yml'.format(profile) + try: + if not args.check: + incompatible = 'ansible-core' if profile == 'legacy' else 'ansible-base' + if {'ansible', incompatible}.intersection(installed_packages()): + raise RuntimeError('Create a clean environment before changing Ansible distributions.') + subprocess.run( + [sys.executable, '-m', 'pip', 'install', '-r', + str(REQUIREMENTS / 'ansible.txt')], check=True + ) + check_python() + if not args.check: + install_collections( + ansible_command('ansible-galaxy') + + ['collection', 'install', '--server', 'https://galaxy.ansible.com', '-r', + str(collections)] + ) + check_collections(collections) + except (RuntimeError, subprocess.CalledProcessError) as error: + print('Ansible dependency setup failed: {}'.format(error), file=sys.stderr) + return error.returncode if isinstance(error, subprocess.CalledProcessError) else 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/setup.py b/setup.py index 114f6590a..4dfb7862d 100644 --- a/setup.py +++ b/setup.py @@ -165,10 +165,12 @@ def run(self): 'vcs_versioning; python_version>="3.10"', ], install_requires=[ - 'ansible;os_name=="posix" and python_version>"3.10"', - 'ansible_base>=2.10.9;os_name=="posix" and python_version<="3.10"', + 'ansible-core>=2.19,<2.20;os_name=="posix" and python_version=="3.11"', + 'ansible-core>=2.21,<2.22;os_name=="posix" and python_version=="3.12"', + 'ansible-core>=2.22,<2.23;os_name=="posix" and python_version>="3.13"', + 'ansible_base>=2.10.17,<2.11;os_name=="posix" and python_version<="3.10"', 'ansible_runner>=2.0.0rc1, <2.3.2;python_version<="3.10"', - 'ansible_runner;python_version>"3.10"', + 'ansible_runner>=2.4.3,<2.5;python_version>"3.10"', 'colorlog>=6.7.0', 'importlib_metadata', 'jinja2>=2.10.1', diff --git a/tests/ansible/test_dependencies.py b/tests/ansible/test_dependencies.py new file mode 100644 index 000000000..fa3dae1f6 --- /dev/null +++ b/tests/ansible/test_dependencies.py @@ -0,0 +1,136 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Tests for dependency acquisition and the installed Ansible collections.""" + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +spec = importlib.util.spec_from_file_location( + 'install_ansible', + Path(__file__).resolve().parents[2] / 'scripts' / 'install_ansible.py' +) +assert spec is not None and spec.loader is not None +install_ansible = importlib.util.module_from_spec(spec) +spec.loader.exec_module(install_ansible) + + +class CollectionRetryTest(unittest.TestCase): + """Exercise bounded retries without contacting Galaxy or waiting.""" + def test_success_and_recovery(self): + """Stop on the first successful attempt and keep the original command.""" + command = ['ansible-galaxy', 'collection', 'install', '-r', 'requirements.yml'] + for codes, delays in [([0], []), ([1, 0], [10]), ([1, 1, 0], [10, 20])]: + with self.subTest(codes=codes), mock.patch.object( + install_ansible.subprocess, + 'run', + side_effect=[subprocess.CompletedProcess(command, code) for code in codes] + ) as run, mock.patch.object(install_ansible.time, 'sleep') as sleep: + install_ansible.install_collections(command) + self.assertEqual(run.call_args_list, [mock.call(command, timeout=300)] * len(codes)) + self.assertEqual(sleep.call_args_list, [mock.call(delay) for delay in delays]) + + def test_exhaustion_preserves_failure(self): + """Propagate the last failure rather than reporting a successful install.""" + command = ['ansible-galaxy'] + with mock.patch.object( + install_ansible.subprocess, 'run', return_value=subprocess.CompletedProcess(command, 17) + ) as run, mock.patch.object(install_ansible.time, 'sleep') as sleep: + with self.assertRaises(subprocess.CalledProcessError) as error: + install_ansible.install_collections(command) + self.assertEqual(error.exception.returncode, 17) + self.assertEqual(run.call_count, 3) + self.assertEqual(sleep.call_args_list, [mock.call(10), mock.call(20)]) + + def test_timeout_is_bounded(self): + """Terminate timed-out acquisition attempts and fail after the budget.""" + command = ['ansible-galaxy'] + with mock.patch.object(install_ansible.subprocess, 'run', side_effect=subprocess.TimeoutExpired(command, 300) + ) as run, mock.patch.object(install_ansible.time, 'sleep'): + with self.assertRaises(subprocess.CalledProcessError) as error: + install_ansible.install_collections(command) + self.assertEqual(error.exception.returncode, 124) + self.assertEqual(run.call_count, 3) + + def test_changed_python_dependency_is_rejected(self): + """Detect a dependency changed by a later application installation.""" + with tempfile.TemporaryDirectory() as directory: + requirements = Path(directory) + (requirements / 'ansible.txt').write_text('packaging==26.3\n') + with mock.patch.object(install_ansible, 'REQUIREMENTS', requirements), mock.patch.object( + install_ansible.subprocess, 'check_output', return_value='[{"name":"packaging","version":"24.0"}]' + ): + with self.assertRaisesRegex(RuntimeError, 'packaging==26.3'): + install_ansible.check_python() + + def test_conflicting_distribution_is_rejected_before_install(self): + """Do not overwrite another distribution sharing the ansible namespace.""" + with mock.patch.object(sys, 'argv', [ + 'install_ansible.py' + ]), mock.patch.object(install_ansible, 'installed_packages', + return_value={'ansible': + '1.0'}), mock.patch.object(install_ansible.subprocess, 'run') as run: + self.assertEqual(install_ansible.main(), 1) + run.assert_not_called() + + @unittest.skipUnless(os.name == 'posix', 'Ansible collections require POSIX.') + def test_shadowed_collection_is_rejected(self): + """Reject a different collection loaded ahead of the pinned version.""" + with tempfile.TemporaryDirectory() as directory: + collection = Path(directory) + (collection / 'MANIFEST.json').write_text( + json.dumps( + { + 'collection_info': { + 'namespace': 'community', + 'name': 'crypto', + 'version': '0.0.0', + 'dependencies': {} + } + } + ) + ) + documentation = { + 'community.crypto.openssh_keypair': { + 'doc': { + 'filename': str(collection / 'plugins' / 'modules' / 'openssh_keypair.py') + } + } + } + with mock.patch.object(install_ansible.subprocess, 'check_output', return_value=json.dumps(documentation)): + with self.assertRaisesRegex(RuntimeError, 'loaded 0.0.0'): + install_ansible.check_collections(install_ansible.REQUIREMENTS / 'ansible-modern.yml') + + +@unittest.skipUnless(os.name == 'posix', 'Ansible collections require POSIX.') +class InstalledCollectionsTest(unittest.TestCase): + """Run the real plugins on disposable local files, without Docker or SSH.""" + def test_installed_collections(self): + """Check key generation, rank lookup and the actual result-fetch playbook.""" + with tempfile.TemporaryDirectory(prefix='sb-ansible-test-') as directory: + config = Path(directory) / 'ansible.cfg' + config.write_text('[defaults]\n') + command = install_ansible.ansible_command('ansible-playbook') + [ + '-i', + 'localhost,', + '-c', + 'local', + str(Path(__file__).with_name('test_dependencies.yaml')), + '-e', + json.dumps({ + 'test_root': directory, + 'ansible_python_interpreter': sys.executable + }), + ] + env = dict(os.environ, ANSIBLE_CONFIG=str(config), ANSIBLE_LOCAL_TEMP=str(Path(directory) / 'local-tmp')) + result = subprocess.run( + command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120 + ) + self.assertEqual(result.returncode, 0, result.stdout) diff --git a/tests/ansible/test_dependencies.yaml b/tests/ansible/test_dependencies.yaml new file mode 100644 index 000000000..63621e5b8 --- /dev/null +++ b/tests/ansible/test_dependencies.yaml @@ -0,0 +1,78 @@ +--- +- name: Exercise the collection operations used by SuperBench + hosts: localhost + gather_facts: false + tasks: + - name: Generate the deployment key + community.crypto.openssh_keypair: + path: '{{ test_root }}/id_ed25519' + type: ed25519 + comment: superbench + force: false + register: first_key + no_log: true + - name: Preserve the deployment key on a repeated run + community.crypto.openssh_keypair: + path: '{{ test_root }}/id_ed25519' + type: ed25519 + comment: superbench + force: false + register: second_key + no_log: true + - name: Check idempotency without inspecting the private key + assert: + that: + - first_key is changed + - second_key is not changed + - first_key.public_key == second_key.public_key + - name: Check ranks against sorted hostfile entries + vars: + nodes: "{{ ['node2', 'node0', 'node1'] | sort }}" + assert: + that: + - lookup('ansible.utils.index_of', nodes, 'eq', 'node0') | int == 0 + - lookup('ansible.utils.index_of', nodes, 'eq', 'node1') | int == 1 + - lookup('ansible.utils.index_of', nodes, 'eq', 'node2') | int == 2 + - nodes | join('\n') == 'node0\nnode1\nnode2' + - name: Prepare disposable result directories + file: + path: '{{ test_root }}/{{ item }}' + state: directory + mode: '0700' + loop: + - source/nodes + - received/nodes + - name: Create a benchmark result + copy: + content: '{"result": 42}' + dest: '{{ test_root }}/source/results.json' + mode: '0600' + - name: Create a result that must not be recursively collected + copy: + content: excluded + dest: '{{ test_root }}/source/nodes/excluded' + mode: '0600' + +- name: Exercise the production result-fetch playbook + import_playbook: ../../superbench/runner/playbooks/fetch_results.yaml + vars: + sb_output_dir: '{{ test_root }}/source' + absolute_output_dir: '{{ test_root }}/received' + +- name: Verify the fetched result layout + hosts: localhost + gather_facts: false + tasks: + - name: Read the disposable benchmark result + slurp: + src: '{{ test_root }}/received/nodes/{{ ansible_hostname }}/results.json' + register: result + - name: Check the excluded directory + stat: + path: '{{ test_root }}/received/nodes/{{ ansible_hostname }}/nodes' + register: excluded + - name: Check result content and recursion exclusion + assert: + that: + - "result.content | b64decode | from_json == {'result': 42}" + - not excluded.stat.exists diff --git a/tests/runner/test_ansible.py b/tests/runner/test_ansible.py index 550762c43..23076683d 100644 --- a/tests/runner/test_ansible.py +++ b/tests/runner/test_ansible.py @@ -4,6 +4,7 @@ """SuperBench Ansible Client test.""" import os +import sys import unittest import tempfile from pathlib import Path @@ -158,3 +159,17 @@ def test_get_playbook_config(self): 'playbook': str(self.ansible_client._playbook_path / 'play'), } ) + + def test_local_execution_and_failure_count(self): + """Exercise the real runner and preserve nonzero command failures.""" + client = AnsibleClient(OmegaConf.create({'host_list': 'localhost'})) + with tempfile.TemporaryDirectory(prefix='sb-ansible-client-') as directory: + for command, expected in [('printf sb-ansible-smoke', 0), ('exit 7', 2)]: + config = client.get_shell_config(command) + config['extravars'] = {'ansible_python_interpreter': sys.executable} + config['envvars'] = { + 'ANSIBLE_LOCAL_TEMP': str(Path(directory) / 'local'), + 'ANSIBLE_REMOTE_TEMP': str(Path(directory) / 'remote'), + } + self.assertEqual(client.run(config), expected) + self.assertEqual(client.failure_count, 1) From bb1008b0dfffc73e382d4db7c86f12b836e911e2 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 16 Nov 2026 14:13:18 -0700 Subject: [PATCH 2/3] CI/CD - Cache and verify Ansible dependency layers Install validated profiles before source-sensitive and expensive build steps across the active image matrix. Check final application environments without contacting Galaxy, and exercise real dependency-layer cache behavior only on relevant PRs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build-image.yml | 15 +++++ dockerfile/cuda11.1.1.dockerfile | 13 +++- dockerfile/cuda12.9.dockerfile | 13 +++- dockerfile/cuda13.0.dockerfile | 13 +++- dockerfile/cuda13.4.dockerfile | 97 +++++++++++++++------------- dockerfile/rocm6.3.x.dockerfile | 13 +++- dockerfile/rocm6.4.x.dockerfile | 16 ++++- docs/developer-guides/development.md | 23 +++++++ tests/ansible/check_build_cache.sh | 70 ++++++++++++++++++++ tests/ansible/test_dependencies.py | 51 +++++++++++++++ 10 files changed, 269 insertions(+), 55 deletions(-) create mode 100644 tests/ansible/check_build_cache.sh diff --git a/.github/workflows/build-image.yml b/.github/workflows/build-image.yml index 4a04cb6e4..44a7c54ed 100644 --- a/.github/workflows/build-image.yml +++ b/.github/workflows/build-image.yml @@ -86,6 +86,7 @@ jobs: uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2.8.0 with: submodules: recursive + fetch-depth: 2 - name: Free disk space run: | mkdir -p /tmp/emptydir @@ -115,6 +116,15 @@ jobs: TAGS=$(sed "s/main:/dev:/g" <<< ${TAGS}) fi DOCKERFILE=dockerfile/${{ matrix.dockerfile }}.dockerfile + ANSIBLE_CACHE_CHECK=false + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + CHANGED_ANSIBLE_INPUTS=$(git diff --name-only HEAD^1 HEAD -- \ + requirements scripts/install_ansible.py tests/ansible/check_build_cache.sh \ + .github/workflows/build-image.yml "$DOCKERFILE") + if [[ -n "$CHANGED_ANSIBLE_INPUTS" ]]; then + ANSIBLE_CACHE_CHECK=true + fi + fi BUILD_ARGS=${{ matrix.build_args }} if [[ "${{ matrix.extra_args }}" ]]; then @@ -135,6 +145,7 @@ jobs: fi echo "dockerfile=${DOCKERFILE}" >> "$GITHUB_OUTPUT" + echo "ansible_cache_check=${ANSIBLE_CACHE_CHECK}" >> "$GITHUB_OUTPUT" echo "build_args=${BUILD_ARGS}" >> "$GITHUB_OUTPUT" echo "tags=${TAGS}" >> "$GITHUB_OUTPUT" { @@ -165,6 +176,10 @@ jobs: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + - name: Check Ansible dependency layer cache + if: ${{ steps.metadata.outputs.ansible_cache_check == 'true' }} + timeout-minutes: 60 + run: bash tests/ansible/check_build_cache.sh "${{ steps.metadata.outputs.dockerfile }}" "${{ matrix.platforms }}" - name: Build and push id: docker_build uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a # v2.10.0 diff --git a/dockerfile/cuda11.1.1.dockerfile b/dockerfile/cuda11.1.1.dockerfile index 9126d8393..95596c126 100644 --- a/dockerfile/cuda11.1.1.dockerfile +++ b/dockerfile/cuda11.1.1.dockerfile @@ -1,4 +1,4 @@ -FROM nvcr.io/nvidia/pytorch:20.12-py3 +FROM nvcr.io/nvidia/pytorch:20.12-py3 AS ansible-dependencies # OS: # - Ubuntu: 20.04 @@ -63,6 +63,14 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* /opt/cmake-3.14.6-Linux-x86_64 +ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +COPY requirements /opt/sb-ansible/requirements +COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py +RUN python3 /opt/sb-ansible/scripts/install_ansible.py + +FROM ansible-dependencies AS benchmark + ARG NUM_MAKE_JOBS= # Install Docker @@ -168,6 +176,7 @@ RUN curl https://sh.rustup.rs -sSf | sh -s -- -y && \ ADD . . RUN python3 -m pip install --upgrade setuptools==65.7 importlib_metadata==6.8.0 && \ python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ make cppbuild && \ - make postinstall && \ + python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/cuda12.9.dockerfile b/dockerfile/cuda12.9.dockerfile index 1c2853b1d..d5f6e54b3 100644 --- a/dockerfile/cuda12.9.dockerfile +++ b/dockerfile/cuda12.9.dockerfile @@ -1,4 +1,4 @@ -FROM nvcr.io/nvidia/pytorch:25.05-py3 +FROM nvcr.io/nvidia/pytorch:25.05-py3 AS ansible-dependencies # OS: # - Ubuntu: 24.04 @@ -62,6 +62,14 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* +ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +COPY requirements /opt/sb-ansible/requirements +COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py +RUN python3 /opt/sb-ansible/scripts/install_ansible.py + +FROM ansible-dependencies AS benchmark + # Install CMake 3.30.4 for nvbench compatibility RUN apt-get update && \ apt-get remove -y cmake cmake-data && \ @@ -190,6 +198,7 @@ RUN make -C third_party cuda_with_msccl ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ make cppbuild && \ - make postinstall && \ + python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/cuda13.0.dockerfile b/dockerfile/cuda13.0.dockerfile index 7588de7fa..1621a1bff 100644 --- a/dockerfile/cuda13.0.dockerfile +++ b/dockerfile/cuda13.0.dockerfile @@ -1,4 +1,4 @@ -FROM nvcr.io/nvidia/pytorch:25.08-py3 +FROM nvcr.io/nvidia/pytorch:25.08-py3 AS ansible-dependencies # OS: # - Ubuntu: 24.04 @@ -62,6 +62,14 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* +ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +COPY requirements /opt/sb-ansible/requirements +COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py +RUN python3 /opt/sb-ansible/scripts/install_ansible.py + +FROM ansible-dependencies AS benchmark + ARG NUM_MAKE_JOBS= ARG TARGETPLATFORM ARG TARGETARCH @@ -157,6 +165,7 @@ RUN make -C third_party cuda ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ make cppbuild && \ - make postinstall && \ + python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/cuda13.4.dockerfile b/dockerfile/cuda13.4.dockerfile index b5fe246ba..ab4a0b28c 100644 --- a/dockerfile/cuda13.4.dockerfile +++ b/dockerfile/cuda13.4.dockerfile @@ -1,46 +1,4 @@ -# Build the streamOlympus STREAM variant in a separate stage. -mcpu=olympus needs GCC 15 and -# binutils 2.46, while the base image ships GCC 13 / binutils 2.42. Building it here keeps -# that toolchain (and its runtime libraries) out of the final image. -FROM nvcr.io/nvidia/pytorch:26.09-py3 AS stream-olympus-builder - -ARG NUM_MAKE_JOBS=64 -ENV DEBIAN_FRONTEND=noninteractive \ - BINUTILS_VERSION=2.46.1 \ - BINUTILS_SHA256=e127a709cba24c76de8936cb7083dd768f28cd37eb010492e2f19b71eb1294e4 - -COPY third_party/stream-tests/Makefile /build/Makefile - -RUN mkdir -p /out && \ - if [ "$(uname -m)" != "aarch64" ]; then \ - echo "Skipping streamOlympus for non-aarch64 architecture"; \ - exit 0; \ - fi && \ - apt-get update && \ - apt-get install -y --no-install-recommends \ - software-properties-common ca-certificates wget xz-utils zlib1g-dev libzstd-dev && \ - add-apt-repository -y ppa:ubuntu-toolchain-r/test && \ - apt-get update && \ - apt-get install -y --no-install-recommends gcc-15 && \ - cd /tmp && \ - for base in https://sourceware.org/pub/binutils/releases https://mirrors.kernel.org/gnu/binutils https://ftp.gnu.org/gnu/binutils; do \ - wget -nv --tries=3 --timeout=60 "${base}/binutils-${BINUTILS_VERSION}.tar.xz" -O binutils.tar.xz && break; \ - done && \ - echo "${BINUTILS_SHA256} binutils.tar.xz" | sha256sum -c - && \ - tar -xf binutils.tar.xz && \ - cd binutils-${BINUTILS_VERSION} && \ - ./configure --prefix=/opt/binutils-${BINUTILS_VERSION} \ - --with-system-zlib \ - --disable-werror \ - --disable-gprofng && \ - make -j "${NUM_MAKE_JOBS}" MAKEINFO=true && \ - make install MAKEINFO=true && \ - cd /build && \ - gcc-15 --version | head -n1 && \ - make OLYMPUS CC="gcc-15 -B/opt/binutils-${BINUTILS_VERSION}/bin/" && \ - sha256sum stream.c streamOlympus && \ - cp streamOlympus /out/ - -FROM nvcr.io/nvidia/pytorch:26.09-py3 +FROM nvcr.io/nvidia/pytorch:26.09-py3 AS ansible-dependencies # OS: # - Ubuntu: 24.04 @@ -116,6 +74,56 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* +ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +COPY requirements /opt/sb-ansible/requirements +COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py +RUN python3 /opt/sb-ansible/scripts/install_ansible.py + +# Build the streamOlympus STREAM variant in a separate stage. -mcpu=olympus needs GCC 15 and +# binutils 2.46, while the base image ships GCC 13 / binutils 2.42. Building it here keeps +# that toolchain (and its runtime libraries) out of the final image. +FROM ansible-dependencies AS stream-olympus-builder + +ARG NUM_MAKE_JOBS=64 +ENV DEBIAN_FRONTEND=noninteractive \ + BINUTILS_VERSION=2.46.1 \ + BINUTILS_SHA256=e127a709cba24c76de8936cb7083dd768f28cd37eb010492e2f19b71eb1294e4 + +COPY third_party/stream-tests/Makefile /build/Makefile + +RUN mkdir -p /out && \ + if [ "$(uname -m)" != "aarch64" ]; then \ + echo "Skipping streamOlympus for non-aarch64 architecture"; \ + exit 0; \ + fi && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + software-properties-common ca-certificates wget xz-utils zlib1g-dev libzstd-dev && \ + add-apt-repository -y ppa:ubuntu-toolchain-r/test && \ + apt-get update && \ + apt-get install -y --no-install-recommends gcc-15 && \ + cd /tmp && \ + for base in https://sourceware.org/pub/binutils/releases https://mirrors.kernel.org/gnu/binutils https://ftp.gnu.org/gnu/binutils; do \ + wget -nv --tries=3 --timeout=60 "${base}/binutils-${BINUTILS_VERSION}.tar.xz" -O binutils.tar.xz && break; \ + done && \ + echo "${BINUTILS_SHA256} binutils.tar.xz" | sha256sum -c - && \ + tar -xf binutils.tar.xz && \ + cd binutils-${BINUTILS_VERSION} && \ + ./configure --prefix=/opt/binutils-${BINUTILS_VERSION} \ + --with-system-zlib \ + --disable-werror \ + --disable-gprofng && \ + make -j "${NUM_MAKE_JOBS}" MAKEINFO=true && \ + make install MAKEINFO=true && \ + cd /build && \ + gcc-15 --version | head -n1 && \ + make OLYMPUS CC="gcc-15 -B/opt/binutils-${BINUTILS_VERSION}/bin/" && \ + sha256sum stream.c streamOlympus && \ + cp streamOlympus /out/ + +FROM ansible-dependencies AS benchmark + # Number of parallel jobs for the NVBench build. Override with --build-arg NUM_MAKE_JOBS=... ARG NUM_MAKE_JOBS=64 @@ -201,6 +209,7 @@ RUN f=${SB_MICRO_PATH}/bin/streamOlympus; \ ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ make cppbuild && \ - make postinstall && \ + python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/rocm6.3.x.dockerfile b/dockerfile/rocm6.3.x.dockerfile index dae4a4bf3..1bcdd8656 100644 --- a/dockerfile/rocm6.3.x.dockerfile +++ b/dockerfile/rocm6.3.x.dockerfile @@ -1,6 +1,6 @@ ARG BASE_IMAGE=rocm/pytorch-training:v25.6 -FROM ${BASE_IMAGE} +FROM ${BASE_IMAGE} AS ansible-dependencies # Base image: rocm/pytorch-training:v25.6 # Pre-installed by base image: @@ -66,6 +66,14 @@ RUN apt-get update && \ && \ rm -rf /tmp/* +ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +COPY requirements /opt/sb-ansible/requirements +COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py +RUN python3 /opt/sb-ansible/scripts/install_ansible.py + +FROM ansible-dependencies AS benchmark + # Install Docker ENV DOCKER_VERSION=27.5.1 RUN cd /tmp && \ @@ -144,6 +152,7 @@ ADD . . ENV USE_HIP_DATATYPE=1 ENV USE_HIPBLAS_COMPUTETYPE=1 RUN python3 -m pip install --no-build-isolation -c requirements/ansible.txt .[amdworker] && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ CXX=/opt/rocm/bin/hipcc make cppbuild && \ - make postinstall && \ + python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/rocm6.4.x.dockerfile b/dockerfile/rocm6.4.x.dockerfile index 6c45b0a6d..48c0f2aaa 100644 --- a/dockerfile/rocm6.4.x.dockerfile +++ b/dockerfile/rocm6.4.x.dockerfile @@ -1,6 +1,6 @@ ARG BASE_IMAGE=rocm/pytorch:rocm6.4.4_ubuntu24.04_py3.12_pytorch_release_2.7.1 -FROM ${BASE_IMAGE} +FROM ${BASE_IMAGE} AS ansible-dependencies # OS: # - Ubuntu: 24.04 @@ -66,6 +66,14 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /tmp/* +ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +COPY requirements /opt/sb-ansible/requirements +COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py +RUN python3 /opt/sb-ansible/scripts/install_ansible.py + +FROM ansible-dependencies AS benchmark + ARG NUM_MAKE_JOBS=64 # Check if CMake is installed and its version @@ -246,10 +254,12 @@ ADD . . ENV USE_HIP_DATATYPE=1 ENV USE_HIPBLAS_COMPUTETYPE=1 RUN python3 -m pip install -c requirements/ansible.txt .[amdworker] && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ CXX=/opt/rocm/bin/hipcc make cppbuild && \ - make postinstall && \ + python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git # Fix stale hypothesis plugin from base image (imports removed pkg_resources) # and add test dependencies missing from the base image. -RUN python3 -m pip install --upgrade hypothesis setuptools pytest-timeout vcrpy +RUN python3 -m pip install --upgrade hypothesis setuptools pytest-timeout vcrpy && \ + python3 /opt/sb-ansible/scripts/install_ansible.py --check diff --git a/docs/developer-guides/development.md b/docs/developer-guides/development.md index 86784941f..93ed49db4 100644 --- a/docs/developer-guides/development.md +++ b/docs/developer-guides/development.md @@ -73,6 +73,29 @@ container-internal `--no-docker`, or GPU image validation. Version pins and cache reuse do not make a cold build offline. Hash-verified offline artifacts and broader image reproducibility are outside this change. +### Dependency Layers in GPU Images + +Active GPU Dockerfiles install the profile in the `ansible-dependencies` stage, +before application source and benchmark compilation. Both CUDA 13.4 build +branches inherit that stage so its validation precedes the separate STREAM +compiler build as well. Later pip operations inherit `PIP_CONSTRAINT`, and +application installation is followed by a read-only profile check and local +collection tests rather than another online collection installation. + +The Build Image workflow checks the actual stage on dependency-related PRs: +a cold build must execute installation, an application-only edit must reuse it, +and a requirements edit must invalidate it. Other PRs do not force cold +dependency downloads. The check temporarily edits and restores two input files; +run it only in a disposable checkout: + +```bash +bash tests/ansible/check_build_cache.sh dockerfile/cuda11.1.1.dockerfile linux/amd64 +``` + +Changing the parent image or dependency inputs can still invalidate the layer. +The usual complete image matrix remains necessary to qualify both architectures +and detect conflicts with preinstalled GPU-framework dependencies. + ## Lint and Test Format code using yapf. diff --git a/tests/ansible/check_build_cache.sh b/tests/ansible/check_build_cache.sh new file mode 100644 index 000000000..5b2452ae6 --- /dev/null +++ b/tests/ansible/check_build_cache.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +set -euo pipefail + +usage() { + echo "Usage: $0 DOCKERFILE PLATFORM" + echo "Check the actual Ansible stage's cold build and cache invalidation in a disposable CI checkout." +} + +if [[ "${1:-}" == "--help" ]]; then + usage + exit 0 +fi +if [[ $# -ne 2 ]]; then + usage >&2 + exit 2 +fi + +cd "$(dirname "$0")/../.." +dockerfile="$1" +platform="$2" +if [[ ! -f "$dockerfile" || ! -f requirements/ansible.txt || ! -f README.md ]]; then + echo "Run this check against a SuperBench Dockerfile in a complete checkout." >&2 + exit 2 +fi + +scratch="$(mktemp -d)" +cp README.md "$scratch/README.md" +cp requirements/ansible.txt "$scratch/ansible.txt" +cleanup() { + cp "$scratch/README.md" README.md + cp "$scratch/ansible.txt" requirements/ansible.txt + rm -f "$scratch/README.md" "$scratch/ansible.txt" "$scratch/build.log" + rmdir "$scratch" +} +trap cleanup EXIT + +check_build() { + expected="$1" + shift + if ! docker buildx build --file "$dockerfile" --platform "$platform" \ + --target ansible-dependencies --progress=plain "$@" . > "$scratch/build.log" 2>&1; then + cat "$scratch/build.log" >&2 + return 1 + fi + cat "$scratch/build.log" + step="$(awk '/] RUN python3 \/opt\/sb-ansible\/scripts\/install_ansible.py$/ {print $1; exit}' "$scratch/build.log")" + if [[ -z "$step" ]]; then + echo "The build did not report the Ansible installation step." >&2 + return 1 + fi + if [[ "$expected" == "cached" ]]; then + if ! grep -Fxq "$step CACHED" "$scratch/build.log"; then + echo "An application-only change invalidated the Ansible dependency layer." >&2 + return 1 + fi + elif grep -Fxq "$step CACHED" "$scratch/build.log" || ! grep -Fq "$step DONE" "$scratch/build.log"; then + echo "The Ansible installation did not execute for a cold or changed-dependency build." >&2 + return 1 + fi +} + +check_build rebuilt --no-cache +printf '\n\n' >> README.md +check_build cached +printf '\n# Ansible dependency cache probe\n' >> requirements/ansible.txt +check_build rebuilt +echo "Verified cold installation, application-only cache reuse, and dependency-change invalidation." diff --git a/tests/ansible/test_dependencies.py b/tests/ansible/test_dependencies.py index fa3dae1f6..888cb1787 100644 --- a/tests/ansible/test_dependencies.py +++ b/tests/ansible/test_dependencies.py @@ -6,6 +6,7 @@ import importlib.util import json import os +import shutil import subprocess import sys import tempfile @@ -134,3 +135,53 @@ def test_installed_collections(self): command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120 ) self.assertEqual(result.returncode, 0, result.stdout) + + +@unittest.skipUnless(os.name == 'posix', 'The build-cache check uses Bash.') +class BuildCacheProbeTest(unittest.TestCase): + """Test cache-log assertions and input restoration without requiring Docker.""" + def test_cache_decisions_and_input_restoration(self): + """Reject unexpected cache behavior and restore the checkout on every exit.""" + for states, expected in [('DONE,CACHED,DONE', 0), ('CACHED', 1), ('DONE,DONE', 1), ('DONE,CACHED,CACHED', 1)]: + with self.subTest(states=states), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'tests' / 'ansible').mkdir(parents=True) + (root / 'requirements').mkdir() + (root / 'bin').mkdir() + readme = root / 'README.md' + requirements = root / 'requirements' / 'ansible.txt' + readme.write_text('original source\n') + requirements.write_text('original requirements\n') + (root / 'Dockerfile').touch() + counter = root / 'counter' + counter.write_text('0\n') + script = root / 'tests' / 'ansible' / 'check_build_cache.sh' + shutil.copyfile(Path(__file__).with_name('check_build_cache.sh'), script) + docker = root / 'bin' / 'docker' + docker.write_text( + '#!/bin/sh\nset -eu\n' + 'count=$(cat "$CACHE_COUNTER"); count=$((count + 1))\n' + 'printf "%s\\n" "$count" > "$CACHE_COUNTER"\n' + 'state=$(printf "%s" "$CACHE_STATES" | cut -d, -f"$count")\n' + 'echo "#7 [ansible-dependencies 6/6] RUN python3 /opt/sb-ansible/scripts/install_ansible.py"\n' + 'if [ "$state" = CACHED ]; then echo "#7 CACHED"; else echo "#7 DONE 0.1s"; fi\n' + ) + docker.chmod(0o755) + env = dict( + os.environ, + PATH=str(root / 'bin') + os.pathsep + os.environ['PATH'], + CACHE_COUNTER=str(counter), + CACHE_STATES=states + ) + result = subprocess.run( + ['bash', str(script), 'Dockerfile', 'linux/amd64'], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=20 + ) + self.assertEqual(result.returncode, expected, result.stdout) + self.assertEqual(int(counter.read_text()), len(states.split(','))) + self.assertEqual(readme.read_text(), 'original source\n') + self.assertEqual(requirements.read_text(), 'original requirements\n') From e596fa819732797354cf6883afb42f9dca387aab Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 16 Nov 2026 20:45:30 -0700 Subject: [PATCH 3/3] CI/CD - Simplify Ansible dependency installation Keep direct Python pins in one requirements file and collection pins with bounded retries in the existing Makefile. Reuse normal early Docker layers and existing CI instead of a custom installer, profile workflow and cache-probe framework. Validated cold installation, focused runner/retry tests and real collection operations on Python 3.8 and 3.12. Other transitive Python dependencies remain pip-managed; full GPU image qualification remains pending. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .azure-pipelines/cpu-unit-test.yml | 2 - .azure-pipelines/cuda-unit-test.yml | 2 +- .github/workflows/ansible-dependencies.yml | 51 ------ .github/workflows/build-image.yml | 15 -- Makefile | 16 +- dockerfile/cuda11.1.1.dockerfile | 16 +- dockerfile/cuda12.9.dockerfile | 15 +- dockerfile/cuda13.0.dockerfile | 15 +- dockerfile/cuda13.4.dockerfile | 99 ++++++----- dockerfile/rocm6.3.x.dockerfile | 15 +- dockerfile/rocm6.4.x.dockerfile | 18 +- docs/developer-guides/development.md | 101 +++-------- requirements/ansible-legacy.yml | 8 - requirements/ansible-modern.yml | 8 - requirements/ansible.in | 12 -- requirements/ansible.txt | 100 ++--------- scripts/install_ansible.py | 151 ----------------- tests/ansible/check_build_cache.sh | 70 -------- tests/ansible/test_dependencies.py | 187 --------------------- tests/ansible/test_dependencies.yaml | 78 --------- tests/runner/test_ansible.py | 56 ++++++ 21 files changed, 191 insertions(+), 844 deletions(-) delete mode 100644 .github/workflows/ansible-dependencies.yml delete mode 100644 requirements/ansible-legacy.yml delete mode 100644 requirements/ansible-modern.yml delete mode 100644 requirements/ansible.in delete mode 100644 scripts/install_ansible.py delete mode 100644 tests/ansible/check_build_cache.sh delete mode 100644 tests/ansible/test_dependencies.py delete mode 100644 tests/ansible/test_dependencies.yaml diff --git a/.azure-pipelines/cpu-unit-test.yml b/.azure-pipelines/cpu-unit-test.yml index efdb7615b..a61ea35da 100644 --- a/.azure-pipelines/cpu-unit-test.yml +++ b/.azure-pipelines/cpu-unit-test.yml @@ -27,8 +27,6 @@ steps: displayName: Export path - script: | set -e - apt-get update - apt-get install -y --no-install-recommends openssh-client rsync if python3 -c "import sys; exit(0 if sys.version_info < (3, 11) else 1)"; then python3 -m pip install --upgrade setuptools==65.7 fi diff --git a/.azure-pipelines/cuda-unit-test.yml b/.azure-pipelines/cuda-unit-test.yml index b024d5ff7..8807206d1 100644 --- a/.azure-pipelines/cuda-unit-test.yml +++ b/.azure-pipelines/cuda-unit-test.yml @@ -25,7 +25,7 @@ steps: "apt-get update -y -q && \ yes '' | apt-get install -y -q sudo && \ apt-get install -y -q \ - ffmpeg libavcodec-dev libavformat-dev libavutil-dev libboost-program-options-dev libswresample-dev openssh-client rsync" + ffmpeg libavcodec-dev libavformat-dev libavutil-dev libboost-program-options-dev libswresample-dev" python3 -m pip install --upgrade setuptools==65.7 python3 -m pip install -c requirements/ansible.txt .[test,nvworker] make postinstall diff --git a/.github/workflows/ansible-dependencies.yml b/.github/workflows/ansible-dependencies.yml deleted file mode 100644 index ec3bdc197..000000000 --- a/.github/workflows/ansible-dependencies.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Ansible Dependencies - -on: - pull_request: - paths: - - .github/workflows/ansible-dependencies.yml - - requirements/ansible* - - scripts/install_ansible.py - - setup.py - - Makefile - - superbench/runner/** - - tests/ansible/** - push: - branches: - - main - - release/* - paths: - - .github/workflows/ansible-dependencies.yml - - requirements/ansible* - - scripts/install_ansible.py - - setup.py - - Makefile - - superbench/runner/** - - tests/ansible/** - -permissions: - contents: read - -jobs: - collections: - name: Ansible Python ${{ matrix.python }} - runs-on: ubuntu-22.04 - timeout-minutes: 25 - strategy: - fail-fast: false - matrix: - python: ['3.7', '3.8', '3.10', '3.11', '3.12', '3.13'] - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 - with: - python-version: ${{ matrix.python }} - - name: Install local test tools - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends openssh-client rsync - - name: Install and exercise the dependency profile - run: | - python3 scripts/install_ansible.py - python3 -m unittest discover -s tests/ansible -p test_dependencies.py -v - python3 scripts/install_ansible.py --check diff --git a/.github/workflows/build-image.yml b/.github/workflows/build-image.yml index 44a7c54ed..4a04cb6e4 100644 --- a/.github/workflows/build-image.yml +++ b/.github/workflows/build-image.yml @@ -86,7 +86,6 @@ jobs: uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2.8.0 with: submodules: recursive - fetch-depth: 2 - name: Free disk space run: | mkdir -p /tmp/emptydir @@ -116,15 +115,6 @@ jobs: TAGS=$(sed "s/main:/dev:/g" <<< ${TAGS}) fi DOCKERFILE=dockerfile/${{ matrix.dockerfile }}.dockerfile - ANSIBLE_CACHE_CHECK=false - if [[ "${{ github.event_name }}" == "pull_request" ]]; then - CHANGED_ANSIBLE_INPUTS=$(git diff --name-only HEAD^1 HEAD -- \ - requirements scripts/install_ansible.py tests/ansible/check_build_cache.sh \ - .github/workflows/build-image.yml "$DOCKERFILE") - if [[ -n "$CHANGED_ANSIBLE_INPUTS" ]]; then - ANSIBLE_CACHE_CHECK=true - fi - fi BUILD_ARGS=${{ matrix.build_args }} if [[ "${{ matrix.extra_args }}" ]]; then @@ -145,7 +135,6 @@ jobs: fi echo "dockerfile=${DOCKERFILE}" >> "$GITHUB_OUTPUT" - echo "ansible_cache_check=${ANSIBLE_CACHE_CHECK}" >> "$GITHUB_OUTPUT" echo "build_args=${BUILD_ARGS}" >> "$GITHUB_OUTPUT" echo "tags=${TAGS}" >> "$GITHUB_OUTPUT" { @@ -176,10 +165,6 @@ jobs: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Check Ansible dependency layer cache - if: ${{ steps.metadata.outputs.ansible_cache_check == 'true' }} - timeout-minutes: 60 - run: bash tests/ansible/check_build_cache.sh "${{ steps.metadata.outputs.dockerfile }}" "${{ matrix.platforms }}" - name: Build and push id: docker_build uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a # v2.10.0 diff --git a/Makefile b/Makefile index d749b3132..d29046dcc 100644 --- a/Makefile +++ b/Makefile @@ -21,4 +21,18 @@ thirdparty: cd ./third_party/ && make all postinstall: - python3 scripts/install_ansible.py + @command -v ansible-galaxy >/dev/null || { echo "Cannot find ansible-galaxy" >&2; exit 1; } + @profile=$$(python3 -c 'import sys; print("legacy" if sys.version_info < (3, 11) else "modern")') || exit $$?; \ + if [ "$$profile" = legacy ]; then \ + collections="ansible.posix:1.5.4 ansible.utils:2.12.0 community.crypto:2.16.0"; \ + else \ + collections="ansible.posix:2.2.2 ansible.utils:6.1.1 community.crypto:3.5.1"; \ + fi; \ + for attempt in 1 2 3; do \ + timeout 300 ansible-galaxy collection install $$collections && exit 0; \ + status=$$?; \ + echo "Ansible collections: attempt $$attempt/3 failed (exit $$status)." >&2; \ + if [ $$attempt -eq 3 ]; then exit $$status; fi; \ + echo "Retrying in $$((attempt * 10)) seconds." >&2; \ + sleep $$((attempt * 10)) || exit $$?; \ + done diff --git a/dockerfile/cuda11.1.1.dockerfile b/dockerfile/cuda11.1.1.dockerfile index 95596c126..423c164d3 100644 --- a/dockerfile/cuda11.1.1.dockerfile +++ b/dockerfile/cuda11.1.1.dockerfile @@ -1,4 +1,4 @@ -FROM nvcr.io/nvidia/pytorch:20.12-py3 AS ansible-dependencies +FROM nvcr.io/nvidia/pytorch:20.12-py3 # OS: # - Ubuntu: 20.04 @@ -47,7 +47,6 @@ RUN apt-get update && \ openssh-client \ openssh-server \ pciutils \ - rsync \ sudo \ util-linux \ vim \ @@ -65,11 +64,10 @@ RUN apt-get update && \ ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections -COPY requirements /opt/sb-ansible/requirements -COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py -RUN python3 /opt/sb-ansible/scripts/install_ansible.py - -FROM ansible-dependencies AS benchmark +COPY requirements/ansible.txt /opt/sb-ansible/requirements/ansible.txt +COPY Makefile /opt/sb-ansible/Makefile +RUN python3 -m pip install --no-cache-dir -r "$PIP_CONSTRAINT" && \ + make -C /opt/sb-ansible postinstall ARG NUM_MAKE_JOBS= @@ -175,8 +173,6 @@ RUN curl https://sh.rustup.rs -sSf | sh -s -- -y && \ ADD . . RUN python3 -m pip install --upgrade setuptools==65.7 importlib_metadata==6.8.0 && \ - python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ + python3 -m pip install --no-cache-dir .[nvworker] && \ make cppbuild && \ - python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/cuda12.9.dockerfile b/dockerfile/cuda12.9.dockerfile index d5f6e54b3..2c15347fa 100644 --- a/dockerfile/cuda12.9.dockerfile +++ b/dockerfile/cuda12.9.dockerfile @@ -1,4 +1,4 @@ -FROM nvcr.io/nvidia/pytorch:25.05-py3 AS ansible-dependencies +FROM nvcr.io/nvidia/pytorch:25.05-py3 # OS: # - Ubuntu: 24.04 @@ -64,11 +64,10 @@ RUN apt-get update && \ ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections -COPY requirements /opt/sb-ansible/requirements -COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py -RUN python3 /opt/sb-ansible/scripts/install_ansible.py - -FROM ansible-dependencies AS benchmark +COPY requirements/ansible.txt /opt/sb-ansible/requirements/ansible.txt +COPY Makefile /opt/sb-ansible/Makefile +RUN python3 -m pip install --no-cache-dir -r "$PIP_CONSTRAINT" && \ + make -C /opt/sb-ansible postinstall # Install CMake 3.30.4 for nvbench compatibility RUN apt-get update && \ @@ -197,8 +196,6 @@ RUN make -C third_party cuda_with_msccl ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ - python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ + python3 -m pip install --no-cache-dir .[nvworker] && \ make cppbuild && \ - python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/cuda13.0.dockerfile b/dockerfile/cuda13.0.dockerfile index 1621a1bff..1f81b6025 100644 --- a/dockerfile/cuda13.0.dockerfile +++ b/dockerfile/cuda13.0.dockerfile @@ -1,4 +1,4 @@ -FROM nvcr.io/nvidia/pytorch:25.08-py3 AS ansible-dependencies +FROM nvcr.io/nvidia/pytorch:25.08-py3 # OS: # - Ubuntu: 24.04 @@ -64,11 +64,10 @@ RUN apt-get update && \ ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections -COPY requirements /opt/sb-ansible/requirements -COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py -RUN python3 /opt/sb-ansible/scripts/install_ansible.py - -FROM ansible-dependencies AS benchmark +COPY requirements/ansible.txt /opt/sb-ansible/requirements/ansible.txt +COPY Makefile /opt/sb-ansible/Makefile +RUN python3 -m pip install --no-cache-dir -r "$PIP_CONSTRAINT" && \ + make -C /opt/sb-ansible postinstall ARG NUM_MAKE_JOBS= ARG TARGETPLATFORM @@ -164,8 +163,6 @@ RUN make -C third_party cuda ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ - python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ + python3 -m pip install --no-cache-dir .[nvworker] && \ make cppbuild && \ - python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/cuda13.4.dockerfile b/dockerfile/cuda13.4.dockerfile index ab4a0b28c..429ff6e00 100644 --- a/dockerfile/cuda13.4.dockerfile +++ b/dockerfile/cuda13.4.dockerfile @@ -1,4 +1,46 @@ -FROM nvcr.io/nvidia/pytorch:26.09-py3 AS ansible-dependencies +# Build the streamOlympus STREAM variant in a separate stage. -mcpu=olympus needs GCC 15 and +# binutils 2.46, while the base image ships GCC 13 / binutils 2.42. Building it here keeps +# that toolchain (and its runtime libraries) out of the final image. +FROM nvcr.io/nvidia/pytorch:26.09-py3 AS stream-olympus-builder + +ARG NUM_MAKE_JOBS=64 +ENV DEBIAN_FRONTEND=noninteractive \ + BINUTILS_VERSION=2.46.1 \ + BINUTILS_SHA256=e127a709cba24c76de8936cb7083dd768f28cd37eb010492e2f19b71eb1294e4 + +COPY third_party/stream-tests/Makefile /build/Makefile + +RUN mkdir -p /out && \ + if [ "$(uname -m)" != "aarch64" ]; then \ + echo "Skipping streamOlympus for non-aarch64 architecture"; \ + exit 0; \ + fi && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + software-properties-common ca-certificates wget xz-utils zlib1g-dev libzstd-dev && \ + add-apt-repository -y ppa:ubuntu-toolchain-r/test && \ + apt-get update && \ + apt-get install -y --no-install-recommends gcc-15 && \ + cd /tmp && \ + for base in https://sourceware.org/pub/binutils/releases https://mirrors.kernel.org/gnu/binutils https://ftp.gnu.org/gnu/binutils; do \ + wget -nv --tries=3 --timeout=60 "${base}/binutils-${BINUTILS_VERSION}.tar.xz" -O binutils.tar.xz && break; \ + done && \ + echo "${BINUTILS_SHA256} binutils.tar.xz" | sha256sum -c - && \ + tar -xf binutils.tar.xz && \ + cd binutils-${BINUTILS_VERSION} && \ + ./configure --prefix=/opt/binutils-${BINUTILS_VERSION} \ + --with-system-zlib \ + --disable-werror \ + --disable-gprofng && \ + make -j "${NUM_MAKE_JOBS}" MAKEINFO=true && \ + make install MAKEINFO=true && \ + cd /build && \ + gcc-15 --version | head -n1 && \ + make OLYMPUS CC="gcc-15 -B/opt/binutils-${BINUTILS_VERSION}/bin/" && \ + sha256sum stream.c streamOlympus && \ + cp streamOlympus /out/ + +FROM nvcr.io/nvidia/pytorch:26.09-py3 # OS: # - Ubuntu: 24.04 @@ -76,53 +118,10 @@ RUN apt-get update && \ ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections -COPY requirements /opt/sb-ansible/requirements -COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py -RUN python3 /opt/sb-ansible/scripts/install_ansible.py - -# Build the streamOlympus STREAM variant in a separate stage. -mcpu=olympus needs GCC 15 and -# binutils 2.46, while the base image ships GCC 13 / binutils 2.42. Building it here keeps -# that toolchain (and its runtime libraries) out of the final image. -FROM ansible-dependencies AS stream-olympus-builder - -ARG NUM_MAKE_JOBS=64 -ENV DEBIAN_FRONTEND=noninteractive \ - BINUTILS_VERSION=2.46.1 \ - BINUTILS_SHA256=e127a709cba24c76de8936cb7083dd768f28cd37eb010492e2f19b71eb1294e4 - -COPY third_party/stream-tests/Makefile /build/Makefile - -RUN mkdir -p /out && \ - if [ "$(uname -m)" != "aarch64" ]; then \ - echo "Skipping streamOlympus for non-aarch64 architecture"; \ - exit 0; \ - fi && \ - apt-get update && \ - apt-get install -y --no-install-recommends \ - software-properties-common ca-certificates wget xz-utils zlib1g-dev libzstd-dev && \ - add-apt-repository -y ppa:ubuntu-toolchain-r/test && \ - apt-get update && \ - apt-get install -y --no-install-recommends gcc-15 && \ - cd /tmp && \ - for base in https://sourceware.org/pub/binutils/releases https://mirrors.kernel.org/gnu/binutils https://ftp.gnu.org/gnu/binutils; do \ - wget -nv --tries=3 --timeout=60 "${base}/binutils-${BINUTILS_VERSION}.tar.xz" -O binutils.tar.xz && break; \ - done && \ - echo "${BINUTILS_SHA256} binutils.tar.xz" | sha256sum -c - && \ - tar -xf binutils.tar.xz && \ - cd binutils-${BINUTILS_VERSION} && \ - ./configure --prefix=/opt/binutils-${BINUTILS_VERSION} \ - --with-system-zlib \ - --disable-werror \ - --disable-gprofng && \ - make -j "${NUM_MAKE_JOBS}" MAKEINFO=true && \ - make install MAKEINFO=true && \ - cd /build && \ - gcc-15 --version | head -n1 && \ - make OLYMPUS CC="gcc-15 -B/opt/binutils-${BINUTILS_VERSION}/bin/" && \ - sha256sum stream.c streamOlympus && \ - cp streamOlympus /out/ - -FROM ansible-dependencies AS benchmark +COPY requirements/ansible.txt /opt/sb-ansible/requirements/ansible.txt +COPY Makefile /opt/sb-ansible/Makefile +RUN python3 -m pip install --no-cache-dir -r "$PIP_CONSTRAINT" && \ + make -C /opt/sb-ansible postinstall # Number of parallel jobs for the NVBench build. Override with --build-arg NUM_MAKE_JOBS=... ARG NUM_MAKE_JOBS=64 @@ -208,8 +207,6 @@ RUN f=${SB_MICRO_PATH}/bin/streamOlympus; \ ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ - python3 -m pip install --no-cache-dir -c requirements/ansible.txt .[nvworker] && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ + python3 -m pip install --no-cache-dir .[nvworker] && \ make cppbuild && \ - python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/rocm6.3.x.dockerfile b/dockerfile/rocm6.3.x.dockerfile index 1bcdd8656..8723f1a10 100644 --- a/dockerfile/rocm6.3.x.dockerfile +++ b/dockerfile/rocm6.3.x.dockerfile @@ -1,6 +1,6 @@ ARG BASE_IMAGE=rocm/pytorch-training:v25.6 -FROM ${BASE_IMAGE} AS ansible-dependencies +FROM ${BASE_IMAGE} # Base image: rocm/pytorch-training:v25.6 # Pre-installed by base image: @@ -68,11 +68,10 @@ RUN apt-get update && \ ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections -COPY requirements /opt/sb-ansible/requirements -COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py -RUN python3 /opt/sb-ansible/scripts/install_ansible.py - -FROM ansible-dependencies AS benchmark +COPY requirements/ansible.txt /opt/sb-ansible/requirements/ansible.txt +COPY Makefile /opt/sb-ansible/Makefile +RUN python3 -m pip install --no-cache-dir -r "$PIP_CONSTRAINT" && \ + make -C /opt/sb-ansible postinstall # Install Docker ENV DOCKER_VERSION=27.5.1 @@ -151,8 +150,6 @@ RUN make RCCL_HOME=/opt/rocm ROCBLAS_BRANCH=release-staging/rocm-rel-6.3 HIPBLAS ADD . . ENV USE_HIP_DATATYPE=1 ENV USE_HIPBLAS_COMPUTETYPE=1 -RUN python3 -m pip install --no-build-isolation -c requirements/ansible.txt .[amdworker] && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ +RUN python3 -m pip install --no-build-isolation .[amdworker] && \ CXX=/opt/rocm/bin/hipcc make cppbuild && \ - python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git diff --git a/dockerfile/rocm6.4.x.dockerfile b/dockerfile/rocm6.4.x.dockerfile index 48c0f2aaa..5e4e2d9d8 100644 --- a/dockerfile/rocm6.4.x.dockerfile +++ b/dockerfile/rocm6.4.x.dockerfile @@ -1,6 +1,6 @@ ARG BASE_IMAGE=rocm/pytorch:rocm6.4.4_ubuntu24.04_py3.12_pytorch_release_2.7.1 -FROM ${BASE_IMAGE} AS ansible-dependencies +FROM ${BASE_IMAGE} # OS: # - Ubuntu: 24.04 @@ -68,11 +68,10 @@ RUN apt-get update && \ ENV PIP_CONSTRAINT=/opt/sb-ansible/requirements/ansible.txt \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections -COPY requirements /opt/sb-ansible/requirements -COPY scripts/install_ansible.py /opt/sb-ansible/scripts/install_ansible.py -RUN python3 /opt/sb-ansible/scripts/install_ansible.py - -FROM ansible-dependencies AS benchmark +COPY requirements/ansible.txt /opt/sb-ansible/requirements/ansible.txt +COPY Makefile /opt/sb-ansible/Makefile +RUN python3 -m pip install --no-cache-dir -r "$PIP_CONSTRAINT" && \ + make -C /opt/sb-ansible postinstall ARG NUM_MAKE_JOBS=64 @@ -253,13 +252,10 @@ RUN python3 -c "import transformer_engine.pytorch; print('TE installed successfu ADD . . ENV USE_HIP_DATATYPE=1 ENV USE_HIPBLAS_COMPUTETYPE=1 -RUN python3 -m pip install -c requirements/ansible.txt .[amdworker] && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check && \ +RUN python3 -m pip install .[amdworker] && \ CXX=/opt/rocm/bin/hipcc make cppbuild && \ - python3 -m unittest discover -s tests/ansible -p test_dependencies.py && \ rm -rf .git # Fix stale hypothesis plugin from base image (imports removed pkg_resources) # and add test dependencies missing from the base image. -RUN python3 -m pip install --upgrade hypothesis setuptools pytest-timeout vcrpy && \ - python3 /opt/sb-ansible/scripts/install_ansible.py --check +RUN python3 -m pip install --upgrade hypothesis setuptools pytest-timeout vcrpy diff --git a/docs/developer-guides/development.md b/docs/developer-guides/development.md index 93ed49db4..1d32a91b6 100644 --- a/docs/developer-guides/development.md +++ b/docs/developer-guides/development.md @@ -19,82 +19,37 @@ Follow [System Requirements](../getting-started/installation.mdx). git clone --recurse-submodules -j8 https://github.com/microsoft/superbenchmark cd superbenchmark -python3 scripts/install_ansible.py python3 -m pip install -c requirements/ansible.txt -e .[develop] -python3 scripts/install_ansible.py --check +make postinstall ``` -The POSIX control environment also needs `openssh-client` and `rsync`. -Use a clean Python environment; do not install the bundled `ansible` distribution -alongside `ansible-base` or `ansible-core`. - -### Ansible Dependency Profiles - -The Python freeze in `requirements/ansible.txt` includes the engine, runner and -their transitive Python dependencies. Collections are pinned separately: - -| Control Python | Engine | Runner | Collections | -| --- | --- | --- | --- | -| 3.7-3.10 | ansible-base 2.10.17 | 2.3.1 | `ansible-legacy.yml` | -| 3.11 | ansible-core 2.19.15 | 2.4.3 | `ansible-modern.yml` | -| 3.12 | ansible-core 2.21.6 | 2.4.3 | `ansible-modern.yml` | -| 3.13+ | ansible-core 2.22.0 | 2.4.3 | `ansible-modern.yml` | - -These are deployment inputs, not a promise that every future Python release is -supported. The old 2.10 engine is end-of-life; retaining it is a compatibility -bridge for existing images, not a long-term support solution. Engine and Python -support lifetimes must be reviewed when updating profiles. Control Python and -managed-host Python have separate compatibility requirements. - -`make postinstall` installs and checks the selected profile. The installer uses -the current Python interpreter, checks collection engine requirements, and -reports the paths of the plugins actually loaded. `--check` is read-only and -does not contact Galaxy. Use it after installing SuperBench to detect dependency -drift or a different collection shadowing the pinned copy. - -Only the Galaxy acquisition command has an external retry loop: at most three -attempts, each limited to 300 seconds, with 10- and 20-second waits. Logs are -preserved and exhaustion fails the build. Pip retains its own network handling; -do not add another retry around the entire Docker build or workflow. - -To update dependencies, edit `requirements/ansible.in`, regenerate the Python -freeze, update the collection requirements, and validate every affected profile: - -```bash -uv pip compile --universal --python-version 3.7 requirements/ansible.in --output-file requirements/ansible.txt -python3 scripts/install_ansible.py -python3 -m pytest -q tests/ansible/test_dependencies.py tests/runner/test_ansible.py -``` - -The local collection test generates disposable keys without logging private key -contents, checks rank lookup and idempotency, and exercises the production -result-fetch playbook on local files. It does not replace remote deployment, -container-internal `--no-docker`, or GPU image validation. -Version pins and cache reuse do not make a cold build offline. Hash-verified -offline artifacts and broader image reproducibility are outside this change. - -### Dependency Layers in GPU Images - -Active GPU Dockerfiles install the profile in the `ansible-dependencies` stage, -before application source and benchmark compilation. Both CUDA 13.4 build -branches inherit that stage so its validation precedes the separate STREAM -compiler build as well. Later pip operations inherit `PIP_CONSTRAINT`, and -application installation is followed by a read-only profile check and local -collection tests rather than another online collection installation. - -The Build Image workflow checks the actual stage on dependency-related PRs: -a cold build must execute installation, an application-only edit must reuse it, -and a requirements edit must invalidate it. Other PRs do not force cold -dependency downloads. The check temporarily edits and restores two input files; -run it only in a disposable checkout: - -```bash -bash tests/ansible/check_build_cache.sh dockerfile/cuda11.1.1.dockerfile linux/amd64 -``` - -Changing the parent image or dependency inputs can still invalidate the layer. -The usual complete image matrix remains necessary to qualify both architectures -and detect conflicts with preinstalled GPU-framework dependencies. +Use a clean Python environment without the bundled `ansible` distribution. +The Linux control environment needs GNU `timeout`, `openssh-client` and `rsync`. + +### Ansible Dependencies + +[requirements/ansible.txt](../../requirements/ansible.txt) pins the engine, +runner and Jinja2 for each supported Python family. Other transitive dependencies +remain managed by pip; this is not a complete environment lock. +[Makefile](../../Makefile) pins the three collections, using a legacy set for +Python 3.7-3.10 and a modern set for Python 3.11+. The legacy Ansible 2.10 engine +is end-of-life and remains a compatibility bridge, not a long-term support promise. + +`make postinstall` installs collections with at most three attempts, a +300-second timeout per attempt, and 10- and 20-second waits. Exhaustion fails +the build. Pip retains its own retry handling. + +The main GPU image stage installs these dependencies before copying application +source or building benchmarks; CUDA 13.4's separate STREAM stage is unchanged. +The images reuse normal Docker layer caching and retain `PIP_CONSTRAINT` for +later pip commands. A cold build still needs the network; the existing Build +Image workflow is unchanged. + +To update versions, edit the requirements file and Makefile together. Run +`python3 -m pytest -q tests/runner/test_ansible.py`, the existing Ansible +integration tests, and the affected image builds before merging. Check both +legacy and modern runtimes; local runner tests alone do not qualify GPU images +or remote deployment. ## Lint and Test diff --git a/requirements/ansible-legacy.yml b/requirements/ansible-legacy.yml deleted file mode 100644 index 853465fcf..000000000 --- a/requirements/ansible-legacy.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- -collections: - - name: ansible.posix - version: 1.5.4 - - name: ansible.utils - version: 2.12.0 - - name: community.crypto - version: 2.16.0 diff --git a/requirements/ansible-modern.yml b/requirements/ansible-modern.yml deleted file mode 100644 index b467c543d..000000000 --- a/requirements/ansible-modern.yml +++ /dev/null @@ -1,8 +0,0 @@ ---- -collections: - - name: ansible.posix - version: 2.2.2 - - name: ansible.utils - version: 6.1.1 - - name: community.crypto - version: 3.5.1 diff --git a/requirements/ansible.in b/requirements/ansible.in deleted file mode 100644 index 4d0d5a3d4..000000000 --- a/requirements/ansible.in +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -# Preserve the existing Python <= 3.10 control runtime while legacy images remain supported. -ansible-base==2.10.17; python_version < "3.11" -ansible-runner==2.3.1; python_version < "3.11" -Jinja2<3.1; python_version < "3.11" - -ansible-core==2.19.15; python_version == "3.11" -ansible-core==2.21.6; python_version == "3.12" -ansible-core==2.22.0; python_version >= "3.13" -ansible-runner==2.4.3; python_version >= "3.11" diff --git a/requirements/ansible.txt b/requirements/ansible.txt index 5eee672a4..8a920f18a 100644 --- a/requirements/ansible.txt +++ b/requirements/ansible.txt @@ -1,88 +1,12 @@ -# This file was autogenerated by uv via the following command: -# uv pip compile --universal --python-version 3.7 requirements/ansible.in --output-file requirements/ansible.txt -ansible-base==2.10.17 ; python_full_version < '3.11' - # via -r requirements/ansible.in -ansible-core==2.19.15 ; python_full_version == '3.11.*' - # via -r requirements/ansible.in -ansible-core==2.21.6 ; python_full_version == '3.12.*' - # via -r requirements/ansible.in -ansible-core==2.22.0 ; python_full_version >= '3.13' - # via -r requirements/ansible.in -ansible-runner==2.3.1 ; python_full_version < '3.11' - # via -r requirements/ansible.in -ansible-runner==2.4.3 ; python_full_version >= '3.11' - # via -r requirements/ansible.in -cffi==1.15.1 ; python_full_version < '3.8' and platform_python_implementation != 'PyPy' - # via cryptography -cffi==1.17.1 ; python_full_version == '3.8.*' and platform_python_implementation != 'PyPy' - # via cryptography -cffi==2.0.0 ; python_full_version == '3.9.*' and platform_python_implementation != 'PyPy' - # via cryptography -cffi==2.1.1 ; python_full_version >= '3.10' and platform_python_implementation != 'PyPy' - # via cryptography -cryptography==45.0.7 ; python_full_version < '3.8' - # via ansible-base -cryptography==47.0.0 ; python_full_version >= '3.8' and python_full_version <= '3.9' - # via ansible-base -cryptography==50.0.2 ; python_full_version > '3.9' - # via - # ansible-base - # ansible-core -jinja2==3.0.3 ; python_full_version < '3.11' - # via - # -r requirements/ansible.in - # ansible-base -jinja2==3.1.6 ; python_full_version >= '3.11' - # via - # -r requirements/ansible.in - # ansible-core -lockfile==0.12.2 - # via python-daemon -markupsafe==2.1.5 ; python_full_version < '3.9' - # via jinja2 -markupsafe==3.0.4 ; python_full_version >= '3.9' - # via jinja2 -packaging==24.0 ; python_full_version < '3.8' - # via - # ansible-base - # ansible-runner -packaging==26.2 ; python_full_version == '3.8.*' - # via - # ansible-base - # ansible-runner -packaging==26.3 ; python_full_version >= '3.9' - # via - # ansible-base - # ansible-core - # ansible-runner -pexpect==4.9.0 - # via ansible-runner -ptyprocess==0.7.0 - # via pexpect -pycparser==2.21 ; python_full_version < '3.8' and platform_python_implementation != 'PyPy' - # via cffi -pycparser==2.23 ; (python_full_version == '3.9.*' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy') or (python_full_version == '3.8.*' and platform_python_implementation != 'PyPy') - # via cffi -pycparser==3.11 ; python_full_version == '3.10.*' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' - # via cffi -pycparser==3.12 ; python_full_version >= '3.11' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' - # via cffi -python-daemon==3.1.2 - # via ansible-runner -pyyaml==6.0.1 ; python_full_version < '3.8' - # via - # ansible-base - # ansible-runner -pyyaml==6.0.3 ; python_full_version >= '3.8' - # via - # ansible-base - # ansible-core - # ansible-runner -resolvelib==1.2.1 ; python_full_version >= '3.11' - # via ansible-core -six==1.17.0 ; python_full_version < '3.11' - # via ansible-runner -typing-extensions==4.13.2 ; python_full_version == '3.8.*' - # via cryptography -typing-extensions==4.16.0 ; python_full_version >= '3.9' and python_full_version < '3.11' - # via cryptography +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +ansible-base==2.10.17; python_version < "3.11" +ansible-core==2.19.15; python_version == "3.11" +ansible-core==2.21.6; python_version == "3.12" +ansible-core==2.22.0; python_version >= "3.13" +ansible-runner==2.3.1; python_version < "3.11" +ansible-runner==2.4.3; python_version >= "3.11" +# Ansible 2.10 uses filter imports removed in Jinja2 3.1. +Jinja2==3.0.3; python_version < "3.11" +Jinja2==3.1.6; python_version >= "3.11" diff --git a/scripts/install_ansible.py b/scripts/install_ansible.py deleted file mode 100644 index a9e88ac17..000000000 --- a/scripts/install_ansible.py +++ /dev/null @@ -1,151 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""Install or check the frozen Ansible environment without importing SuperBench.""" - -import argparse -import json -import re -import shutil -import subprocess -import sys -import sysconfig -import time -from pathlib import Path - -REQUIREMENTS = Path(__file__).resolve().parents[1] / 'requirements' - - -def ansible_command(name): - """Run an Ansible entry point with the same interpreter as the application.""" - script = Path(sysconfig.get_path('scripts')) / name - if not script.is_file(): - found = shutil.which(name) - if not found: - raise RuntimeError('Cannot find {} for {}.'.format(name, sys.executable)) - script = Path(found) - return [sys.executable, str(script)] - - -def install_collections(command): - """Retry collection acquisition at most three times within a bounded budget.""" - for attempt in range(1, 4): - try: - result = subprocess.run(command, timeout=300) - returncode = result.returncode - except subprocess.TimeoutExpired: - print('Collection installation exceeded 300 seconds.', file=sys.stderr, flush=True) - returncode = 124 - if returncode == 0: - return - print( - 'Collection installation attempt {}/3 failed (exit {}).'.format(attempt, returncode), - file=sys.stderr, - flush=True, - ) - if attempt == 3: - raise subprocess.CalledProcessError(returncode, command) - delay = attempt * 10 - print('Retrying in {} seconds.'.format(delay), file=sys.stderr, flush=True) - time.sleep(delay) - - -def installed_packages(): - """Read installed distribution metadata without importing the engine.""" - packages = json.loads( - subprocess.check_output( - [sys.executable, '-m', 'pip', 'list', '--format=json', '--disable-pip-version-check'], text=True - ) - ) - return {re.sub(r'[-_.]+', '-', package['name']).lower(): package['version'] for package in packages} - - -def check_python(): - """Fail if application installation changed any frozen Python dependency.""" - from packaging.requirements import Requirement - from packaging.utils import canonicalize_name - - installed = installed_packages() - if 'ansible' in installed or ('ansible-base' in installed and 'ansible-core' in installed): - raise RuntimeError('Use a clean environment: do not mix ansible, ansible-base and ansible-core distributions.') - for line in (REQUIREMENTS / 'ansible.txt').read_text().splitlines(): - if not line.strip() or line.lstrip().startswith('#'): - continue - requirement = Requirement(line) - if requirement.marker and not requirement.marker.evaluate(): - continue - version = installed.get(canonicalize_name(requirement.name)) - if version is None or not requirement.specifier.contains(version): - raise RuntimeError('{} is required, but {} is installed.'.format(requirement, version)) - print('{}=={}'.format(requirement.name, version)) - - -def check_collections(requirements): - """Check the versions, engine support and paths of the plugins actually loaded.""" - import yaml - from ansible.release import __version__ as engine_version - from packaging.specifiers import SpecifierSet - - expected = {item['name']: str(item['version']) for item in yaml.safe_load(requirements.read_text())['collections']} - plugins = [ - ('module', 'community.crypto.openssh_keypair'), - ('module', 'ansible.posix.synchronize'), - ('lookup', 'ansible.utils.index_of'), - ] - for plugin_type, plugin in plugins: - command = ansible_command('ansible-doc') + ['--json', '-t', plugin_type, plugin] - documentation = json.loads(subprocess.check_output(command, text=True)) - if plugin not in documentation: - raise RuntimeError('Cannot load required plugin {}.'.format(plugin)) - collection = Path(documentation[plugin]['doc']['filename']).resolve().parents[2] - metadata = json.loads((collection / 'MANIFEST.json').read_text())['collection_info'] - name = '{}.{}'.format(metadata['namespace'], metadata['name']) - if metadata['version'] != expected[name]: - raise RuntimeError( - '{}: expected {}, loaded {} from {}.'.format(name, expected[name], metadata['version'], collection) - ) - runtime = yaml.safe_load((collection / 'meta' / 'runtime.yml').read_text()) - if not SpecifierSet(runtime['requires_ansible']).contains(engine_version): - raise RuntimeError( - '{} requires Ansible {}, not {}.'.format(name, runtime['requires_ansible'], engine_version) - ) - for dependency, versions in metadata['dependencies'].items(): - if dependency not in expected or not SpecifierSet(versions).contains(expected[dependency]): - raise RuntimeError('Pin the {} dependency of {} in {}.'.format(dependency, name, requirements)) - print('{}=={} ({})'.format(name, metadata['version'], collection)) - - -def main(): - """Install the selected profile, or verify it without network access.""" - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - '--check', action='store_true', help='Check installed versions and effective plugin paths only.' - ) - args = parser.parse_args() - profile = 'legacy' if sys.version_info[:2] < (3, 11) else 'modern' - collections = REQUIREMENTS / 'ansible-{}.yml'.format(profile) - try: - if not args.check: - incompatible = 'ansible-core' if profile == 'legacy' else 'ansible-base' - if {'ansible', incompatible}.intersection(installed_packages()): - raise RuntimeError('Create a clean environment before changing Ansible distributions.') - subprocess.run( - [sys.executable, '-m', 'pip', 'install', '-r', - str(REQUIREMENTS / 'ansible.txt')], check=True - ) - check_python() - if not args.check: - install_collections( - ansible_command('ansible-galaxy') + - ['collection', 'install', '--server', 'https://galaxy.ansible.com', '-r', - str(collections)] - ) - check_collections(collections) - except (RuntimeError, subprocess.CalledProcessError) as error: - print('Ansible dependency setup failed: {}'.format(error), file=sys.stderr) - return error.returncode if isinstance(error, subprocess.CalledProcessError) else 1 - return 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tests/ansible/check_build_cache.sh b/tests/ansible/check_build_cache.sh deleted file mode 100644 index 5b2452ae6..000000000 --- a/tests/ansible/check_build_cache.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/bash -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -set -euo pipefail - -usage() { - echo "Usage: $0 DOCKERFILE PLATFORM" - echo "Check the actual Ansible stage's cold build and cache invalidation in a disposable CI checkout." -} - -if [[ "${1:-}" == "--help" ]]; then - usage - exit 0 -fi -if [[ $# -ne 2 ]]; then - usage >&2 - exit 2 -fi - -cd "$(dirname "$0")/../.." -dockerfile="$1" -platform="$2" -if [[ ! -f "$dockerfile" || ! -f requirements/ansible.txt || ! -f README.md ]]; then - echo "Run this check against a SuperBench Dockerfile in a complete checkout." >&2 - exit 2 -fi - -scratch="$(mktemp -d)" -cp README.md "$scratch/README.md" -cp requirements/ansible.txt "$scratch/ansible.txt" -cleanup() { - cp "$scratch/README.md" README.md - cp "$scratch/ansible.txt" requirements/ansible.txt - rm -f "$scratch/README.md" "$scratch/ansible.txt" "$scratch/build.log" - rmdir "$scratch" -} -trap cleanup EXIT - -check_build() { - expected="$1" - shift - if ! docker buildx build --file "$dockerfile" --platform "$platform" \ - --target ansible-dependencies --progress=plain "$@" . > "$scratch/build.log" 2>&1; then - cat "$scratch/build.log" >&2 - return 1 - fi - cat "$scratch/build.log" - step="$(awk '/] RUN python3 \/opt\/sb-ansible\/scripts\/install_ansible.py$/ {print $1; exit}' "$scratch/build.log")" - if [[ -z "$step" ]]; then - echo "The build did not report the Ansible installation step." >&2 - return 1 - fi - if [[ "$expected" == "cached" ]]; then - if ! grep -Fxq "$step CACHED" "$scratch/build.log"; then - echo "An application-only change invalidated the Ansible dependency layer." >&2 - return 1 - fi - elif grep -Fxq "$step CACHED" "$scratch/build.log" || ! grep -Fq "$step DONE" "$scratch/build.log"; then - echo "The Ansible installation did not execute for a cold or changed-dependency build." >&2 - return 1 - fi -} - -check_build rebuilt --no-cache -printf '\n\n' >> README.md -check_build cached -printf '\n# Ansible dependency cache probe\n' >> requirements/ansible.txt -check_build rebuilt -echo "Verified cold installation, application-only cache reuse, and dependency-change invalidation." diff --git a/tests/ansible/test_dependencies.py b/tests/ansible/test_dependencies.py deleted file mode 100644 index 888cb1787..000000000 --- a/tests/ansible/test_dependencies.py +++ /dev/null @@ -1,187 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""Tests for dependency acquisition and the installed Ansible collections.""" - -import importlib.util -import json -import os -import shutil -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -spec = importlib.util.spec_from_file_location( - 'install_ansible', - Path(__file__).resolve().parents[2] / 'scripts' / 'install_ansible.py' -) -assert spec is not None and spec.loader is not None -install_ansible = importlib.util.module_from_spec(spec) -spec.loader.exec_module(install_ansible) - - -class CollectionRetryTest(unittest.TestCase): - """Exercise bounded retries without contacting Galaxy or waiting.""" - def test_success_and_recovery(self): - """Stop on the first successful attempt and keep the original command.""" - command = ['ansible-galaxy', 'collection', 'install', '-r', 'requirements.yml'] - for codes, delays in [([0], []), ([1, 0], [10]), ([1, 1, 0], [10, 20])]: - with self.subTest(codes=codes), mock.patch.object( - install_ansible.subprocess, - 'run', - side_effect=[subprocess.CompletedProcess(command, code) for code in codes] - ) as run, mock.patch.object(install_ansible.time, 'sleep') as sleep: - install_ansible.install_collections(command) - self.assertEqual(run.call_args_list, [mock.call(command, timeout=300)] * len(codes)) - self.assertEqual(sleep.call_args_list, [mock.call(delay) for delay in delays]) - - def test_exhaustion_preserves_failure(self): - """Propagate the last failure rather than reporting a successful install.""" - command = ['ansible-galaxy'] - with mock.patch.object( - install_ansible.subprocess, 'run', return_value=subprocess.CompletedProcess(command, 17) - ) as run, mock.patch.object(install_ansible.time, 'sleep') as sleep: - with self.assertRaises(subprocess.CalledProcessError) as error: - install_ansible.install_collections(command) - self.assertEqual(error.exception.returncode, 17) - self.assertEqual(run.call_count, 3) - self.assertEqual(sleep.call_args_list, [mock.call(10), mock.call(20)]) - - def test_timeout_is_bounded(self): - """Terminate timed-out acquisition attempts and fail after the budget.""" - command = ['ansible-galaxy'] - with mock.patch.object(install_ansible.subprocess, 'run', side_effect=subprocess.TimeoutExpired(command, 300) - ) as run, mock.patch.object(install_ansible.time, 'sleep'): - with self.assertRaises(subprocess.CalledProcessError) as error: - install_ansible.install_collections(command) - self.assertEqual(error.exception.returncode, 124) - self.assertEqual(run.call_count, 3) - - def test_changed_python_dependency_is_rejected(self): - """Detect a dependency changed by a later application installation.""" - with tempfile.TemporaryDirectory() as directory: - requirements = Path(directory) - (requirements / 'ansible.txt').write_text('packaging==26.3\n') - with mock.patch.object(install_ansible, 'REQUIREMENTS', requirements), mock.patch.object( - install_ansible.subprocess, 'check_output', return_value='[{"name":"packaging","version":"24.0"}]' - ): - with self.assertRaisesRegex(RuntimeError, 'packaging==26.3'): - install_ansible.check_python() - - def test_conflicting_distribution_is_rejected_before_install(self): - """Do not overwrite another distribution sharing the ansible namespace.""" - with mock.patch.object(sys, 'argv', [ - 'install_ansible.py' - ]), mock.patch.object(install_ansible, 'installed_packages', - return_value={'ansible': - '1.0'}), mock.patch.object(install_ansible.subprocess, 'run') as run: - self.assertEqual(install_ansible.main(), 1) - run.assert_not_called() - - @unittest.skipUnless(os.name == 'posix', 'Ansible collections require POSIX.') - def test_shadowed_collection_is_rejected(self): - """Reject a different collection loaded ahead of the pinned version.""" - with tempfile.TemporaryDirectory() as directory: - collection = Path(directory) - (collection / 'MANIFEST.json').write_text( - json.dumps( - { - 'collection_info': { - 'namespace': 'community', - 'name': 'crypto', - 'version': '0.0.0', - 'dependencies': {} - } - } - ) - ) - documentation = { - 'community.crypto.openssh_keypair': { - 'doc': { - 'filename': str(collection / 'plugins' / 'modules' / 'openssh_keypair.py') - } - } - } - with mock.patch.object(install_ansible.subprocess, 'check_output', return_value=json.dumps(documentation)): - with self.assertRaisesRegex(RuntimeError, 'loaded 0.0.0'): - install_ansible.check_collections(install_ansible.REQUIREMENTS / 'ansible-modern.yml') - - -@unittest.skipUnless(os.name == 'posix', 'Ansible collections require POSIX.') -class InstalledCollectionsTest(unittest.TestCase): - """Run the real plugins on disposable local files, without Docker or SSH.""" - def test_installed_collections(self): - """Check key generation, rank lookup and the actual result-fetch playbook.""" - with tempfile.TemporaryDirectory(prefix='sb-ansible-test-') as directory: - config = Path(directory) / 'ansible.cfg' - config.write_text('[defaults]\n') - command = install_ansible.ansible_command('ansible-playbook') + [ - '-i', - 'localhost,', - '-c', - 'local', - str(Path(__file__).with_name('test_dependencies.yaml')), - '-e', - json.dumps({ - 'test_root': directory, - 'ansible_python_interpreter': sys.executable - }), - ] - env = dict(os.environ, ANSIBLE_CONFIG=str(config), ANSIBLE_LOCAL_TEMP=str(Path(directory) / 'local-tmp')) - result = subprocess.run( - command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120 - ) - self.assertEqual(result.returncode, 0, result.stdout) - - -@unittest.skipUnless(os.name == 'posix', 'The build-cache check uses Bash.') -class BuildCacheProbeTest(unittest.TestCase): - """Test cache-log assertions and input restoration without requiring Docker.""" - def test_cache_decisions_and_input_restoration(self): - """Reject unexpected cache behavior and restore the checkout on every exit.""" - for states, expected in [('DONE,CACHED,DONE', 0), ('CACHED', 1), ('DONE,DONE', 1), ('DONE,CACHED,CACHED', 1)]: - with self.subTest(states=states), tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / 'tests' / 'ansible').mkdir(parents=True) - (root / 'requirements').mkdir() - (root / 'bin').mkdir() - readme = root / 'README.md' - requirements = root / 'requirements' / 'ansible.txt' - readme.write_text('original source\n') - requirements.write_text('original requirements\n') - (root / 'Dockerfile').touch() - counter = root / 'counter' - counter.write_text('0\n') - script = root / 'tests' / 'ansible' / 'check_build_cache.sh' - shutil.copyfile(Path(__file__).with_name('check_build_cache.sh'), script) - docker = root / 'bin' / 'docker' - docker.write_text( - '#!/bin/sh\nset -eu\n' - 'count=$(cat "$CACHE_COUNTER"); count=$((count + 1))\n' - 'printf "%s\\n" "$count" > "$CACHE_COUNTER"\n' - 'state=$(printf "%s" "$CACHE_STATES" | cut -d, -f"$count")\n' - 'echo "#7 [ansible-dependencies 6/6] RUN python3 /opt/sb-ansible/scripts/install_ansible.py"\n' - 'if [ "$state" = CACHED ]; then echo "#7 CACHED"; else echo "#7 DONE 0.1s"; fi\n' - ) - docker.chmod(0o755) - env = dict( - os.environ, - PATH=str(root / 'bin') + os.pathsep + os.environ['PATH'], - CACHE_COUNTER=str(counter), - CACHE_STATES=states - ) - result = subprocess.run( - ['bash', str(script), 'Dockerfile', 'linux/amd64'], - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - timeout=20 - ) - self.assertEqual(result.returncode, expected, result.stdout) - self.assertEqual(int(counter.read_text()), len(states.split(','))) - self.assertEqual(readme.read_text(), 'original source\n') - self.assertEqual(requirements.read_text(), 'original requirements\n') diff --git a/tests/ansible/test_dependencies.yaml b/tests/ansible/test_dependencies.yaml deleted file mode 100644 index 63621e5b8..000000000 --- a/tests/ansible/test_dependencies.yaml +++ /dev/null @@ -1,78 +0,0 @@ ---- -- name: Exercise the collection operations used by SuperBench - hosts: localhost - gather_facts: false - tasks: - - name: Generate the deployment key - community.crypto.openssh_keypair: - path: '{{ test_root }}/id_ed25519' - type: ed25519 - comment: superbench - force: false - register: first_key - no_log: true - - name: Preserve the deployment key on a repeated run - community.crypto.openssh_keypair: - path: '{{ test_root }}/id_ed25519' - type: ed25519 - comment: superbench - force: false - register: second_key - no_log: true - - name: Check idempotency without inspecting the private key - assert: - that: - - first_key is changed - - second_key is not changed - - first_key.public_key == second_key.public_key - - name: Check ranks against sorted hostfile entries - vars: - nodes: "{{ ['node2', 'node0', 'node1'] | sort }}" - assert: - that: - - lookup('ansible.utils.index_of', nodes, 'eq', 'node0') | int == 0 - - lookup('ansible.utils.index_of', nodes, 'eq', 'node1') | int == 1 - - lookup('ansible.utils.index_of', nodes, 'eq', 'node2') | int == 2 - - nodes | join('\n') == 'node0\nnode1\nnode2' - - name: Prepare disposable result directories - file: - path: '{{ test_root }}/{{ item }}' - state: directory - mode: '0700' - loop: - - source/nodes - - received/nodes - - name: Create a benchmark result - copy: - content: '{"result": 42}' - dest: '{{ test_root }}/source/results.json' - mode: '0600' - - name: Create a result that must not be recursively collected - copy: - content: excluded - dest: '{{ test_root }}/source/nodes/excluded' - mode: '0600' - -- name: Exercise the production result-fetch playbook - import_playbook: ../../superbench/runner/playbooks/fetch_results.yaml - vars: - sb_output_dir: '{{ test_root }}/source' - absolute_output_dir: '{{ test_root }}/received' - -- name: Verify the fetched result layout - hosts: localhost - gather_facts: false - tasks: - - name: Read the disposable benchmark result - slurp: - src: '{{ test_root }}/received/nodes/{{ ansible_hostname }}/results.json' - register: result - - name: Check the excluded directory - stat: - path: '{{ test_root }}/received/nodes/{{ ansible_hostname }}/nodes' - register: excluded - - name: Check result content and recursion exclusion - assert: - that: - - "result.content | b64decode | from_json == {'result': 42}" - - not excluded.stat.exists diff --git a/tests/runner/test_ansible.py b/tests/runner/test_ansible.py index 23076683d..8766ce38a 100644 --- a/tests/runner/test_ansible.py +++ b/tests/runner/test_ansible.py @@ -4,6 +4,7 @@ """SuperBench Ansible Client test.""" import os +import subprocess import sys import unittest import tempfile @@ -16,6 +17,61 @@ AnsibleClient = LazyImport('superbench.runner.ansible', 'AnsibleClient') +class AnsiblePostinstallTestCase(unittest.TestCase): + """Test the shared Makefile entry point without contacting Galaxy.""" + def test_bounded_collection_retries(self): + """Stop on success and propagate exhausted installation failures.""" + for codes in [[0], [1, 0], [1, 1, 0], [17, 17, 17], [124, 124, 124]]: + with self.subTest(codes=codes), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + attempts = root / 'attempts' + waits = root / 'waits' + status_codes = root / 'codes' + status_codes.write_text('\n'.join(map(str, codes)) + '\n') + waits.touch() + scripts = { + 'ansible-galaxy': ( + 'printf "%s\\n" "$*" >> "$INSTALL_ATTEMPTS"\n' + 'attempt=$(wc -l < "$INSTALL_ATTEMPTS")\n' + 'exit "$(sed -n "${attempt}p" "$INSTALL_CODES")"\n' + ), + 'sleep': + 'printf "%s\\n" "$1" >> "$INSTALL_WAITS"\n', + } + for name, body in scripts.items(): + script = root / name + script.write_text('#!/bin/sh\nset -eu\n' + body) + script.chmod(0o755) + env = dict( + os.environ, + PATH=str(root) + os.pathsep + os.environ['PATH'], + INSTALL_ATTEMPTS=str(attempts), + INSTALL_WAITS=str(waits), + INSTALL_CODES=str(status_codes), + ) + result = subprocess.run( + ['make', '--no-print-directory', 'postinstall'], + cwd=Path(__file__).resolve().parents[2], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=30, + ) + self.assertEqual(result.returncode == 0, codes[-1] == 0, result.stdout) + commands = attempts.read_text().splitlines() + self.assertEqual(len(commands), len(codes), result.stdout) + self.assertEqual(commands, [commands[0]] * len(codes)) + self.assertRegex( + commands[0], + r'^collection install ansible\.posix:\d+\.\d+\.\d+ ' + r'ansible\.utils:\d+\.\d+\.\d+ community\.crypto:\d+\.\d+\.\d+$', + ) + self.assertEqual(waits.read_text().splitlines(), ['10', '20'][:len(codes) - 1]) + if codes[-1]: + self.assertIn('attempt 3/3 failed (exit {}).'.format(codes[-1]), result.stdout) + + class AnsibleClientTestCase(unittest.TestCase): """A class for ansible client test cases.""" def setUp(self):