Files
leleka/scripts/smoke-generation-deadline.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

145 lines
6.3 KiB
Python

#!/usr/bin/env python3
"""CPU-only HTTP execution deadline, no replay, and recovery acceptance."""
import concurrent.futures
import http.client
import importlib.util
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import sys
import tempfile
import time
def exercise(binary, fixture, streaming, restarts):
with tempfile.TemporaryDirectory(prefix='strata-deadline-http-') as directory:
root = Path(directory)
fixture.tokenizer(root)
engine = root / 'engine.sh'
engine.write_text('''#!/bin/sh
printf '%s\\n' "$$" >> "$2/pids"
if [ -e "$2/booted" ]; then recovered=1; else recovered=0; fi
: > "$2/booted"
printf 'READY 262144 stop\\n'
while IFS= read -r line; do
case "$line" in
'GEN '*)
printf '%s\\n' "$line" >> "$2/requests"
printf 'T 79\\n'
if [ "$recovered" = 1 ]; then
printf 'T 75\\nDONE 2 7 1.0 2.0 stop\\n'
else
# Never finish this command. An execution deadline must kill us.
while IFS= read -r ignored; do :; done
exit 3
fi ;;
QUIT) exit 0 ;;
esac
done
''')
engine.chmod(0o700)
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}',
'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_GENERATION_TIMEOUT_S': '1',
'STRATA_MAX_WORKER_RESTARTS': str(restarts)}
def request(path, body=None):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
try:
connection.request('POST' if body is not None else 'GET', path,
json.dumps(body) if body is not None else None,
{'Content-Type': 'application/json'})
response = connection.getresponse()
content = response.read().decode()
return response.status, content
finally:
connection.close()
def get(path):
return json.loads(request(path)[1])
def wait_for(predicate):
deadline = time.monotonic() + 8
while True:
try:
if predicate():
return
except OSError:
pass
assert process.poll() is None and time.monotonic() < deadline, 'condition timed out'
time.sleep(0.01)
with tempfile.TemporaryFile() as logs, concurrent.futures.ThreadPoolExecutor(2) as pool:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs,
start_new_session=True)
try:
wait_for(lambda: request('/ready')[0] == 200)
payload = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 8,
'reasoning': {'effort': 'none'}, 'stream': streaming}
active = pool.submit(request, '/v1/responses', payload)
wait_for(lambda: (root / 'requests').exists())
original_pid = int((root / 'pids').read_text().splitlines()[0])
queued = pool.submit(request, '/v1/responses', {**payload, 'stream': False})
wait_for(lambda: get('/admin/lifecycle')['generation_jobs'] == 2)
code, content = active.result(timeout=6)
if streaming:
assert code == 200
events = [json.loads(line[5:]) for line in content.splitlines() if line.startswith('data:')]
assert [e['sequence_number'] for e in events] == list(range(len(events)))
assert events[-1]['type'] == 'response.failed'
assert events[-1]['response']['status'] == 'failed'
assert 'configured execution deadline' in json.dumps(events[-1])
assert not any(e['type'] == 'response.completed' for e in events)
else:
assert code == 502 and json.loads(content)['error']['code'] == 'generation_failed'
assert 'configured execution deadline' in content
assert queued.result(timeout=6)[0] in (502, 503)
assert len((root / 'requests').read_text().splitlines()) == 1, 'queued work replayed'
wait_for(lambda: get('/admin/lifecycle')['generation_jobs'] == 0)
assert request('/ready')[0] == 503
assert get('/metrics')['generation']['failed_or_interrupted'] == 1
try:
os.kill(original_pid, 0)
except ProcessLookupError:
pass
else:
raise AssertionError('expired worker still alive')
if restarts:
wait_for(lambda: request('/ready')[0] == 200)
code, content = request('/v1/responses', {**payload, 'stream': False})
assert code == 200 and json.loads(content)['output'][0]['content'][0]['text'] == 'OK'
assert len((root / 'requests').read_text().splitlines()) == 2
assert len((root / 'pids').read_text().splitlines()) == 2
assert get('/metrics')['generation']['completed'] == 1
else:
assert get('/status')['worker'] == 'failed'
assert request('/health')[0] == 200
finally:
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def main():
binary = Path(sys.argv[1]).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)
for streaming in (False, True):
for restarts in (0, 1):
exercise(binary, fixture, streaming, restarts)
print('Generation deadline: 4 HTTP cases passed; terminal failures, kill/reap, no replay, fresh recovery output exactly OK; CPU only')
if __name__ == '__main__':
main()