From edea410253b045bc7ecf131d641211624cb95a0b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 20:00:48 +0200 Subject: [PATCH] build: assemble verified private Linux runtime packages --- .github/workflows/linux.yml | 36 +++++-- deploy/README.md | 44 +++++++++ scripts/build-linux-package.py | 176 +++++++++++++++++++++++++++++++++ scripts/check-local.sh | 1 + scripts/test-linux-package.py | 117 ++++++++++++++++++++++ 5 files changed, 366 insertions(+), 8 deletions(-) create mode 100644 scripts/build-linux-package.py create mode 100644 scripts/test-linux-package.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 1628f7a8..896829cc 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -40,7 +40,7 @@ jobs: run: scripts/check-keyless-gpu.sh static-cuda-package: - if: github.event_name == 'workflow_dispatch' && inputs.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: @@ -51,9 +51,27 @@ jobs: 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: | + 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}" + - 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 private build intermediates if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" + run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" linux-static-cli: needs: verify @@ -134,12 +152,14 @@ jobs: - name: Embedded CPU worker packaging without GPU run: | musl-gcc -O2 -static scripts/fixtures/embedded-worker.c -o "$RUNNER_TEMP/embedded-worker" - export STRATA_EMBED_ENGINE_PATH="$RUNNER_TEMP/embedded-worker" - export STRATA_EMBED_ENGINE_SHA256="$(sha256sum "$STRATA_EMBED_ENGINE_PATH" | cut -d ' ' -f 1)" - export STRATA_EMBED_ENGINE_REVISION="$GITHUB_SHA" - cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next - python3 scripts/smoke-embedded-engine.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next "$STRATA_EMBED_ENGINE_PATH" - rm "$STRATA_EMBED_ENGINE_PATH" + python3 scripts/build-linux-package.py --cpu-fixture --engine "$RUNNER_TEMP/embedded-worker" \ + --sha256 "$(sha256sum "$RUNNER_TEMP/embedded-worker" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ + --cargo-target-dir control-plane/target --output "$RUNNER_TEMP/combined-fixture" + cd "$RUNNER_TEMP/combined-fixture" + sha256sum -c SHA256SUMS + cd "$GITHUB_WORKSPACE" + python3 scripts/smoke-embedded-engine.py "$RUNNER_TEMP/combined-fixture/strata-next-linux-x86_64-musl" "$RUNNER_TEMP/embedded-worker" + rm "$RUNNER_TEMP/embedded-worker" - uses: actions/upload-artifact@v4 with: name: strata-next-linux-x86_64-musl diff --git a/deploy/README.md b/deploy/README.md index 28735ece..cefa9f12 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -620,3 +620,47 @@ A loader failure reports the stage and exit status without echoing child output; use the engine's explicit `--help` (`strata-next engine-help` for embedded payloads) for detailed local loader diagnostics. Full clean-node inference remains a separate qualification step. + +### Assemble a complete private Linux package + +On a Linux x86_64 build host with the CUDA toolkit, GNU toolchain, `musl-gcc`, +Python 3.11+, `readelf`, and the pinned Rust toolchain/target installed: + +```sh +scripts/build-static-cuda.sh +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)" \ + --cargo-target-dir "$PWD/artifacts/combined-build" \ + --output "$PWD/artifacts/combined-v1" +``` + +Commit source changes before packaging. The revision must match the clean +checkout; the engine digest must match the exact frozen bytes embedded by the +existing Rust build. Use a dedicated Cargo directory without concurrent external +Cargo commands. The builder serializes its own calls and never replaces an +existing output directory. Failed assembly removes its private stage and leaves +older packages intact. Linux `renameat2(RENAME_NOREPLACE)` atomically publishes the +new directory; unsupported hosts fail instead of using an overwrite fallback. + +The result contains the combined executable, `PROVENANCE.json`, and `SHA256SUMS`. +It verifies static outer ELF, embedded identity and bounded GPU-hidden engine +help before publication. The provenance records the inner engine's direct +shared-library and minimum glibc requirements. The engine source revision is +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 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, +requests or credentials enter either package. + +A successful package build does not pass the clean-node real-model gate: the +inner engine still requires the recorded host glibc and NVIDIA driver, and lazy +CUDA dependencies, kernels, model/MTP compatibility and quality need separate +qualification. Existing active endpoints are not modified by this build tool. diff --git a/scripts/build-linux-package.py b/scripts/build-linux-package.py new file mode 100644 index 00000000..ad7388e9 --- /dev/null +++ b/scripts/build-linux-package.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Offline release assembly; production serving has no Python dependency.""" +import argparse +import contextlib +import ctypes +import stat +import fcntl +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[1] +TARGET = 'x86_64-unknown-linux-musl' +NAME = 'strata-next-linux-x86_64-musl' +LIMIT = 1024 ** 3 + + +def run(args, **kwargs): + return subprocess.check_output([str(x) for x in args], text=True, **kwargs).strip() + + +def sha256(path): + with path.open('rb') as source: + return hashlib.file_digest(source, 'sha256').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') + if run(['git', '-C', repo, 'rev-parse', 'HEAD']) != revision: + raise ValueError('source revision differs from checkout HEAD') + if run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=no']): + raise ValueError('tracked source changes must be committed before packaging') + + +def snapshot(source, dest, expected): + if not re.fullmatch(r'[0-9a-f]{64}', expected): + raise ValueError('engine SHA256 must be 64 lowercase hexadecimal characters') + digest, size = hashlib.sha256(), 0 + fd = os.open(source, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as src, dest.open('xb') as dst: + if not stat.S_ISREG(os.fstat(src.fileno()).st_mode): + raise ValueError('engine must be a regular file') + while block := src.read(65536): + size += len(block) + if size > LIMIT: + raise ValueError('engine exceeds 1 GiB package limit') + digest.update(block) + dst.write(block) + if digest.hexdigest() != expected: + raise ValueError('engine SHA256 mismatch') + dest.chmod(0o700) + return size + + +def static_outer(binary): + headers = run(['readelf', '-lW', binary]) + dynamic = run(['readelf', '-dW', binary]) + if 'INTERP' in headers or '(NEEDED)' in dynamic: + raise ValueError('outer executable must be static musl (no INTERP/NEEDED)') + return {'program_headers': headers, 'dynamic_section': dynamic} + + +@contextlib.contextmanager +def lock(path): + # Caller-controlled build/output paths are private; keep the inode for reuse. + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + yield + finally: + os.close(fd) + + +def publish(source, output): + # Linux atomic no-replace protects even against a non-cooperating publisher. + libc = ctypes.CDLL(None, use_errno=True) + rename = getattr(libc, 'renameat2', None) + if rename is None: + raise ValueError('host libc must provide renameat2 for safe publication') + rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + rename.restype = ctypes.c_int + if rename(-100, os.fsencode(source), -100, os.fsencode(output), 1) != 0: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code)) + + +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) + output = args.output.absolute() + output.parent.mkdir(parents=True, exist_ok=True) + output = output.parent.resolve() / output.name + target_dir = args.cargo_target_dir.resolve() + if output == target_dir or output in target_dir.parents or target_dir in output.parents: + raise ValueError('package output and Cargo build directory must be disjoint') + target_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + with lock(output.parent / ('.' + output.name + '.package-lock')), lock(target_dir / '.package-lock'): + if os.path.lexists(output): + raise ValueError('output already exists; select a new versioned directory') + with tempfile.TemporaryDirectory(prefix='.' + output.name + '.stage-', dir=output.parent) as tmp: + stage = Path(tmp) + engine = stage / 'engine' + size = snapshot(args.engine.resolve(), engine, args.sha256) + if args.cpu_fixture: + audit = {'kind': 'cpu-fixture', 'gpu_tested': False} + else: + spec = importlib.util.spec_from_file_location('elf_audit', REPO / 'scripts/check-static-cuda-elf.py') + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + audit = checker.inspect(engine) + env = dict(os.environ, STRATA_EMBED_ENGINE_PATH=str(engine), + STRATA_EMBED_ENGINE_SHA256=args.sha256, + STRATA_EMBED_ENGINE_REVISION=args.revision, + CARGO_TARGET_DIR=str(target_dir), CUDA_VISIBLE_DEVICES='') + env.pop('LD_LIBRARY_PATH', None) + subprocess.run(['cargo', 'build', '--manifest-path', str(REPO / 'control-plane/Cargo.toml'), + '--locked', '--release', '--target', TARGET, '--bin', 'strata-next'], + env=env, check=True) + published = stage / 'package' + published.mkdir(mode=0o700) + binary = published / NAME + shutil.copyfile(target_dir / TARGET / 'release/strata-next', binary) + binary.chmod(0o700) + outer = static_outer(binary) + probe_env = {'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': ''} + info = json.loads(run([binary, 'engine-info'], env=probe_env, timeout=30)) + if not (info['embedded'] and info['sha256'] == args.sha256 and + info['declared_source_revision'] == args.revision and info['bytes'] == size and + info['target_os'] == 'linux' and info['target_arch'] == 'x86_64'): + raise ValueError('combined engine identity does not match pinned input') + probe = stage / 'probe.json' + probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True})) + run([binary, 'provision', '--config', probe], env=probe_env, timeout=30) + source_check(REPO, args.revision) + provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview', + 'source_revision': args.revision, 'target': TARGET, 'engine': info, + 'engine_elf_audit': audit, 'outer_elf_audit': outer, + 'cargo_lock_sha256': sha256(REPO / 'control-plane/Cargo.lock'), + 'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']), + '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.'} + (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): + raise ValueError('output appeared during assembly; refusing replacement') + publish(published, output) + return {'output': str(output), 'kind': provenance['kind'], 'gpu_tested': False} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--engine', type=Path, required=True) + parser.add_argument('--sha256', required=True) + parser.add_argument('--revision', required=True) + 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') + args = parser.parse_args() + try: + print(json.dumps(assemble(args))) + except (ValueError, OSError, subprocess.SubprocessError) as error: + parser.exit(1, f'Package assembly failed: {error}\n') + + +if __name__ == '__main__': + main() diff --git a/scripts/check-local.sh b/scripts/check-local.sh index cff2d3ff..0bfd4879 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -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-static-cuda-elf.py" +python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-keyless-routing.py" cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check diff --git a/scripts/test-linux-package.py b/scripts/test-linux-package.py new file mode 100644 index 00000000..fce8b255 --- /dev/null +++ b/scripts/test-linux-package.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Fault boundaries for offline package publication; real assembly runs in Linux CI.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('package', Path(__file__).with_name('build-linux-package.py')) +pkg = importlib.util.module_from_spec(spec) +spec.loader.exec_module(pkg) + + +class PackageTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def test_snapshot_digest_exact_and_bad_pin(self): + source = self.root / 'engine' + payload = b'fixture' * 20000 + source.write_bytes(payload) + digest = hashlib.sha256(payload).hexdigest() + out = self.root / 'copy' + self.assertEqual(pkg.snapshot(source, out, digest), len(payload)) + self.assertEqual(out.read_bytes(), payload) + self.assertEqual(out.stat().st_mode & 0o777, 0o700) + for pin in ['0' * 64, 'bad']: + with self.assertRaises(ValueError): + pkg.snapshot(source, self.root / pin, pin) + + def test_snapshot_rejects_oversize_and_nonregular_without_block(self): + source = self.root / 'engine' + source.write_bytes(b'over limit') + with patch.object(pkg, 'LIMIT', 4), self.assertRaisesRegex(ValueError, 'limit'): + pkg.snapshot(source, self.root / 'copy', hashlib.sha256(source.read_bytes()).hexdigest()) + fifo = self.root / 'pipe' + os.mkfifo(fifo) + with self.assertRaisesRegex(ValueError, 'regular'): + pkg.snapshot(fifo, self.root / 'fifo-copy', '0' * 64) + + def test_source_pin_and_dirty_tree(self): + subprocess.run(['git', 'init', '-q', self.root], check=True) + (self.root / 'source').write_text('initial') + subprocess.run(['git', '-C', self.root, 'add', '.'], check=True) + subprocess.run(['git', '-C', self.root, '-c', 'user.email=fixture@example.invalid', '-c', + 'user.name=Fixture', 'commit', '-qm', 'fixture'], check=True) + revision = pkg.run(['git', '-C', self.root, 'rev-parse', 'HEAD']) + pkg.source_check(self.root, revision) + for wrong in ['bad', '0' * 40]: + with self.assertRaises(ValueError): + pkg.source_check(self.root, wrong) + (self.root / 'source').write_text('changed') + with self.assertRaisesRegex(ValueError, 'committed'): + pkg.source_check(self.root, revision) + + def test_lock_excludes_other_builder_and_symlink(self): + path = self.root / 'lock' + with pkg.lock(path), self.assertRaises(BlockingIOError): + with pkg.lock(path): + self.fail('second writer acquired lock') + alias = self.root / 'alias' + alias.symlink_to(path) + with self.assertRaises(OSError): + with pkg.lock(alias): + self.fail('symlink lock accepted') + + @unittest.skipUnless(sys.platform == 'linux', 'Linux atomic publication') + def test_atomic_publication_never_replaces_existing_directory(self): + staged, output = self.root / 'stage', self.root / 'out' + staged.mkdir() + (staged / 'sentinel').write_text('new') + output.mkdir() + with self.assertRaises(FileExistsError): + pkg.publish(staged, output) + self.assertEqual(list(output.iterdir()), []) + output.rmdir() + pkg.publish(staged, output) + self.assertFalse(staged.exists()) + self.assertEqual((output / 'sentinel').read_text(), 'new') + + def test_outer_elf_rejects_loader_or_shared_library(self): + for outputs in [('INTERP', ''), ('', '(NEEDED)')]: + with patch.object(pkg, 'run', side_effect=outputs), self.assertRaises(ValueError): + pkg.static_outer(Path('fixture')) + with patch.object(pkg, 'run', side_effect=['static headers', 'no dynamic section']): + self.assertIn('program_headers', pkg.static_outer(Path('fixture'))) + + def test_failed_build_cleans_stage_and_does_not_publish(self): + from types import SimpleNamespace + engine = self.root / 'engine' + engine.write_bytes(b'fixture') + output = self.root / 'final' + args = SimpleNamespace(engine=engine, sha256=pkg.sha256(engine), revision='a' * 40, + output=output, cargo_target_dir=self.root / 'target', cpu_fixture=True) + with patch.object(pkg.platform, 'system', return_value='Linux'), patch.object(pkg.platform, 'machine', return_value='x86_64'), patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'cargo')): + with self.assertRaises(subprocess.CalledProcessError): + pkg.assemble(args) + self.assertFalse(output.exists()) + self.assertFalse(list(self.root.glob('.final.stage-*'))) + output.mkdir() + (output / 'old').write_text('keep') + with patch.object(pkg.platform, 'system', return_value='Linux'), patch.object(pkg.platform, 'machine', return_value='x86_64'), patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run') as build: + with self.assertRaisesRegex(ValueError, 'already exists'): + pkg.assemble(args) + build.assert_not_called() + self.assertEqual((output / 'old').read_text(), 'keep') + + +if __name__ == '__main__': + unittest.main()