Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
177 lines
8.4 KiB
Python
177 lines
8.4 KiB
Python
#!/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=all']):
|
|
raise ValueError('source checkout must be clean before packaging; commit source changes or exclude generated files')
|
|
|
|
|
|
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()
|