diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index d1754a16..18b2389e 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -63,6 +63,16 @@ jobs: --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 @@ -71,6 +81,15 @@ jobs: 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}" @@ -161,7 +180,20 @@ jobs: 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" + python3 scripts/build-runtime-image.py --cpu-fixture --package "$RUNNER_TEMP/combined-fixture" \ + --receipt-sha256 "$(sha256sum "$RUNNER_TEMP/combined-fixture/SHA256SUMS" | cut -d ' ' -f 1)" \ + > "$RUNNER_TEMP/combined-image.json" + python3 scripts/smoke-runtime-image.py "$RUNNER_TEMP/combined-image.json" rm "$RUNNER_TEMP/embedded-worker" + - name: Remove owned CPU fixture image + if: always() + run: | + receipt="$RUNNER_TEMP/combined-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" + rm "$receipt" + fi - uses: actions/upload-artifact@v4 with: name: strata-next-linux-x86_64-musl diff --git a/deploy/Dockerfile.runtime b/deploy/Dockerfile.runtime new file mode 100644 index 00000000..ff6af8b1 --- /dev/null +++ b/deploy/Dockerfile.runtime @@ -0,0 +1,15 @@ +# Built only from the private, validated context produced by build-runtime-image.py. +ARG BASE +FROM ${BASE} +ARG BUILD_ID +ARG PACKAGE_KIND +LABEL io.strata.build-id=${BUILD_ID} io.strata.package-kind=${PACKAGE_KIND} +COPY --chmod=0555 strata-next-linux-x86_64-musl /usr/local/bin/strata-next +COPY --chmod=0444 PROVENANCE.json SHA256SUMS /usr/share/strata/ +ENV NVIDIA_VISIBLE_DEVICES=void NVIDIA_DRIVER_CAPABILITIES=compute,utility STRATA_BIND=0.0.0.0:8081 +USER 65532:65532 +WORKDIR /tmp +EXPOSE 8081 +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/local/bin/strata-next"] +CMD ["serve"] diff --git a/deploy/README.md b/deploy/README.md index 5aeaaa59..b653edea 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -666,3 +666,52 @@ 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. + +## Combined runtime OCI preview (STRA-67) + +Build a private image from a trusted STRA-65 combined package (exactly the +executable, `PROVENANCE.json`, and `SHA256SUMS`): + +```sh +python3 scripts/build-runtime-image.py --package /private/package \ + --receipt-sha256 > /private/image.json +``` + +The builder freezes and verifies the three files before Docker receives a minimal +context. An official Ubuntu 26.04 **linux/amd64 manifest digest** is the default +base; its actual `getconf GNU_LIBC_VERSION` reports 2.43 in the isolated validation. +`--base repository@sha256:DIGEST` permits another explicitly pinned glibc image. +A base below the engine's recorded minimum glibc is rejected before image build. +Embedded identity and GPU-hidden `engine-help` are checked inside the resulting +non-root, read-only image. The image ID is returned only after these checks; +failed probes remove the uniquely labelled build image. No public registry push +occurs. Python and Docker are build tools, not serving dependencies. + +Run the image ID with NVIDIA Container Toolkit and a compatible installed host +driver. The caller supplies private configuration, source/model data, and a +writable state directory owned by UID 65532. Example paths inside the configuration +must match these mount destinations: + +```sh +docker run --rm --gpus all --read-only --cap-drop ALL \ + --security-opt no-new-privileges --tmpfs /tmp:rw,nosuid,nodev,size=256m \ + -e NVIDIA_VISIBLE_DEVICES=all -p 127.0.0.1:8081:8081 \ + --mount type=bind,src=/private/config,dst=/config,readonly \ + --mount type=bind,src=/private/models,dst=/models,readonly \ + --mount type=bind,src=/private/state,dst=/state \ + sha256:IMAGE_ID serve --config /config/runtime.json +``` + +The runtime uses its native `@embedded` engine and existing asset/native-model +configuration. Set the profile's explicit GPU requirement and `engine_probe`; +keep the key file private and readable by the container UID. Network access is +needed for configured acquisition; use verified offline assets to avoid it. +Do not mount the Docker socket or include models, keys, logs or configuration in +the build context. The default image exposes no GPU unless requested explicitly. + +The hosted CPU path uses `--cpu-fixture` and verifies actual Responses output `A`, +worker crash/restart and graceful shutdown in the image, with zero tolerance. +The manual private CUDA job now saves the image and provenance alongside the +combined package. Neither CPU success nor hidden-GPU help qualifies CUDA kernels, +lazy driver dependencies, real model/MTP compatibility, quality or clean-node GPU +serving. That full gate remains pending; the active user trial is not migrated. diff --git a/scripts/build-runtime-image.py b/scripts/build-runtime-image.py new file mode 100644 index 00000000..2d557360 --- /dev/null +++ b/scripts/build-runtime-image.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Build-time only: verify a combined package and assemble a private OCI image.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import tempfile +import uuid + +REPO = Path(__file__).resolve().parents[1] +NAME = 'strata-next-linux-x86_64-musl' +FILES = {NAME, 'PROVENANCE.json', 'SHA256SUMS'} +# Official Ubuntu 26.04 linux/amd64 manifest, observed 2026-10-04; glibc is probed. +BASE = 'ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794' + + +def digest(path): + with path.open('rb') as source: + return hashlib.file_digest(source, 'sha256').hexdigest() + + +def frozen_file(source, dest, limit): + 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('package entries must be regular files') + total = 0 + while block := src.read(65536): + total += len(block) + if total > limit: + raise ValueError('package entry exceeds size limit') + dst.write(block) + + +def freeze(package, stage, receipt_sha, cpu_fixture): + if not re.fullmatch(r'[0-9a-f]{64}', receipt_sha): + raise ValueError('receipt SHA256 must be 64 lowercase hex characters') + if {p.name for p in package.iterdir()} != FILES: + raise ValueError('package must contain exactly binary, provenance and SHA256SUMS') + for name in FILES: + frozen_file(package / name, stage / name, 1024**3 if name == NAME else 1024**2) + if digest(stage / 'SHA256SUMS') != receipt_sha: + raise ValueError('pinned receipt SHA256 mismatch') + hashes = {} + for line in (stage / 'SHA256SUMS').read_text().splitlines(): + match = re.fullmatch(r'([0-9a-f]{64}) (strata-next-linux-x86_64-musl|PROVENANCE.json)', line) + if not match or match[2] in hashes: + raise ValueError('invalid or duplicate receipt entry') + hashes[match[2]] = match[1] + if set(hashes) != {NAME, 'PROVENANCE.json'}: + raise ValueError('incomplete receipt') + if any(digest(stage / name) != sha for name, sha in hashes.items()): + raise ValueError('package file checksum mismatch') + p = json.loads((stage / 'PROVENANCE.json').read_text()) + kind = 'cpu-fixture' if cpu_fixture else 'static-cuda-preview' + if (p.get('schema_version') != 1 or p.get('kind') != kind or + 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') + 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 + engine.get('declared_source_revision') != p['source_revision'] or + type(engine.get('bytes')) is not int or not 0 < engine['bytes'] <= 1024**3 or + not re.fullmatch(r'[0-9a-f]{64}', engine.get('sha256', ''))): + raise ValueError('invalid embedded engine identity') + if not cpu_fixture: + audit = p.get('engine_elf_audit', {}) + if audit.get('toolkit_shared_libraries') is not False or audit.get('host_glibc_required') is not True: + raise ValueError('missing static CUDA ELF audit') + version(audit.get('minimum_glibc', '')) + return p + + +def version(value): + if not isinstance(value, str) or not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', value): + raise ValueError('invalid glibc version') + return tuple(map(int, value.split('.'))) + (0,) * (3 - len(value.split('.'))) + + +def check_glibc(provenance, output): + match = re.fullmatch(r'glibc ([0-9]+\.[0-9]+(?:\.[0-9]+)?)\s*', output) + if not match: + raise ValueError('base does not report GNU glibc') + minimum = provenance.get('engine_elf_audit', {}).get('minimum_glibc', '0.0') + if version(match[1]) < version(minimum): + raise ValueError(f'base glibc {match[1]} is below engine requirement {minimum}; choose a compatible pinned base or rebuild engine') + return match[1] + + +def docker(*args, timeout=30, check=True): + return subprocess.run(['docker', *map(str, args)], capture_output=True, text=True, + check=check, timeout=timeout) + + +def isolated_run(image, arguments, *, entrypoint=None): + name = 'strata-image-probe-' + uuid.uuid4().hex + args = ['run', '--name', name, '--rm', '--platform', 'linux/amd64', '--network', 'none', + '--read-only', '--user', '65532:65532', '--cap-drop', 'ALL', + '--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=', + '-e', 'NVIDIA_VISIBLE_DEVICES=void'] + if entrypoint: + args += ['--entrypoint', entrypoint] + try: + return docker(*args, image, *arguments).stdout + finally: + docker('rm', '-f', name, check=False) + + +def assemble(args): + if not re.fullmatch(r'[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}', args.base): + raise ValueError('base must be an explicit lowercase repository@sha256 digest') + image = None + success = False + with tempfile.TemporaryDirectory(prefix='strata-oci-') as tmp: + stage = Path(tmp) + p = freeze(args.package, stage, args.receipt_sha256, args.cpu_fixture) + shutil.copyfile(REPO / 'deploy/Dockerfile.runtime', stage / 'Dockerfile') + # Pull before timed probes, so network latency cannot masquerade as ABI failure. + docker('pull', '--platform', 'linux/amd64', args.base, timeout=300) + glibc = check_glibc(p, isolated_run(args.base, ['GNU_LIBC_VERSION'], entrypoint='getconf')) + iid = stage / '.image-id' + try: + docker('build', '--platform', 'linux/amd64', '--network', 'none', + '--build-arg', 'BASE=' + args.base, '--build-arg', 'BUILD_ID=' + uuid.uuid4().hex, + '--build-arg', 'PACKAGE_KIND=' + p['kind'], '--iidfile', iid, stage, timeout=300) + image = iid.read_text().strip() + if not re.fullmatch(r'sha256:[0-9a-f]{64}', image): + raise ValueError('invalid built image identity') + info = json.loads(isolated_run(image, ['engine-info'])) + if info != p['engine']: + raise ValueError('image embedded metadata differs from pinned package') + isolated_run(image, ['engine-help']) + result = {'schema_version': 1, 'image': image, 'base': args.base, 'base_glibc': glibc, + '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.'} + success = True + return result + finally: + if not success: + # The unique build label makes this image ours, never a caller's tag. + if image is None and iid.exists(): + image = iid.read_text().strip() + if image and re.fullmatch(r'sha256:[0-9a-f]{64}', image): + docker('image', 'rm', image, check=False) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--package', type=Path, required=True) + parser.add_argument('--receipt-sha256', required=True, help='trusted SHA256 of package SHA256SUMS') + parser.add_argument('--base', default=BASE) + parser.add_argument('--cpu-fixture', action='store_true') + args = parser.parse_args() + os.umask(0o077) + try: + print(json.dumps(assemble(args))) + except (ValueError, OSError, subprocess.SubprocessError, KeyError, TypeError) as error: + parser.exit(1, f'Runtime image assembly failed: {error}\n') + + +if __name__ == '__main__': + main() diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 0bfd4879..8ca1a015 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -11,6 +11,7 @@ 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-runtime-image.py" python3 "${repo_root}/scripts/test-keyless-routing.py" cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check diff --git a/scripts/smoke-runtime-image.py b/scripts/smoke-runtime-image.py new file mode 100644 index 00000000..fd20fcb3 --- /dev/null +++ b/scripts/smoke-runtime-image.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Actual combined CPU image proof. Never use with a model/CUDA image.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import urllib.request +import uuid + + +def docker(*args, check=True): + return subprocess.run(['docker', *map(str, args)], check=check, capture_output=True, text=True, timeout=30) + + +def main(receipt): + proof = json.loads(Path(receipt).read_text()) + assert proof['kind'] == 'cpu-fixture' and proof['gpu_tested'] is False + image = proof['image'] + label = docker('inspect', '--format', '{{index .Config.Labels "io.strata.package-kind"}}', image).stdout.strip() + assert label == 'cpu-fixture' + spec = importlib.util.spec_from_file_location('helper', Path(__file__).with_name('smoke-worker-cancel.py')) + helper = importlib.util.module_from_spec(spec); spec.loader.exec_module(helper) + name = 'strata-runtime-smoke-' + uuid.uuid4().hex + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with tempfile.TemporaryDirectory(prefix='strata-container-fixture-') as tmp: + root = Path(tmp); root.chmod(0o755) + helper.tokenizer(root) + (root/'config.json').write_text(json.dumps({'bind': '0.0.0.0:8081', 'model': 'embedded-fixture', + 'engine_probe': True, 'engine': {'executable': '@embedded', 'args': ['/tmp/worker.pid'], + 'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}})) + for path in root.iterdir(): path.chmod(0o644) + try: + docker('run', '-d', '--name', name, '--platform', 'linux/amd64', '--read-only', + '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '65532:65532', + '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-e', 'CUDA_VISIBLE_DEVICES=', + '-e', 'NVIDIA_VISIBLE_DEVICES=void', '-p', '127.0.0.1::8081', + '--mount', f'type=bind,src={root},dst=/fixture,readonly', image, + 'serve', '--config', '/fixture/config.json') + port = int(docker('port', name, '8081/tcp').stdout.strip().rsplit(':', 1)[1]) + def request(route, body=None): + req = urllib.request.Request(f'http://127.0.0.1:{port}{route}', + data=json.dumps(body).encode() if body else None, headers={'Content-Type': 'application/json'}) + with opener.open(req, timeout=5) as response: return json.load(response) + def ready(): + deadline = time.monotonic()+15 + while time.monotonic()