Files
leleka/scripts/smoke-asset-bootstrap.py
Pavlo Ratushnyi 4013e0c9bd
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
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

228 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""CPU-only asset acquisition/atomic publication and native serve ordering."""
import hashlib
import importlib.util
import http.client
import http.server
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import threading
import time
def main():
binary = str(Path(sys.argv[1]).resolve())
payloads = {'weights.pack': b'synthetic pinned pack', 'metadata.json': b'{}\n'}
requests = []
slow_entered, slow_release = threading.Event(), threading.Event()
class Source(http.server.BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
name = self.path.lstrip('/')
requests.append(name)
if name == 'slow':
slow_entered.set()
slow_release.wait(15)
name = 'weights.pack'
data = payloads[name]
self.send_response(200)
self.send_header('Content-Length', str(len(data)))
self.end_headers()
try:
self.wfile.write(data)
except (BrokenPipeError, ConnectionResetError):
pass
with tempfile.TemporaryDirectory(prefix='strata-asset-bootstrap-') as tmp:
root = Path(tmp).resolve()
spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py'))
fixture = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fixture)
tokenizer_source = root / 'tokenizer-source'
tokenizer_source.mkdir()
fixture.tokenizer(tokenizer_source)
tokenizer_config = json.loads((tokenizer_source / 'tokenizer.json').read_text())
tokenizer_config['n_merges'] = 1
(tokenizer_source / 'tokenizer.json').write_text(json.dumps(tokenizer_config))
(tokenizer_source / 'merges.txt').write_text('a b')
payloads.update({p.name: p.read_bytes() for p in tokenizer_source.iterdir()})
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Source)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
processes = []
source = f'http://127.0.0.1:{server.server_port}'
manifest = {'schema_version': 1, 'files': [
{'name': name, 'url': source + '/' + name, 'size': len(data),
'sha256': hashlib.sha256(data).hexdigest()} for name, data in payloads.items()]}
manifest_path = root / 'manifest.json'
manifest_path.write_text(json.dumps(manifest))
destination = root / 'version-one'
config_path = root / 'config.json'
marker = root / 'worker-started'
worker = root / 'worker.sh'
worker.write_text('''#!/bin/sh
set -eu
# Supervisor adds --serve as argument one.
[ "$(cat "$2/weights.pack")" = 'synthetic pinned pack' ]
[ "$(cat "$2/metadata.json")" = '{}' ]
: > "$3"
printf 'READY 256 stop\n'
while IFS= read -r line; do
case "$line" in QUIT) exit 0 ;; esac
done
''')
worker.chmod(0o700)
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
config = {'bind': f'127.0.0.1:{port}', 'assets': [
{'manifest': str(manifest_path), 'directory': str(destination)}],
'engine': {'executable': str(worker), 'args': [str(destination), str(marker)],
'startup_timeout_s': 5, 'max_restarts': 0}}
env = {'PATH': os.defpath}
count = 0
def save():
config_path.write_text(json.dumps(config))
def run(command='provision', ok=True):
nonlocal count
save()
r = subprocess.run([binary, command, '--config', str(config_path)], env=env,
capture_output=True, text=True, timeout=15)
assert (r.returncode == 0) == ok, (r.stdout, r.stderr)
count += 1
return r
def spawn(command):
save()
log = open(root / f'process-{len(processes)}.log', 'w+')
p = subprocess.Popen([binary, command, '--config', str(config_path)], env=env,
stdout=log, stderr=log)
processes.append((p, log))
return p
def stop(p):
if p.poll() is None:
p.terminate()
p.wait(timeout=8)
try:
# A malformed later manifest must reject before the first download.
bad = root / 'bad.json'
bad.write_text('{}')
config['assets'].append({'manifest': str(bad), 'directory': str(root / 'other')})
run(ok=False)
assert not requests and not destination.exists()
config['assets'].pop()
report = json.loads(run('check-config').stdout)
assert report['asset_bundles_configured'] == 1 and not report['assets_verified']
assert not requests and not destination.exists() and not marker.exists()
# A bad second file cannot publish even the valid first file.
config['engine']['tokenizer_dir'] = str(destination)
manifest['files'][1]['sha256'] = '0' * 64
manifest_path.write_text(json.dumps(manifest))
run('serve', ok=False)
assert not destination.exists() and not marker.exists()
with socket.socket() as check:
check.bind(('127.0.0.1', port))
manifest['files'][1]['sha256'] = hashlib.sha256(payloads['metadata.json']).hexdigest()
manifest_path.write_text(json.dumps(manifest))
p = spawn('serve')
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
if p.poll() is not None:
raise AssertionError('serve exited before readiness')
try:
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=1)
conn.request('GET', '/ready')
r = conn.getresponse()
r.read()
if r.status == 200:
break
except OSError:
pass
finally:
conn.close()
time.sleep(.02)
else:
raise AssertionError('worker never ready')
assert marker.exists()
for name, data in payloads.items():
assert (destination / name).read_bytes() == data
stop(p)
count += 1
# Preserve published data on mismatch; never replace in place.
manifest['files'][0]['sha256'] = '0' * 64
manifest_path.write_text(json.dumps(manifest))
before = len(requests)
run(ok=False)
assert len(requests) == before
assert (destination / 'weights.pack').read_bytes() == payloads['weights.pack']
manifest['files'][0]['sha256'] = hashlib.sha256(payloads['weights.pack']).hexdigest()
manifest_path.write_text(json.dumps(manifest))
# A process death releases the lock; an interrupted stage is reusable.
config['assets'][0]['directory'] = str(root / 'version-two')
manifest['files'][0]['url'] = source + '/slow'
manifest_path.write_text(json.dumps(manifest))
p = spawn('provision')
assert slow_entered.wait(5)
assert 'busy' in run(ok=False).stderr # competing preparer cannot enter the stage
assert not (root / 'version-two').exists()
p.kill()
p.wait(timeout=5)
slow_release.set()
run()
assert (root / 'version-two' / 'weights.pack').read_bytes() == payloads['weights.pack']
# Reject symlinks and overlapping destinations, without writes.
alias = root / 'alias'
alias.symlink_to(destination, target_is_directory=True)
config['assets'][0]['directory'] = str(alias)
run(ok=False)
config['assets'][0]['directory'] = str(destination)
config['assets'].append({'manifest': str(manifest_path), 'directory': str(destination / 'child')})
run(ok=False)
config['assets'].pop()
config['assets'][0]['directory'] = '../escape'
run(ok=False)
config['assets'][0]['directory'] = str(destination)
# Once published, no network is needed, but bytes are still checked.
server.shutdown()
server.server_close()
thread.join(timeout=5)
assert json.loads(run().stdout) == {'assets_verified': 1, 'native_model_prepared': False, 'mtp_pack_structurally_validated': False, 'worker_started': False}
corrupt = b'x' * len(payloads['weights.pack'])
(destination / 'weights.pack').write_bytes(corrupt)
run(ok=False)
assert (destination / 'weights.pack').read_bytes() == corrupt
print(json.dumps({'status': 'passed', 'scenarios': count,
'real_model': False, 'gpu_used': False}))
finally:
slow_release.set()
for p, log in processes:
stop(p)
if p.returncode not in (0, -9, -15):
log.seek(0)
print(log.read(), file=sys.stderr)
log.close()
server.shutdown()
server.server_close()
thread.join(timeout=5)
if __name__ == '__main__':
main()