177 lines
8.7 KiB
Python
177 lines
8.7 KiB
Python
#!/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_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')
|
|
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)
|
|
untracked = self.root / 'untracked-source'
|
|
untracked.write_text('not in revision')
|
|
with self.assertRaisesRegex(ValueError, 'clean'):
|
|
pkg.source_check(self.root, revision)
|
|
untracked.unlink()
|
|
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, 'clean'):
|
|
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')
|
|
|
|
def test_assembly_records_workspace_lock_digest(self):
|
|
from types import SimpleNamespace
|
|
engine = self.root / 'engine'
|
|
engine.write_bytes(b'CPU package fixture')
|
|
workspace_lock = self.root / 'Cargo.lock'
|
|
workspace_lock.write_text('version = 4\n')
|
|
target = self.root / 'target'
|
|
binary = target / pkg.TARGET / 'release/leleka-api'
|
|
binary.parent.mkdir(parents=True)
|
|
binary.write_bytes(b'outer executable fixture')
|
|
args = SimpleNamespace(engine=engine, sha256=pkg.sha256(engine), revision='a' * 40,
|
|
output=self.root / 'final', cargo_target_dir=target, cpu_fixture=True)
|
|
info = {'embedded': True, 'sha256': args.sha256, 'declared_source_revision': args.revision,
|
|
'bytes': engine.stat().st_size, 'target_os': 'linux', 'target_arch': 'x86_64'}
|
|
published = {}
|
|
|
|
def capture_publication(source, output):
|
|
published.update(json.loads((source / 'PROVENANCE.json').read_text()))
|
|
|
|
with (patch.object(pkg, 'REPO', self.root),
|
|
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'),
|
|
patch.object(pkg, 'static_outer', return_value={'fixture': True}),
|
|
patch.object(pkg, 'run', side_effect=[json.dumps(info), '', 'rustc fixture', 'cargo fixture']),
|
|
patch.object(pkg, 'publish', side_effect=capture_publication)):
|
|
pkg.assemble(args)
|
|
self.assertEqual(published['cargo_lock_sha256'], pkg.sha256(workspace_lock))
|
|
self.assertFalse(published['gpu_tested'])
|
|
self.assertFalse(published['model_tested'])
|
|
self.assertFalse(list(self.root.glob('.final.stage-*')))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|