Files
leleka/scripts/smoke-native-drain.py
Pavlo RatushnyiandClaude Sonnet 5.5 0ca493be04 test: run the scripted-engine HTTP smokes through the runtime stack (fake_runtime over real gRPC)
fake_runtime is a leleka.runtime.v1 server (the real RuntimeServer) whose engine is the same
engine.sh the smokes already use; fixture.runtime_stack() swaps strata-next's engine child for
it when STRATA_TEST_FAKE_RUNTIME is set, otherwise nothing changes. scripts/test-api-over-runtime.py
runs the ten smokes whose assertions do not depend on strata-next owning the engine process.

The HTTP layer clamps reasoning_tokens to the engine-reported output total, which a text-level
engine's re-tokenized pieces can otherwise exceed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 03:00:55 +02:00

161 lines
7.7 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)
key = root / 'key'
key.write_text('fixture-only-admission-secret-00000001')
key.chmod(0o600)
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',
'STRATA_MAX_IN_FLIGHT_REQUESTS': '2', 'STRATA_API_KEY_FILE': str(key)}
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', 'Authorization': 'Bearer ' + key.read_text()})
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)
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
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)
state = request('/admin/lifecycle')[1]
assert state['max_in_flight_requests'] == 2 and state['available_request_slots'] == 0
assert request('/ready')[0] == 200 and request('/status')[1]['ready']
# Auth is outermost; admission rejects before JSON parsing, with no extra GEN.
for authenticated, expected in [(False, 401), (True, 429)]:
rejected = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
headers = {'Content-Type': 'application/json'}
if authenticated:
headers['Authorization'] = 'Bearer ' + key.read_text()
rejected.request('POST', '/v1/responses', '{broken', headers)
rejection = rejected.getresponse()
assert rejection.status == expected
error = json.loads(rejection.read())
if authenticated:
assert rejection.getheader('Retry-After') == '1'
assert error['error']['code'] == 'runtime_overloaded'
rejected.close()
assert request('/metrics')[1]['generation']['started'] == 1
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'])
assert request('/admin/lifecycle')[1]['available_request_slots'] == 2
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 admission/drain passed: limit 2, auth/429/503 precedence, SSE and queued JSON exact output, capacity release/resume and no excess GEN; CPU fixtures only')
if __name__ == '__main__':
main()