From 65589dff4484f1efb5693e119ac3cde8600c208f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 01:47:32 +0200 Subject: [PATCH] ci: compile CUDA package in CPU-only Docker --- .github/workflows/linux.yml | 127 +++++-------- deploy/Dockerfile.cuda-builder | 30 +++ deploy/README.md | 51 ++++-- docs/build-validation.md | 25 ++- scripts/build-cuda-engine-in-docker.py | 244 +++++++++++++++++++++++++ scripts/check-local.sh | 3 +- scripts/test-cuda-docker-builder.py | 189 +++++++++++++++++++ 7 files changed, 555 insertions(+), 114 deletions(-) create mode 100644 deploy/Dockerfile.cuda-builder create mode 100644 scripts/build-cuda-engine-in-docker.py create mode 100644 scripts/test-cuda-docker-builder.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index f4a0da94..9de32def 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -15,10 +15,6 @@ on: description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact) type: boolean default: false - static_cuda_package: - description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference) - type: boolean - default: false permissions: contents: read @@ -52,69 +48,13 @@ jobs: - name: Bounded KAR expert component GPU tests run: scripts/check-kar-expert-gpu.sh - static-cuda-package: - if: github.event_name == 'workflow_dispatch' && inputs.static_cuda_package && github.event.repository.private - needs: verify - runs-on: [self-hosted, linux, x64, strata-gpu] - steps: - - uses: actions/checkout@v4 - - name: Build and audit engine without GPU inference - env: - CUDA_VISIBLE_DEVICES: '' - BUILD_JOBS: '2' - STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }} - run: nice -n 10 scripts/build-static-cuda.sh - - name: Install pinned Rust and musl target - run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - export PATH="$HOME/.cargo/bin:$PATH" - rustup toolchain install 1.99.0 --profile minimal - rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl - command -v musl-gcc - - name: Assemble combined private package - run: | - engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata" - python3 scripts/build-linux-package.py --engine "$engine" \ - --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \ - --output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Build compatible private runtime image without GPU inference - run: | - package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - python3 scripts/build-runtime-image.py --package "$package" \ - --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ - > "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")" - docker save --output "$package/runtime-image.tar" "$image" - cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json" - (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS) - - uses: actions/upload-artifact@v4 - with: - name: strata-next-static-cuda-preview - path: ${{ runner.temp }}/strata-package-${{ github.run_id }}/ - if-no-files-found: error - retention-days: 7 - - name: Remove uploaded package copy - run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Remove owned runtime image - if: always() - run: | - receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - if test -s "$receipt"; then - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" - rm "$receipt" - fi - - name: Remove private build intermediates - if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" - hosted-cuda-package: if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private needs: verify runs-on: ubuntu-latest timeout-minutes: 150 + permissions: + contents: write env: CUDA_VISIBLE_DEVICES: '' BUILD_JOBS: '1' @@ -122,18 +62,16 @@ jobs: CUDA_ARCHITECTURES: '120' steps: - uses: actions/checkout@v4 - - name: Install compatible host tools (no drivers) + - name: Install Docker and package tools (no drivers) run: | echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && apt-get install -y ca-certificates curl gcc-13 g++-13 cmake ninja-build musl-tools binutils + apt-get update && apt-get install -y ca-certificates curl docker.io gh musl-tools binutils python3-numpy - name: Assemble pinned build-only CUDA components run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - name: Record actual toolchain run: | - "$CUDACXX" --version - g++-13 --version df -h "$RUNNER_TEMP" free -h python3 - <<'PYTOOL' @@ -141,17 +79,17 @@ jobs: from pathlib import Path info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text()) info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(), - gcc=subprocess.check_output(['g++-13','--version'],text=True), - nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True), cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False) (Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n') PYTOOL - - name: Build actual static CUDA engine and audit without GPU - env: - CC: gcc-13 - CXX: g++-13 - CUDAHOSTCXX: g++-13 - run: scripts/build-static-cuda.sh + - name: Compile and audit actual CUDA engine in CPU-only Docker + run: | + python3 scripts/build-cuda-engine-in-docker.py \ + --toolkit "$CUDAToolkit_ROOT" \ + --build-dir "$RUNNER_TEMP/strata-hosted-cuda-build" \ + --output "$STRATA_BUILD_DIR/strata" \ + --metadata "$RUNNER_TEMP/CUDA-BUILDER.json" \ + --image-tag "${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - name: Install pinned Rust and musl target run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none @@ -181,16 +119,29 @@ jobs: image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")" docker save --output "$package/runtime-image.tar" "$image" cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json" - cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json" + python3 - "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$RUNNER_TEMP/CUDA-BUILDER.json" "$package/CUDA-TOOLCHAIN.json" <<'PYTOOL' + import json, sys + from pathlib import Path + bootstrap=json.loads(Path(sys.argv[1]).read_text()) + builder=json.loads(Path(sys.argv[2]).read_text()) + bootstrap['docker_builder']=builder + Path(sys.argv[3]).write_text(json.dumps(bootstrap,indent=2)+'\n') + PYTOOL tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS) - - uses: actions/upload-artifact@v4 - with: - name: strata-next-hosted-cuda-preview - path: ${{ runner.temp }}/strata-hosted-cuda-package/ - if-no-files-found: error - retention-days: 7 - - name: Remove uploaded package copy + - name: Publish private CUDA preview release + env: + GH_TOKEN: ${{ github.token }} + run: | + export GH_HOST="${GITHUB_SERVER_URL#https://}" + export GH_HOST="${GH_HOST#http://}" + tag="cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + gh release create "$tag" "$RUNNER_TEMP/strata-hosted-cuda-package/"* \ + --target "$GITHUB_SHA" --repo "$GITHUB_REPOSITORY" \ + --title "CUDA build preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ + --notes 'Actual CUDA compilation and packaging from this commit. Built in a GPU-hidden Docker container. This is not driver, inference, model-quality or performance qualification.' \ + --prerelease + - name: Remove privately published package copy run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package" - name: Remove owned intermediate image and build files if: always() @@ -198,9 +149,15 @@ jobs: receipt="$RUNNER_TEMP/strata-hosted-image.json" if test -s "$receipt"; then image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" + docker image rm "$image" || true fi - rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build" + builder_label="leleka.cuda-builder.run=${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if command -v docker >/dev/null 2>&1; then + docker ps -aq --filter "label=$builder_label" | xargs -r docker rm -f || true + docker volume ls -q --filter "label=$builder_label" | xargs -r docker volume rm --force || true + docker image ls -q --filter "label=$builder_label" | sort -u | xargs -r docker image rm || true + fi + rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-cuda-build" "$RUNNER_TEMP/strata-hosted-package-build" linux-static-cli: needs: verify @@ -435,6 +392,8 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: | + export GH_HOST="${GITHUB_SERVER_URL#https://}" + export GH_HOST="${GH_HOST#http://}" gh release create "${GITHUB_REF_NAME}" dist/strata-next-linux-x86_64-musl dist/SHA256SUMS dist/BUILD-PROVENANCE.txt dist/ELF-AUDIT.txt \ --repo "${GITHUB_REPOSITORY}" --title "Strata Next ${GITHUB_REF_NAME}" \ --notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --prerelease diff --git a/deploy/Dockerfile.cuda-builder b/deploy/Dockerfile.cuda-builder new file mode 100644 index 00000000..439c6038 --- /dev/null +++ b/deploy/Dockerfile.cuda-builder @@ -0,0 +1,30 @@ +FROM --platform=linux/amd64 ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b + +ENV DEBIAN_FRONTEND=noninteractive + +# Freeze Ubuntu's package view as well as the base-image digest. CUDA itself is +# supplied separately by the checksum-pinned redistributable bundle. +RUN rm -f /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list && \ + printf '%s\n' \ + 'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble main universe' \ + 'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble-updates main universe' \ + 'deb [check-valid-until=no] https://snapshot.ubuntu.com/ubuntu/20260917T000000Z noble-security main universe' \ + > /etc/apt/sources.list && \ + apt-get -o Acquire::Check-Valid-Until=false update && \ + apt-get install -y --no-install-recommends \ + ca-certificates cmake gcc-13 g++-13 git ninja-build python3 python3-numpy && \ + rm -rf /var/lib/apt/lists/* && \ + test "$(gcc-13 -dumpfullversion | cut -d. -f1)" = 13 && \ + mkdir -p /stage/source /stage/toolkit /build && chmod 1777 /build + +ENV CUDACXX=/opt/cuda/bin/nvcc \ + CUDAToolkit_ROOT=/opt/cuda \ + CUDAHOSTCXX=/usr/bin/g++-13 \ + CC=/usr/bin/gcc-13 \ + CXX=/usr/bin/g++-13 \ + CUDA_VISIBLE_DEVICES= \ + NVIDIA_VISIBLE_DEVICES=void \ + HOME=/tmp/home + +WORKDIR /workspace +ENTRYPOINT ["/bin/bash"] diff --git a/deploy/README.md b/deploy/README.md index 1010ce20..acffbaac 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -602,21 +602,27 @@ CMake's static CUDA runtime and cuBLAS targets and statically links the engine's GNU C++ runtime. The default CUDA profile continues to use shared toolkit libraries. HIP and non-Linux/GNU configurations reject this option. -On a Linux builder with the toolkit and CMake already installed: +On a Linux x86_64 host with Docker and the pinned CUDA toolkit bundle already +bootstrapped, use the repository wrapper to build inside a digest-pinned Ubuntu +24.04 amd64 image. The source checkout and toolkit are read-only mounts, output +paths must be fresh and outside the checkout, and no GPU device is passed into +the container: ```sh -export CUDACXX=/absolute/path/to/cuda/bin/nvcc -export CUDAToolkit_ROOT=/absolute/path/to/cuda -# Optional existing pinned llama.cpp checkout; otherwise CMake fetches its pinned source: -export STRATA_GGML_DIR=/absolute/path/to/llama.cpp -BUILD_JOBS=2 scripts/build-static-cuda.sh +python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/strata-cuda-toolkit +python3 scripts/build-cuda-engine-in-docker.py \ + --toolkit /tmp/strata-cuda-toolkit \ + --build-dir /tmp/strata-cuda-build \ + --output /tmp/strata-cuda-output/strata \ + --metadata /tmp/strata-cuda-output/CUDA-BUILDER.json \ + --image-tag local-1 ``` -The script builds only `strata`, using SM 120 and portable AVX2 GGML defaults; -`CUDA_ARCHITECTURES` and `STRATA_BUILD_DIR` can override the build target/path. -It audits ELF dependencies and runs only `--help` with no GPU visible. It does -not install anything, serve a model, change a service, or run a speed test. -CMake's imported targets provide the static dependency closure; see the +The wrapper compiles only `strata`, using SM 120 and portable AVX2 GGML defaults; +`CUDA_ARCHITECTURES` remains configurable in `scripts/build-static-cuda.sh`. +It audits ELF dependencies and runs only `--help` with NVIDIA device nodes hidden. +It does not install anything, serve a model, change a service, run a kernel, or +measure speed. CMake's imported targets provide the static dependency closure; see the [FindCUDAToolkit reference](https://cmake.org/cmake/help/latest/module/FindCUDAToolkit.html). The measured CUDA 13.2 build has only `libm.so.6`, `libc.so.6` and the host loader @@ -638,10 +644,16 @@ the dynamic engine. See the [packaging report](../docs/experiments/2026-10-04-la No quality, numerical parity, speedup or production-ready claim follows from linking successfully. Keep the default profile until the model gates pass. -The optional `static_cuda_package` workflow-dispatch job performs the build and -ELF audit on the private CUDA runner without inference. It publishes no package -and cleans its private build directory. The runner must have the required -compiler/toolkit in its environment; hosted execution has not yet occurred. +The optional `hosted_cuda_package` workflow-dispatch job bootstraps the +checksum-pinned toolkit on the generic Linux runner, then builds the actual CUDA +engine in this GPU-hidden Docker image before assembling the executable and OCI +preview. It publishes a private prerelease asset with provenance and checksums. +This verifies compilation, ELF dependencies and GPU-hidden help only; the host +driver, kernel execution, real model, quality and performance still require +separate GPU qualification. This job publishes a private prerelease because +the Gitea instance does not support the GitHub-hosted `upload-artifact` action. +The independent `keyless_gpu` job remains opt-in and requires an actual GPU +runner for kernel-execution tests. ## Fetch pinned assets as part of native startup @@ -997,11 +1009,10 @@ operator/CI-declared provenance, not a binary-to-source attestation, and this pipeline does not promise bit-identical compiler output. Python is used only on the build host; the resulting runtime does not require it. -The manual `static_cuda_package` workflow builds the engine then assembles and -uploads the combined preview to the **private repository**, with seven-day -artifact retention. It cleans owned build directories after the upload attempt; the final package -copy is removed only after a successful upload. A failed upload leaves that -private final package available for recovery. +The manual `hosted_cuda_package` workflow builds the engine inside a pinned, +GPU-hidden Docker builder on the generic Linux CPU runner, assembles the combined +preview, and publishes it as a private prerelease with provenance and checksums. +The workflow removes its local package copy only after successful publication. The normal hosted job uses `--cpu-fixture` to exercise the same assembly path and then tests exact serving output/restart against the external fixture. CPU artifacts are explicitly marked and are not CUDA releases. No model weights, diff --git a/docs/build-validation.md b/docs/build-validation.md index 6edfc9ca..c3c12131 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -796,8 +796,9 @@ readiness remain separate acceptance gates. No image is pushed to a registry. `workflow_dispatch` input `hosted_cuda_package=true` selects a private-repository Ubuntu 24.04 CPU job. It never targets the private GPU runner. The existing -`static_cuda_package` and `keyless_gpu` inputs remain false unless explicitly -selected. This build does not load a model or install a driver. +`keyless_gpu` input remains false unless explicitly selected and requires a +dedicated GPU runner. The CUDA build route itself needs only the generic Linux +CPU runner. This build does not load a model or install a driver. The build-only `scripts/bootstrap-cuda-toolkit.py` assembles seven components from NVIDIA's [CUDA 13.0.1 redistrib manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.1.json), @@ -807,9 +808,13 @@ prefix, bounded downloads/expansion, safe tar extraction, collision/link checks and retained component licenses avoid a system CUDA installation. This is a build dependency bootstrap, not an end-user runtime installer. NVIDIA documents [component assembly and supported host compilers](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-installation-guide-linux/index.html). -The job explicitly uses GCC 13, one engine compile job, two Rust build jobs and a -150-minute job limit; it refuses acquisition below 6 GiB RAM or 12 GiB free disk. -Actual host/compiler versions and initial resources are recorded. Toolkit bytes +The job builds the CUDA engine with `scripts/build-cuda-engine-in-docker.py` in a +digest-pinned Ubuntu 24.04 amd64 Docker builder, with the source and toolkit +mounted read-only and no GPU devices or NVIDIA container runtime. GCC 13 is +scoped to the engine builder; the job uses one engine compile job, two Rust build +jobs and a 150-minute limit. The toolkit bootstrap refuses acquisition below 6 +GiB RAM or 12 GiB free disk. Container compiler/image identity and initial host +resources are recorded. Toolkit bytes are pinned; hosted OS/compiler patch updates mean byte-identical rebuilds are not asserted. @@ -825,11 +830,13 @@ equality remain mandatory checks for this build-path change. Existing static-engine, combined-package and OCI builders supply the actual compile/link, dependency/ABI, embedded identity and GPU-hidden help gates. -The private `strata-next-hosted-cuda-preview` artifact retains package checksums, +The private prerelease `cuda-preview-.` retains package checksums, source provenance, image archive/receipt, exact toolkit manifest/toolchain data -and component license archive. Retention is seven days. Successful upload is -required; an ephemeral hosted runner is not durable fallback storage if upload -fails. Owned build directories and image are cleaned. Tests use deliberately +and component license archive. Publishing uses the same Gitea-compatible `gh +release create` path as the CLI preview; the unsupported `actions/upload-artifact` +action is not used. A failed publication fails the job; an ephemeral hosted +runner is not durable fallback storage if publication fails. Owned build +directories and image are cleaned. Tests use deliberately invalid archives/receipts and do not require CUDA; only a successful manual actual-CUDA job qualifies compilation and packaging. GPU driver loading, full-model/MTP inference, quality and clean-node rollback remain separate gates. diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py new file mode 100644 index 00000000..77828a47 --- /dev/null +++ b/scripts/build-cuda-engine-in-docker.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Build and audit the CUDA engine in a pinned CPU-only Linux Docker container.""" +import argparse +import hashlib +from io import BytesIO +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tarfile +import tempfile +import uuid + +REPO = Path(__file__).resolve().parents[1].resolve() +DOCKERFILE = REPO / 'deploy/Dockerfile.cuda-builder' +BASE = 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' +PLATFORM = 'linux/amd64' + +CONTAINER_BUILD = r'''set -euo pipefail +test -x /opt/cuda/bin/nvcc +test -f /opt/cuda/lib/libcudart_static.a +shopt -s nullglob +devices=(/dev/nvidia*) +if (( ${#devices[@]} != 0 )); then + echo "CUDA builder unexpectedly sees NVIDIA device nodes: ${devices[*]}" >&2 + exit 91 +fi +test "${CUDA_VISIBLE_DEVICES+x}" = x && test -z "$CUDA_VISIBLE_DEVICES" +test "${NVIDIA_VISIBLE_DEVICES}" = void +mkdir -p /tmp/home /build/engine /build/output +python3 - <<'PY' +import json, os, subprocess +def capture(*args): + return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT).strip() +data = { + 'builder_base': os.environ['LELEKA_BUILDER_BASE'], + 'builder_platform': 'linux/amd64', + 'apt_snapshot': '20260917T000000Z', + 'nvidia_device_nodes_visible': False, + 'cuda_visible_devices': os.environ['CUDA_VISIBLE_DEVICES'], + 'nvidia_visible_devices': os.environ['NVIDIA_VISIBLE_DEVICES'], + 'nvcc': capture('/opt/cuda/bin/nvcc', '--version'), + 'gcc': capture('gcc-13', '--version'), + 'gxx': capture('g++-13', '--version'), + 'cmake': capture('cmake', '--version'), + 'ninja': capture('ninja', '--version'), + 'packages': capture('dpkg-query', '-W', '-f=${Package}=${Version}\\n', + 'ca-certificates', 'cmake', 'gcc-13', 'g++-13', 'git', 'ninja-build', 'python3', 'python3-numpy'), +} +with open(os.environ['LELEKA_TOOLCHAIN_METADATA'], 'w', encoding='utf-8') as stream: + json.dump(data, stream, indent=2) + stream.write('\\n') +PY +scripts/build-static-cuda.sh +install -m 0755 /build/engine/strata "$LELEKA_ENGINE_OUTPUT" +''' + + +def digest(path): + h = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def stage_tracked_source(destination): + changed = subprocess.run(['git', '-C', str(REPO), 'diff', '--quiet', 'HEAD', '--'], check=False) + if changed.returncode == 1: + raise ValueError('refusing to build from a checkout with tracked changes; commit the source first') + if changed.returncode < 0: + raise ValueError('git diff was interrupted while checking the source checkout') + if changed.returncode != 0: + raise subprocess.CalledProcessError(changed.returncode, changed.args) + archive = subprocess.check_output(['git', '-C', str(REPO), 'archive', '--format=tar', 'HEAD']) + with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source: + try: + source.extractall(destination, filter='data') + except (OSError, tarfile.TarError, ValueError) as error: + raise ValueError(f'could not safely stage the committed source tree: {error}') from error + return subprocess.check_output(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], text=True).strip(), hashlib.sha256(archive).hexdigest() + + +def outside_repo(path, label): + resolved = path.resolve() + repo = REPO.resolve() + if resolved == repo or repo in resolved.parents: + raise ValueError(f'{label} must stay outside the source checkout') + if any(char in str(resolved) for char in ',:\n'): + raise ValueError(f'{label} contains a character unsupported in Docker mount paths') + return resolved + + +def run(command): + subprocess.run([str(arg) for arg in command], check=True) + + +def capture(command): + return subprocess.check_output([str(arg) for arg in command], text=True).strip() + + +def build(args): + docker = shutil.which(args.docker) if '/' not in args.docker else args.docker + if not docker: + raise ValueError('Docker CLI is not available') + toolkit = args.toolkit.resolve(strict=True) + if not (toolkit / 'bin/nvcc').is_file() or not (toolkit / 'lib/libcudart_static.a').is_file(): + raise ValueError('toolkit is missing nvcc or static CUDA runtime') + build_dir = outside_repo(args.build_dir, 'build directory') + engine_output = outside_repo(args.output, 'engine output') + metadata_output = outside_repo(args.metadata, 'metadata output') + for path in (toolkit, build_dir, engine_output.parent, metadata_output.parent): + if any(char in str(path) for char in ',:\n'): + raise ValueError('a Docker mount path contains an unsupported character') + output_roots = (engine_output.parent, metadata_output.parent) + if any(build_dir == output or build_dir in output.parents or output in build_dir.parents + for output in output_roots): + raise ValueError('build and output directories must not overlap') + if engine_output.exists() or metadata_output.exists(): + raise ValueError('refusing to overwrite an existing build output') + if build_dir.exists() and any(build_dir.iterdir()): + raise ValueError('build directory must be fresh and empty') + build_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + engine_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + metadata_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + + dockerfile = DOCKERFILE.read_text(encoding='utf-8') + match = re.search(r'^FROM --platform=linux/amd64 (\S+)$', dockerfile, re.M) + if not match or match.group(1) != BASE: + raise ValueError('CUDA builder Dockerfile must use the reviewed immutable amd64 base') + if not re.fullmatch(r'[A-Za-z0-9_.-]{1,46}', args.image_tag): + raise ValueError('invalid image tag') + nonce = uuid.uuid4().hex[:12] + tag = f'leleka-cuda-builder:{args.image_tag}-{nonce}' + image_built = False + container_id = None + staging_container_id = None + volume_names = {kind: f'leleka-cuda-{kind}-{args.image_tag}-{nonce}' for kind in ('source', 'toolkit', 'build')} + owned_volumes = [] + source = build_dir / 'source' + try: + source.mkdir(mode=0o700) + source_commit, source_archive_sha256 = stage_tracked_source(source) + with tempfile.TemporaryDirectory(prefix='leleka-cuda-docker-context-') as context_name: + context = Path(context_name) + image_context = context / 'image' + image_context.mkdir() + shutil.copyfile(DOCKERFILE, image_context / 'Dockerfile') + run([docker, 'build', '--platform', PLATFORM, '--pull', '--file', image_context / 'Dockerfile', + '--label', f'leleka.cuda-builder.run={args.image_tag}', '--tag', tag, image_context]) + image_built = True + image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', tag], text=True).strip() + if not re.fullmatch(r'sha256:[0-9a-f]{64}', image_id): + raise ValueError('Docker returned an invalid builder image ID') + for kind, volume in volume_names.items(): + created = capture([docker, 'volume', 'create', '--label', f'leleka.cuda-builder.run={args.image_tag}', volume]) + if created != volume: + raise ValueError(f'Docker returned an unexpected {kind} volume name') + owned_volumes.append(volume) + staging_container_id = capture([ + docker, 'create', '--platform', PLATFORM, '--network', 'none', + '--label', f'leleka.cuda-builder.run={args.image_tag}', + '--mount', f'type=volume,source={volume_names["source"]},target=/stage/source', + '--mount', f'type=volume,source={volume_names["toolkit"]},target=/stage/toolkit', + '--entrypoint', '/bin/true', tag + ]) + if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', staging_container_id): + raise ValueError('Docker returned an invalid staging container ID') + run([docker, 'cp', f'{source}/.', f'{staging_container_id}:/stage/source']) + run([docker, 'cp', f'{toolkit}/.', f'{staging_container_id}:/stage/toolkit']) + run([docker, 'rm', staging_container_id]) + staging_container_id = None + uid, gid = os.getuid(), os.getgid() + container_id = capture([docker, 'create', '--platform', PLATFORM, '--network', 'bridge', '--read-only', + '--label', f'leleka.cuda-builder.run={args.image_tag}', + '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '512', + '--tmpfs', f'/tmp:rw,nosuid,nodev,size=1g,uid={uid},gid={gid}', '--user', f'{uid}:{gid}', + '--mount', f'type=volume,source={volume_names["source"]},target=/workspace,readonly', + '--mount', f'type=volume,source={volume_names["toolkit"]},target=/opt/cuda,readonly', + '--mount', f'type=volume,source={volume_names["build"]},target=/build', + '--workdir', '/workspace', + '--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + '--env', 'HOME=/tmp/home', '--env', 'CUDA_VISIBLE_DEVICES=', '--env', 'NVIDIA_VISIBLE_DEVICES=void', + '--env', f'LELEKA_BUILDER_BASE={BASE}', '--env', 'LELEKA_ENGINE_OUTPUT=/build/output/strata', + '--env', 'LELEKA_TOOLCHAIN_METADATA=/build/output/CUDA-BUILDER.json', + '--env', 'CUDACXX=/opt/cuda/bin/nvcc', '--env', 'CUDAToolkit_ROOT=/opt/cuda', + '--env', 'CUDAHOSTCXX=/usr/bin/g++-13', '--env', 'CC=/usr/bin/gcc-13', '--env', 'CXX=/usr/bin/g++-13', + '--env', 'STRATA_BUILD_DIR=/build/engine', '--env', 'BUILD_JOBS=1', '--env', 'CUDA_ARCHITECTURES=120', + tag, '-lc', CONTAINER_BUILD]) + if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', container_id): + raise ValueError('Docker returned an invalid build container ID') + run([docker, 'start', '--attach', container_id]) + run([docker, 'cp', f'{container_id}:/build/output/strata', engine_output]) + run([docker, 'cp', f'{container_id}:/build/output/CUDA-BUILDER.json', metadata_output]) + if not engine_output.is_file() or engine_output.is_symlink(): + raise ValueError('Docker build did not produce a regular engine file') + engine_output.chmod(0o755) + container_metadata = json.loads(metadata_output.read_text(encoding='utf-8')) + expected = {'builder_base': BASE, 'builder_platform': PLATFORM, + 'nvidia_device_nodes_visible': False, 'cuda_visible_devices': '', 'nvidia_visible_devices': 'void'} + if any(container_metadata.get(key) != value for key, value in expected.items()): + raise ValueError('container toolchain metadata violates CPU-only builder policy') + metadata = {'schema_version': 1, **container_metadata, 'source_commit': source_commit, + 'source_archive_sha256': source_archive_sha256, 'builder_image_id': image_id, + 'engine_sha256': digest(engine_output), 'engine_bytes': engine_output.stat().st_size, + 'gpu_tested': False, 'model_tested': False, + 'qualification': 'CUDA compilation, ELF dependency audit and GPU-hidden --help only.'} + metadata_output.write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8') + return metadata + finally: + if source.exists(): + shutil.rmtree(source) + for owned_container in (container_id, staging_container_id): + if owned_container: + subprocess.run([docker, 'rm', '--force', owned_container], check=False, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for volume in owned_volumes: + subprocess.run([docker, 'volume', 'rm', '--force', volume], check=False, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if image_built: + subprocess.run([docker, 'image', 'rm', tag], check=False, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--toolkit', type=Path, required=True, help='checksum-verified toolkit from bootstrap-cuda-toolkit.py') + parser.add_argument('--build-dir', type=Path, required=True, help='fresh private directory outside the checkout') + parser.add_argument('--output', type=Path, required=True, help='new engine file path outside the checkout') + parser.add_argument('--metadata', type=Path, required=True, help='new provenance JSON path outside the checkout') + parser.add_argument('--image-tag', required=True, help='unique CI run/attempt suffix for the temporary builder image') + parser.add_argument('--docker', default='docker', help='Docker CLI (used by tests)') + args = parser.parse_args() + try: + result = build(args) + print(json.dumps(result, sort_keys=True)) + except (OSError, ValueError, subprocess.SubprocessError, json.JSONDecodeError) as error: + parser.exit(1, f'Docker CUDA build failed: {error}\n') + + +if __name__ == '__main__': + main() diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 27af6254..53684890 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -3,13 +3,14 @@ set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" +python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" "${repo_root}/scripts/build-cuda-engine-in-docker.py" python3 "${repo_root}/scripts/test-benchmark-harness.py" python3 "${repo_root}/scripts/test-native-service.py" python3 "${repo_root}/scripts/test-native-api.py" python3 "${repo_root}/scripts/test-native-menu.py" python3 "${repo_root}/scripts/test-model-switch.py" python3 "${repo_root}/scripts/test-cuda-bootstrap.py" +python3 "${repo_root}/scripts/test-cuda-docker-builder.py" python3 "${repo_root}/scripts/test-static-cuda-elf.py" python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-runtime-image.py" diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py new file mode 100644 index 00000000..8a32f983 --- /dev/null +++ b/scripts/test-cuda-docker-builder.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""CPU-only contract tests for the Docker CUDA builder wrapper.""" +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +MODULE = Path(__file__).with_name('build-cuda-engine-in-docker.py') +spec = importlib.util.spec_from_file_location('cuda_docker_builder', MODULE) +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +class Tests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='cuda-docker-contract-') + self.root = Path(self.temp.name) + self.source_repo = self.root / 'repo' + (self.source_repo / 'deploy').mkdir(parents=True) + (self.source_repo / 'scripts').mkdir() + shutil.copyfile(builder.DOCKERFILE, self.source_repo / 'deploy/Dockerfile.cuda-builder') + (self.source_repo / 'scripts/build-static-cuda.sh').write_text('#!/bin/sh\nexit 0\n', encoding='utf-8') + (self.source_repo / 'scripts/check-static-cuda-elf.py').write_text('# fixture\n', encoding='utf-8') + subprocess.run(['git', '-C', str(self.source_repo), 'init', '-q'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'config', 'user.email', 'cuda-test@example.invalid'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'config', 'user.name', 'CUDA test'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'add', '-f', 'deploy/Dockerfile.cuda-builder', + 'scripts/build-static-cuda.sh', 'scripts/check-static-cuda-elf.py'], check=True) + subprocess.run(['git', '-C', str(self.source_repo), 'commit', '-qm', 'fixture'], check=True) + (self.source_repo / '.env').write_text('must not be staged', encoding='utf-8') + self.original_repo = builder.REPO + self.original_dockerfile = builder.DOCKERFILE + builder.REPO = self.source_repo.resolve() + builder.DOCKERFILE = self.source_repo / 'deploy/Dockerfile.cuda-builder' + self.toolkit = self.root / 'toolkit' + (self.toolkit / 'bin').mkdir(parents=True) + (self.toolkit / 'lib').mkdir() + (self.toolkit / 'bin/nvcc').write_text('fixture', encoding='utf-8') + (self.toolkit / 'lib/libcudart_static.a').write_bytes(b'fixture') + self.fake_docker = self.root / 'docker' + self.log = self.root / 'calls.jsonl' + fake = r'''#!/usr/bin/env python3 +import json, pathlib, sys +args=sys.argv[1:] +with open(__LOG_PATH__, 'a') as f: f.write(json.dumps(args)+'\n') +if args[0] == 'build': + dockerfile=pathlib.Path(args[args.index('--file')+1]).read_text() + assert 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' in dockerfile +elif args[:2] == ['image','inspect']: + print('sha256:' + 'a'*64) +elif args[:2] == ['volume','create']: + print(args[-1]) +elif args[0] == 'create': + if '--entrypoint' not in args: + assert '--read-only' in args and '--gpus' not in args and '--device' not in args and '--runtime' not in args + mounts=[args[i+1] for i,x in enumerate(args[:-1]) if x=='--mount'] + assert len(mounts)==3 and all(item.startswith('type=volume,') for item in mounts) + assert any('target=/workspace,readonly' in item for item in mounts) + assert any('target=/opt/cuda,readonly' in item for item in mounts) + assert any('target=/build' in item and 'readonly' not in item for item in mounts) + envs=[args[i+1] for i,x in enumerate(args[:-1]) if x=='--env'] + assert 'CUDA_VISIBLE_DEVICES=' in envs and 'NVIDIA_VISIBLE_DEVICES=void' in envs + print(('a' if '--entrypoint' in args else 'b')*64) +elif args[0] == 'cp': + if args[2].endswith(':/stage/source'): + source=pathlib.Path(args[1][:-2]) + assert (source/'scripts/build-static-cuda.sh').is_file() + assert not (source/'.env').exists() + elif args[2].endswith(':/stage/toolkit'): + source=pathlib.Path(args[1][:-2]) + assert (source/'bin/nvcc').is_file() + elif args[1].endswith(':/build/output/strata'): + pathlib.Path(args[2]).write_bytes(b'fake compiled CUDA engine') + elif args[1].endswith(':/build/output/CUDA-BUILDER.json'): + pathlib.Path(args[2]).write_text(json.dumps({ + 'builder_base':'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b', + 'builder_platform':'linux/amd64','apt_snapshot':'20260917T000000Z', + 'nvidia_device_nodes_visible':False,'cuda_visible_devices':'','nvidia_visible_devices':'void', + 'nvcc':'fixture','gcc':'fixture','gxx':'fixture','cmake':'fixture','ninja':'fixture','packages':'fixture'})) +elif args[0] == 'start': + if pathlib.Path(__FAIL_RUN__).exists(): sys.exit(42) +elif args[0] == 'rm' or args[:2] == ['volume','rm'] or args[:2] == ['image','rm']: + pass +else: + raise AssertionError(args) +'''.replace('__LOG_PATH__', json.dumps(str(self.log))) + self.fake_docker.write_text(fake.replace('__FAIL_RUN__', json.dumps(str(self.root / 'fail-run'))), encoding='utf-8') + self.fake_docker.chmod(0o755) + + def tearDown(self): + builder.REPO = self.original_repo + builder.DOCKERFILE = self.original_dockerfile + self.temp.cleanup() + + def arguments(self, **overrides): + from argparse import Namespace + values = dict(toolkit=self.toolkit, + build_dir=self.root / 'build', + output=self.root / 'out' / 'strata', + metadata=self.root / 'out' / 'CUDA-BUILDER.json', + image_tag='test-1', docker=str(self.fake_docker)) + values.update(overrides) + return Namespace(**values) + + def docker_calls(self): + return [json.loads(line) for line in self.log.read_text().splitlines()] + + def test_container_build_has_pinned_cpu_only_invocation(self): + result = builder.build(self.arguments()) + self.assertEqual(result['builder_base'], builder.BASE) + self.assertFalse(result['gpu_tested']) + self.assertEqual(result['source_commit'], subprocess.check_output( + ['git', '-C', str(self.source_repo), 'rev-parse', 'HEAD'], text=True).strip()) + self.assertEqual(result['engine_sha256'], builder.digest(self.root / 'out/strata')) + calls = self.docker_calls() + build = next(args for args in calls if args[0] == 'build') + container = next(args for args in calls if args[0] == 'create' and '--entrypoint' not in args) + self.assertEqual(build[build.index('--platform')+1], 'linux/amd64') + self.assertEqual(container[container.index('--platform')+1], 'linux/amd64') + self.assertNotIn('--gpus', container) + self.assertIn(['rm', '--force', 'b'*64], calls) + self.assertTrue(any(call[:2] == ['volume', 'rm'] for call in calls)) + self.assertEqual(calls[-1][:2], ['image','rm']) + subprocess.run(['bash','-n','-c',builder.CONTAINER_BUILD], check=True) + + def test_owned_docker_resources_are_removed_when_build_fails(self): + (self.root / 'fail-run').touch() + with self.assertRaises(subprocess.CalledProcessError): + builder.build(self.arguments()) + calls = self.docker_calls() + self.assertIn(['rm', '--force', 'b'*64], calls) + self.assertEqual(calls[-1][:2], ['image', 'rm']) + + def test_refuses_output_inside_source_checkout_before_docker(self): + with self.assertRaisesRegex(ValueError, 'outside the source checkout'): + builder.build(self.arguments(output=self.source_repo / 'artifacts/strata')) + self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '') + + def test_refuses_existing_output(self): + output = self.root / 'existing' + output.mkdir() + (output / 'strata').write_bytes(b'keep') + with self.assertRaisesRegex(ValueError, 'refusing to overwrite'): + builder.build(self.arguments(output=output / 'strata')) + self.assertEqual((output / 'strata').read_bytes(), b'keep') + self.assertFalse(self.log.exists()) + + def test_refuses_overlapping_build_and_output_directories(self): + with self.assertRaisesRegex(ValueError, 'must not overlap'): + builder.build(self.arguments(build_dir=self.root / 'out')) + self.assertFalse(self.log.exists()) + + def test_rejects_changed_builder_base_before_docker(self): + with tempfile.TemporaryDirectory() as d: + bad = Path(d) / 'Dockerfile' + bad.write_text('FROM ubuntu:latest\n', encoding='utf-8') + old = builder.DOCKERFILE + builder.DOCKERFILE = bad + try: + with self.assertRaisesRegex(ValueError, 'immutable amd64 base'): + builder.build(self.arguments()) + finally: + builder.DOCKERFILE = old + self.assertFalse(self.log.exists()) + + def test_refuses_tracked_source_changes_before_docker(self): + (self.source_repo / 'scripts/build-static-cuda.sh').write_text('#!/bin/sh\necho modified\n', encoding='utf-8') + diff = subprocess.run(['git', '-C', str(self.source_repo), 'diff', '--quiet', 'HEAD', '--'], check=False) + self.assertEqual(diff.returncode, 1) + with self.assertRaisesRegex(ValueError, 'tracked changes'): + builder.build(self.arguments()) + self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '') + + def test_manual_cuda_job_uses_generic_linux_and_no_artifact_action(self): + workflow = (self.original_repo / '.github/workflows/linux.yml').read_text(encoding='utf-8') + job = workflow.split(' hosted-cuda-package:', 1)[1].split('\n linux-static-cli:', 1)[0] + self.assertIn('runs-on: ubuntu-latest', job) + self.assertIn('scripts/build-cuda-engine-in-docker.py', job) + self.assertIn('gh release create', job) + self.assertNotIn('strata-gpu', job) + self.assertNotIn('actions/upload-artifact', job) + self.assertNotIn('static_cuda_package', workflow) + + +if __name__ == '__main__': + unittest.main()