Build opt-in KAR PLE CUDA profile on Gitea

This commit is contained in:
Pavlo Ratushnyi
2026-10-07 16:03:43 +02:00
parent fef5fca6fd
commit 5cc41008eb
11 changed files with 422 additions and 14 deletions
+73 -8
View File
@@ -15,6 +15,10 @@ on:
description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact)
type: boolean
default: false
hosted_cuda_ple:
description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default)
type: boolean
default: false
static_cuda_package:
description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference)
type: boolean
@@ -67,6 +71,7 @@ jobs:
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" \
--build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \
--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
@@ -101,15 +106,17 @@ jobs:
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
if: github.event_name == 'workflow_dispatch' && (inputs.hosted_cuda_package || inputs.hosted_cuda_ple) && github.event.repository.private
needs: verify
runs-on: ubuntu-24.04
timeout-minutes: 150
env:
CUDA_VISIBLE_DEVICES: ''
NVIDIA_VISIBLE_DEVICES: void
BUILD_JOBS: '1'
CARGO_BUILD_JOBS: '2'
CUDA_ARCHITECTURES: '120'
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
steps:
- uses: actions/checkout@v4
- name: Install compatible host tools (no drivers)
@@ -117,31 +124,86 @@ jobs:
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"
sudo apt-get update && sudo apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils
sudo apt-get update && sudo apt-get install -y musl-tools binutils
- name: Assemble pinned build-only CUDA components
run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT"
- name: Build pinned GPU-hidden compiler image
env:
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
run: |
context="$RUNNER_TEMP/strata-cuda-builder-context"
mkdir -p "$context"
cp deploy/Dockerfile.cuda-builder "$context/Dockerfile"
cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt"
docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \
--tag "$CUDA_BUILDER_IMAGE" "$context"
docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
- name: Record actual toolchain
env:
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
run: |
"$CUDACXX" --version
g++-13 --version
docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version
df -h "$RUNNER_TEMP"
free -h
python3 - <<'PYTOOL'
import json, os, platform, subprocess
from pathlib import Path
info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text())
packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}\\n',
'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines()
gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True)
info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(),
gcc=subprocess.check_output(['g++-13','--version'],text=True),
builder_base=os.environ['CUDA_BUILDER_BASE'],
builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(),
builder_packages=packages,
gcc=gcc,
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
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
run: |
mkdir -p "$STRATA_BUILD_DIR"
docker run --rm --platform linux/amd64 --network bridge --read-only \
--user "$(id -u):$(id -g)" --cap-drop ALL --security-opt no-new-privileges \
--tmpfs /tmp:rw,nosuid,size=2g \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
-e CUDACXX=/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/toolkit \
-e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \
-e BUILD_JOBS=1 -e CUDA_ARCHITECTURES -e STRATA_KAR_PLE \
-e STRATA_BUILD_DIR=/build \
--mount "type=bind,src=$GITHUB_WORKSPACE,dst=/workspace,readonly" \
--mount "type=bind,src=$CUDAToolkit_ROOT,dst=/toolkit,readonly" \
--mount "type=bind,src=$STRATA_BUILD_DIR,dst=/build" \
"$CUDA_BUILDER_IMAGE" /bin/bash -euo pipefail -c '
if compgen -G "/dev/nvidia*" >/dev/null; then
echo "NVIDIA devices unexpectedly visible in build container" >&2
exit 1
fi
cd /workspace
scripts/build-static-cuda.sh
'
- name: Bind compile capability to CUDA toolchain provenance
run: |
python3 - <<'PYFEATURES'
import hashlib, json, os
from pathlib import Path
features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json'
features=json.loads(features_path.read_text())
toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
info=json.loads(toolchain_path.read_text())
info['build_features']=features['features']
info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest()
toolchain_path.write_text(json.dumps(info,indent=2)+'\n')
PYFEATURES
- name: Install pinned Rust and musl target
run: |
rustup toolchain install 1.99.0 --profile minimal
@@ -161,6 +223,7 @@ jobs:
package="$RUNNER_TEMP/strata-hosted-cuda-package"
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
@@ -188,6 +251,8 @@ jobs:
docker image rm "$image"
fi
rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build"
docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true
rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
linux-static-cli:
needs: verify
+16
View File
@@ -0,0 +1,16 @@
ARG BUILDER_BASE=ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
FROM ${BUILDER_BASE}
# The caller supplies its verified runner CA bundle as build context. This
# lets later TLS fetches use the runner's complete trust store.
COPY runner-ca-bundle.crt /tmp/runner-ca-bundle.crt
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
binutils ca-certificates cmake gcc-13 g++-13 git make python3 \
&& cp /tmp/runner-ca-bundle.crt /etc/ssl/certs/ca-certificates.crt \
&& rm -f /tmp/runner-ca-bundle.crt \
&& rm -rf /var/lib/apt/lists/*
LABEL org.opencontainers.image.title="Leleka GPU-hidden CUDA build environment"
LABEL org.opencontainers.image.description="CPU-only container for compiling the pinned CUDA engine; no NVIDIA driver or device is installed"
+1
View File
@@ -977,6 +977,7 @@ engine="$PWD/artifacts/build-static-cuda/strata"
python3 scripts/build-linux-package.py \
--engine "$engine" --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" \
--revision "$(git rev-parse HEAD)" \
--build-features "$PWD/artifacts/build-static-cuda/BUILD-FEATURES.json" \
--cargo-target-dir "$PWD/artifacts/combined-build" \
--output "$PWD/artifacts/combined-v1"
```
+19
View File
@@ -15,6 +15,25 @@ still checks payload CRCs. The feature is off in ordinary builds.
`strata_next_kar_ple_probe ARCHIVE 2 ROW...` prints FNV-1a checksums for
comparison with `strata-next model checksum-kar-row` on the matching part.
### Static CUDA PLE package profile
`scripts/build-static-cuda.sh` accepts only `STRATA_KAR_PLE=0|1`; it defaults
to `0`. The script always resets the cached PLE, expert-KAR, and PLE-trace
CMake options explicitly, so reusing a build directory cannot accidentally
retain those experimental arms. `STRATA_KAR_PLE=1` compiles the existing PLE
implementation from `gpu/kar`; it does not select a model, archive, PLE level,
or runtime profile. The private Gitea `hosted_cuda_package` workflow exposes
this build capability as a separate boolean, defaulting off, and binds the
selected flags and CUDA architecture into the checksummed package provenance.
The CUDA runtime and C++ runtime are statically linked for the engine build.
The NVIDIA driver and host glibc remain system dependencies; this is not a
fully static CUDA executable and does not eliminate driver compatibility.
The combined outer CLI is separately built for musl. Neither static linking
nor a PLE-enabled package proves GPU inference, model quality, or a speedup;
the serving profile must still explicitly select the model's PLE archive,
level, and cache budget after the separate GPU gates pass.
This arm measures whether PLE transcoding changes whole-model output and task
quality. It does not load the full compressed model, stage sparse PLE packets
to CUDA, or establish a model throughput gain. Use the same engine source,
+44
View File
@@ -31,6 +31,43 @@ def sha256(path):
return hashlib.file_digest(source, 'sha256').hexdigest()
def build_features(path, revision):
"""Read a bounded, exact-schema static CUDA feature receipt without following links."""
if path is None:
return None
fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as source:
if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
raise ValueError('build feature receipt must be a regular file')
raw = source.read(65537)
if len(raw) > 65536:
raise ValueError('build feature receipt exceeds size limit')
try:
record = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise ValueError('build feature receipt must be UTF-8 JSON') from error
if (not isinstance(record, dict) or set(record) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(record['schema_version']) is not int or record['schema_version'] != 1 or
record['source_revision'] != revision or
not isinstance(record['cuda_architectures'], str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*',
record['cuda_architectures'])):
raise ValueError('unsupported or source-mismatched build feature receipt')
canonical = (json.dumps(record, sort_keys=True, indent=2) + '\n').encode()
if raw != canonical:
raise ValueError('build feature receipt is not canonical JSON')
features = record['features']
if (not isinstance(features, dict) or set(features) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in features.values()) or
features['cuda'] is not True or features['cuda_static_runtime'] is not True or
features['cxx_static_runtime'] is not True or
features['kar_experts'] is not False or features['ple_trace'] is not False):
raise ValueError('build feature receipt violates the static CUDA PLE package contract')
return record, hashlib.sha256(raw).hexdigest()
def source_check(repo, revision):
if not re.fullmatch(r'[0-9a-f]{40}', revision):
raise ValueError('source revision must be a full lowercase Git SHA')
@@ -96,6 +133,9 @@ def assemble(args):
if platform.system() != 'Linux' or platform.machine() != 'x86_64':
raise ValueError('package assembly requires Linux x86_64')
source_check(REPO, args.revision)
features = build_features(getattr(args, 'build_features', None), args.revision)
if args.cpu_fixture and features is not None:
raise ValueError('CPU fixtures cannot claim CUDA build features')
output = args.output.absolute()
output.parent.mkdir(parents=True, exist_ok=True)
output = output.parent.resolve() / output.name
@@ -149,6 +189,8 @@ def assemble(args):
'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False,
'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.',
'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'}
if features is not None:
provenance['build_features'], provenance['build_features_sha256'] = features
(published / 'PROVENANCE.json').write_text(json.dumps(provenance, indent=2) + '\n')
(published / 'SHA256SUMS').write_text(''.join(f'{sha256(p)} {p.name}\n' for p in [binary, published / 'PROVENANCE.json']))
if os.path.lexists(output):
@@ -165,6 +207,8 @@ def main():
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--cargo-target-dir', type=Path, required=True, help='dedicated build directory; do not run other Cargo commands here concurrently')
parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release')
parser.add_argument('--build-features', type=Path,
help='exact build feature receipt emitted by build-static-cuda.sh')
args = parser.parse_args()
try:
print(json.dumps(assemble(args)))
+29
View File
@@ -62,6 +62,32 @@ def freeze(package, stage, receipt_sha, cpu_fixture):
p.get('target') != 'x86_64-unknown-linux-musl' or
not re.fullmatch(r'[0-9a-f]{40}', p.get('source_revision', ''))):
raise ValueError('unsupported package provenance or explicit fixture mode mismatch')
feature_record = p.get('build_features')
feature_sha = p.get('build_features_sha256')
if feature_record is not None or feature_sha is not None:
if (not isinstance(feature_record, dict) or set(feature_record) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(feature_record['schema_version']) is not int or feature_record['schema_version'] != 1 or
feature_record['source_revision'] != p['source_revision'] or
not isinstance(feature_record['cuda_architectures'], str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*',
feature_record['cuda_architectures']) or
not isinstance(feature_sha, str) or
not re.fullmatch(r'[0-9a-f]{64}', feature_sha)):
raise ValueError('invalid static CUDA build feature provenance')
feature_values = feature_record['features']
if (not isinstance(feature_values, dict) or set(feature_values) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in feature_values.values()) or
feature_values['cuda'] is not True or feature_values['cuda_static_runtime'] is not True or
feature_values['cxx_static_runtime'] is not True or
feature_values['kar_experts'] is not False or feature_values['ple_trace'] is not False):
raise ValueError('invalid static CUDA feature selection')
canonical = (json.dumps(feature_record, sort_keys=True, indent=2) + '\n').encode()
if hashlib.sha256(canonical).hexdigest() != feature_sha:
raise ValueError('static CUDA build feature digest mismatch')
elif not cpu_fixture:
raise ValueError('CUDA package lacks an explicit build feature receipt')
engine = p.get('engine', {})
if (engine.get('embedded') is not True or engine.get('target_os') != 'linux' or
engine.get('target_arch') != 'x86_64' or
@@ -140,6 +166,9 @@ def assemble(args):
'package_receipt_sha256': args.receipt_sha256, 'source_revision': p['source_revision'],
'kind': p['kind'], 'gpu_tested': False, 'model_tested': False,
'qualification': 'Non-root GPU-hidden embedded identity and loader help only.'}
if p.get('build_features') is not None:
result['build_features'] = p['build_features']['features']
result['build_features_sha256'] = p['build_features_sha256']
success = True
return result
finally:
+65 -6
View File
@@ -6,17 +6,76 @@ build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-static-cuda}"
jobs="${BUILD_JOBS:-2}"
[[ "$(uname -s)" == Linux ]] || { echo 'Static CUDA engine builds require Linux.' >&2; exit 1; }
# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML.
extra=()
if [[ -n "${STRATA_GGML_DIR:-}" ]]; then
extra+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}")
if [[ ${STRATA_KAR_PLE+x} ]]; then
kar_ple="${STRATA_KAR_PLE}"
else
kar_ple=0
fi
cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \
case "${kar_ple}" in
0) cmake_kar_ple=OFF ;;
1) cmake_kar_ple=ON ;;
*) echo 'STRATA_KAR_PLE must be exactly 0 or 1.' >&2; exit 2 ;;
esac
# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML.
cmake_args=(
-S "${repo_root}/engine/strata" -B "${build_dir}"
-DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF -DSTRATA_CUDA_STATIC=ON \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES="${CUDA_ARCHITECTURES:-120}" \
-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE="${cmake_kar_ple}" \
-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=OFF \
-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE=OFF \
-DSTRATA_NEXT_KAR_DIR="${repo_root}/gpu/kar" \
-DSTRATA_BUILD_TESTS=OFF -DSTRATA_NATIVE_EXPERTS=ON \
-DSTRATA_PORTABLE=ON "${extra[@]}"
-DSTRATA_PORTABLE=ON
)
if [[ -n "${STRATA_GGML_DIR:-}" ]]; then
cmake_args+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}")
fi
cmake "${cmake_args[@]}"
cmake --build "${build_dir}" --parallel "${jobs}" --target strata
python3 "${repo_root}/scripts/check-static-cuda-elf.py" "${build_dir}/strata"
# generate.cpp handles --help before any model or GPU initialization.
env -u LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES= "${build_dir}/strata" --help
# This records compile capability only. The runtime still requires an explicit
# model/profile selection; PLE is experimental and defaults off at serving time.
python3 - "${repo_root}" "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" <<'PYFEATURES'
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
repo, destination, ple, architectures = sys.argv[1:]
revision = subprocess.check_output(['git', '-C', repo, 'rev-parse', 'HEAD'], text=True).strip()
if len(revision) != 40 or any(ch not in '0123456789abcdef' for ch in revision):
raise SystemExit('could not record an exact source revision')
record = {
'schema_version': 1,
'source_revision': revision,
'cuda_architectures': architectures,
'features': {
'cuda': True,
'cuda_static_runtime': True,
'cxx_static_runtime': True,
'kar_ple': ple == '1',
'kar_experts': False,
'ple_trace': False,
},
}
path = Path(destination)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.BUILD-FEATURES-', dir=path.parent)
try:
with os.fdopen(fd, 'w') as output:
json.dump(record, output, sort_keys=True, indent=2)
output.write('\n')
output.flush()
os.fsync(output.fileno())
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
PYFEATURES
+1
View File
@@ -10,6 +10,7 @@ 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-static-cuda-profile.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"
+22
View File
@@ -35,6 +35,28 @@ class PackageTests(unittest.TestCase):
with self.assertRaises(ValueError):
pkg.snapshot(source, self.root / pin, pin)
def test_build_feature_receipt_is_pinned_strict_and_linkage_safe(self):
revision = 'a' * 40
features = {'schema_version': 1, 'source_revision': revision,
'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, 'kar_ple': True,
'kar_experts': False, 'ple_trace': False}}
path = self.root / 'BUILD-FEATURES.json'
path.write_text(json.dumps(features, sort_keys=True, indent=2) + '\n')
parsed, digest = pkg.build_features(path, revision)
self.assertEqual(parsed, features)
self.assertEqual(digest, hashlib.sha256(path.read_bytes()).hexdigest())
with self.assertRaisesRegex(ValueError, 'source-mismatched'):
pkg.build_features(path, 'b' * 40)
features['features']['kar_experts'] = True
path.write_text(json.dumps(features, sort_keys=True, indent=2) + '\n')
with self.assertRaisesRegex(ValueError, 'contract'):
pkg.build_features(path, revision)
path.unlink()
path.symlink_to('/dev/null')
with self.assertRaises(OSError):
pkg.build_features(path, revision)
def test_snapshot_rejects_oversize_and_nonregular_without_block(self):
source = self.root / 'engine'
source.write_bytes(b'over limit')
+49
View File
@@ -1,8 +1,10 @@
#!/usr/bin/env python3
"""Package corruption and ABI rejection without Docker or GPU access."""
import importlib.util
import hashlib
import json
from pathlib import Path
import shutil
import tempfile
import unittest
from types import SimpleNamespace
@@ -26,6 +28,13 @@ class PackageTests(unittest.TestCase):
'declared_source_revision': 'a'*40, 'bytes': 3, 'sha256': 'b'*64},
'engine_elf_audit': {'toolkit_shared_libraries': False,
'host_glibc_required': True, 'minimum_glibc': '2.43'}}
features = {'schema_version': 1, 'source_revision': 'a'*40,
'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True,
'kar_ple': False, 'kar_experts': False, 'ple_trace': False}}
canonical = (json.dumps(features, sort_keys=True, indent=2) + '\n').encode()
self.provenance['build_features'] = features
self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest()
(self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input')
self.write()
@@ -46,6 +55,46 @@ class PackageTests(unittest.TestCase):
b.check_glibc(p, 'glibc 2.39\n')
with self.assertRaises(ValueError): b.check_glibc(p, 'musl 1.2.5')
def test_static_cuda_feature_receipt_is_preserved_and_digest_checked(self):
features = {'schema_version': 1, 'source_revision': 'a'*40,
'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True, 'kar_ple': True,
'kar_experts': False, 'ple_trace': False}}
canonical = (json.dumps(features, sort_keys=True, indent=2) + '\n').encode()
self.provenance['build_features'] = features
self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest()
self.write()
p = self.freeze()
self.assertTrue(p['build_features']['features']['kar_ple'])
self.provenance['build_features_sha256'] = '0'*64
self.write()
shutil.rmtree(self.stage)
self.stage.mkdir()
with self.assertRaisesRegex(ValueError, 'digest mismatch'):
self.freeze()
def test_image_receipt_carries_ple_profile_without_gpu_claim(self):
self.provenance['build_features']['features']['kar_ple'] = True
canonical = (json.dumps(self.provenance['build_features'], sort_keys=True, indent=2) + '\n').encode()
self.provenance['build_features_sha256'] = hashlib.sha256(canonical).hexdigest()
self.write()
args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256=self.sha, cpu_fixture=False)
image = 'sha256:' + 'c'*64
calls = []
def docker(*argv, **kwargs):
calls.append(argv)
if argv[0] == 'build':
Path(argv[argv.index('--iidfile')+1]).write_text(image)
return SimpleNamespace(stdout='')
engine_info = json.dumps(self.provenance['engine'])
with patch.object(b, 'docker', side_effect=docker), \
patch.object(b, 'isolated_run', side_effect=['glibc 2.43', engine_info, 'help']):
result = b.assemble(args)
self.assertEqual(result['build_features']['kar_ple'], True)
self.assertEqual(result['build_features_sha256'], self.provenance['build_features_sha256'])
self.assertFalse(result['gpu_tested'])
self.assertFalse(any('--gpus' in call for call in calls))
def test_pinned_receipt_rejects_replaced_hashes(self):
(self.pkg/'SHA256SUMS').write_text('a'*64 + ' ../outside\n')
with self.assertRaisesRegex(ValueError, 'pinned receipt'): self.freeze()
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Exercise the static CUDA PLE build contract with a mocked Linux toolchain."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name('build-static-cuda.sh')
class StaticCudaProfileTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix='strata-cuda-profile-')
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.repo = self.root / 'repo'
(self.repo / 'scripts').mkdir(parents=True)
(self.repo / 'engine/strata').mkdir(parents=True)
shutil.copyfile(SCRIPT, self.repo / 'scripts/build-static-cuda.sh')
checker = self.repo / 'scripts/check-static-cuda-elf.py'
checker.write_text('raise SystemExit(0)\n')
self.bin = self.root / 'bin'
self.bin.mkdir()
(self.bin / 'uname').write_text('#!/bin/sh\necho Linux\n')
(self.bin / 'cmake').write_text(
'#!/usr/bin/env python3\n'
'import json, os, pathlib, sys\n'
'with open(os.environ["CMAKE_CAPTURE"], "a") as out: out.write(json.dumps(sys.argv[1:])+"\\n")\n'
'if "--build" in sys.argv:\n'
' b=pathlib.Path(sys.argv[sys.argv.index("--build")+1]); b.mkdir(parents=True, exist_ok=True)\n'
' p=b/"strata"; p.write_text("#!/bin/sh\\necho help\\n"); p.chmod(0o755)\n')
for executable in self.bin.iterdir(): executable.chmod(0o755)
self.capture = self.root / 'cmake.jsonl'
self.build = self.root / 'build'
subprocess.run(['git', 'init', '-q', str(self.repo)], check=True)
subprocess.run(['git', '-C', str(self.repo), 'add', '.'], check=True)
subprocess.run(['git', '-C', str(self.repo), '-c', 'user.email=fixture@example.invalid',
'-c', 'user.name=Fixture', 'commit', '-qm', 'mock toolchain fixture'], check=True)
def run_profile(self, value='unset'):
env = dict(os.environ)
env.update(PATH=f'{self.bin}{os.pathsep}{env["PATH"]}',
STRATA_BUILD_DIR=str(self.build), CMAKE_CAPTURE=str(self.capture),
CUDA_ARCHITECTURES='120')
env.pop('STRATA_KAR_PLE', None)
if value != 'unset':
env['STRATA_KAR_PLE'] = value
return subprocess.run(['bash', str(self.repo / 'scripts/build-static-cuda.sh')],
env=env, text=True, capture_output=True)
def captured_configure(self):
calls = [json.loads(line) for line in self.capture.read_text().splitlines()]
configure = next(call for call in reversed(calls) if '-S' in call)
return {arg.split('=', 1)[0]: arg.split('=', 1)[1]
for arg in configure if arg.startswith('-D') and '=' in arg}
def test_defaults_off_and_explicitly_keeps_static_cuda_runtime(self):
result = self.run_profile()
self.assertEqual(result.returncode, 0, result.stderr)
flags = self.captured_configure()
self.assertEqual(flags['-DSTRATA_CUDA_STATIC'], 'ON')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_KAR_DIR'], str(self.repo / 'gpu/kar'))
features = json.loads((self.build / 'BUILD-FEATURES.json').read_text())
self.assertFalse(features['features']['kar_ple'])
self.assertTrue(features['features']['cuda_static_runtime'])
self.assertTrue(features['features']['cxx_static_runtime'])
def test_enabled_profile_is_build_only_and_expert_arm_stays_off(self):
result = self.run_profile('1')
self.assertEqual(result.returncode, 0, result.stderr)
flags = self.captured_configure()
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'ON')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS'], 'OFF')
self.assertEqual(flags['-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE'], 'OFF')
self.assertTrue(json.loads((self.build / 'BUILD-FEATURES.json').read_text())['features']['kar_ple'])
def test_explicit_disable_resets_an_existing_cmake_cache(self):
self.assertEqual(self.run_profile('1').returncode, 0)
result = self.run_profile('0')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.captured_configure()['-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE'], 'OFF')
self.assertFalse(json.loads((self.build / 'BUILD-FEATURES.json').read_text())['features']['kar_ple'])
def test_invalid_values_fail_before_cmake(self):
for value in ('', 'true', 'ON', '2', '01'):
with self.subTest(value=value):
self.capture.unlink(missing_ok=True)
result = self.run_profile(value)
self.assertEqual(result.returncode, 2)
self.assertIn('exactly 0 or 1', result.stderr)
self.assertFalse(self.capture.exists())
if __name__ == '__main__':
unittest.main()