137 lines
6.0 KiB
Python
137 lines
6.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Exercise native drain over HTTP with one active and one queued CPU request."""
|
|
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 main():
|
|
binary = Path(sys.argv[1]).resolve()
|
|
spec = importlib.util.spec_from_file_location('cancel_fixture', Path(__file__).with_name('smoke-worker-cancel.py'))
|
|
fixture = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(fixture)
|
|
with tempfile.TemporaryDirectory(prefix='strata-drain-http-') as directory:
|
|
root = Path(directory)
|
|
fixture.tokenizer(root)
|
|
engine = root / 'engine.sh'
|
|
engine.write_text('''#!/bin/sh
|
|
printf 'READY 262144 stop\\n'
|
|
count=0
|
|
while IFS= read -r line; do
|
|
case "$line" in
|
|
'GEN '*)
|
|
count=$((count + 1))
|
|
printf 'T 79\\n'
|
|
if [ "$count" = 1 ]; then
|
|
while [ ! -e "$2/release" ]; do sleep 0.01; done
|
|
fi
|
|
printf 'T 75\\nDONE 2 7 1.0 2.0 stop\\n' ;;
|
|
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_MAX_WORKER_RESTARTS': '0'}
|
|
|
|
def open_request(path, body=None):
|
|
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
|
|
conn.request('POST' if body is not None else 'GET', path,
|
|
json.dumps(body) if body is not None else None,
|
|
{'Content-Type': 'application/json'})
|
|
return conn, conn.getresponse()
|
|
|
|
def request(path, body=None):
|
|
conn, response = open_request(path, body)
|
|
code, data = response.status, json.loads(response.read())
|
|
conn.close()
|
|
return code, data
|
|
|
|
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.02)
|
|
|
|
with tempfile.TemporaryFile() as logs:
|
|
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
|
|
conn = None
|
|
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
|
try:
|
|
wait_for(lambda: request('/ready')[0] == 200)
|
|
payload = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 8,
|
|
'reasoning': {'effort': 'none'}, 'stream': True}
|
|
conn, response = open_request('/v1/responses', payload)
|
|
assert response.status == 200
|
|
events = []
|
|
while True:
|
|
line = response.readline().decode()
|
|
assert line, 'stream ended before first token'
|
|
if line.startswith('data:'):
|
|
event = json.loads(line[5:])
|
|
events.append(event)
|
|
if event['type'] == 'response.output_text.delta':
|
|
break
|
|
queued = pool.submit(request, '/v1/responses', {**payload, 'stream': False})
|
|
wait_for(lambda: request('/admin/lifecycle')[1]['generation_jobs'] == 2)
|
|
for _ in range(2):
|
|
code, state = request('/admin/drain', {})
|
|
assert code == 200 and state['draining'] and not state['drained']
|
|
assert state['requests_in_flight'] == 2 and state['generation_jobs'] == 2
|
|
assert request('/ready')[0] == 503
|
|
assert request('/status')[1]['ready'] is False
|
|
code, error = request('/v1/responses', payload)
|
|
assert code == 503 and error['error']['code'] == 'runtime_draining'
|
|
assert request('/health')[0] == 200
|
|
(root / 'release').touch()
|
|
events += [json.loads(line[5:]) for line in response.read().decode().splitlines() if line.startswith('data:')]
|
|
conn.close()
|
|
conn = None
|
|
assert [e['sequence_number'] for e in events] == list(range(len(events)))
|
|
assert ''.join(e['delta'] for e in events if e['type'] == 'response.output_text.delta') == 'OK'
|
|
assert events[-1]['type'] == 'response.completed'
|
|
code, result = queued.result(timeout=8)
|
|
assert code == 200 and result['output'][0]['content'][0]['text'] == 'OK'
|
|
wait_for(lambda: request('/admin/lifecycle')[1]['drained'])
|
|
for _ in range(2):
|
|
code, state = request('/admin/resume', {})
|
|
assert code == 200 and not state['draining'] and not state['drained']
|
|
assert request('/ready')[0] == 200
|
|
code, result = request('/v1/responses', {**payload, 'stream': False})
|
|
assert code == 200 and result['output'][0]['content'][0]['text'] == 'OK'
|
|
assert request('/metrics')[1]['generation']['started'] == 3
|
|
finally:
|
|
(root / 'release').touch()
|
|
if conn is not None:
|
|
conn.close()
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=8)
|
|
except subprocess.TimeoutExpired:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
process.wait()
|
|
pool.shutdown(wait=True, cancel_futures=True)
|
|
print('Native drain passed: active SSE and queued JSON preserved, admission/readiness gated, drained state and resume; CPU fixtures only')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|