#!/usr/bin/env python3 """CPU-only contract tests for the Docker CUDA builder wrapper.""" import importlib.util import hashlib from io import BytesIO import json from pathlib import Path import shutil import subprocess from types import SimpleNamespace import tempfile import tarfile import unittest from unittest.mock import patch 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_runner_ca_bundle = builder.runner_ca_bundle self.original_repo = builder.REPO self.original_dockerfile = builder.DOCKERFILE self.ca_bundle = b'-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n' self.ca_patch = patch.object(builder, 'runner_ca_bundle', return_value=self.ca_bundle) self.ca_patch.start() 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() context=pathlib.Path(args[-1]) assert 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b' in dockerfile assert (context/'runner-ca-certificates.crt').is_file() assert 'COPY runner-ca-certificates.crt /etc/ssl/certs/ca-certificates.crt' in dockerfile assert 'ca-certificates cmake gcc-13 g++-13 git make ninja-build' 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): self.ca_patch.stop() 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_runner_ca_bundle_resolves_a_default_symlink(self): pem = self.root / 'runner-ca.pem' pem.write_bytes(self.ca_bundle) link = self.root / 'runner-ca-link.pem' link.symlink_to(pem) with patch.object(builder.ssl, 'get_default_verify_paths', return_value=SimpleNamespace(cafile=str(link))): self.assertEqual(self.original_runner_ca_bundle(), self.ca_bundle) def test_runner_ca_bundle_rejects_missing_path(self): missing = self.root / 'missing-ca.pem' with patch.object(builder.ssl, 'get_default_verify_paths', return_value=SimpleNamespace(cafile=str(missing))): with self.assertRaisesRegex(ValueError, 'missing or unreadable'): self.original_runner_ca_bundle() def test_container_build_has_pinned_cpu_only_invocation(self): self.assertIn('stream.write(chr(10))', builder.CONTAINER_BUILD) 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']) self.assertEqual(result['runner_ca_bundle_sha256'], hashlib.sha256(self.ca_bundle).hexdigest()) 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_archive_extraction_rejects_parent_paths_and_symlinks(self): for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)): with self.subTest(name=name): archive = BytesIO() with tarfile.open(fileobj=archive, mode='w:') as output: entry = tarfile.TarInfo(name) entry.type = kind entry.linkname = '../outside' if kind == tarfile.REGTYPE: entry.size = 1 output.addfile(entry, BytesIO(b'x')) else: output.addfile(entry) destination = self.root / f"safe-stage-{name.replace('/', '_')}" destination.mkdir() with self.assertRaisesRegex(ValueError, 'unsafe path|unsupported entry'): builder.extract_git_archive(archive.getvalue(), destination) self.assertEqual(list(destination.iterdir()), []) self.assertFalse((self.root / 'escape').exists()) 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.assertRegex(job, r'apt-get install -y .*\btime\b') self.assertIn('/usr/bin/time -v python3 scripts/build-linux-package.py', job) self.assertIn('--defer-engine-help-probe-to-runtime-image', job) self.assertIn('scripts/build-runtime-image.py --package', job) self.assertIn('contents: read', job) self.assertIn('releases: write', job) self.assertIn('secrets.GITEA_TOKEN', job) self.assertIn('github.api_url', job) self.assertIn('scripts/publish-gitea-release.py', job) self.assertNotIn('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()