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>
181 lines
8.8 KiB
Python
181 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Actual idle HTTP SSE, terminal parity and cancellation on isolated CPU workers."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
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 load(name, filename):
|
|
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename))
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def check(binary, kind, fixture, replay):
|
|
with tempfile.TemporaryDirectory(prefix='strata-sse-idle-') as directory:
|
|
root = Path(directory)
|
|
fixture.tokenizer(root)
|
|
text = '{"ok":true}' if kind == 'structured' else 'A'
|
|
response = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 1024,
|
|
'reasoning': {'effort': 'none'}, 'store': False}
|
|
path = '/v1/responses'
|
|
if kind == 'structured':
|
|
response['text'] = {'format': {'type': 'json_object'}}
|
|
elif kind == 'tools':
|
|
response['tools'] = [{'type': 'function', 'name': 'lookup', 'parameters': {
|
|
'type': 'object', 'properties': {'key': {'type': 'string'}}}}]
|
|
text = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
|
|
elif kind in ('chat', 'messages'):
|
|
path = '/v1/chat/completions' if kind == 'chat' else '/v1/messages'
|
|
response = {'model': 'fixture', 'messages': [{'role': 'user', 'content': 'hello'}],
|
|
'max_tokens': 1024}
|
|
data = text.encode()
|
|
(root / 'output').write_text(''.join(f'T {b}\n' for b in data)
|
|
+ f'DONE {len(data)} 7 1.0 2.0 stop\n')
|
|
engine = root / 'engine.py'
|
|
engine.write_text(f'#!{sys.executable}\n' + '''import os, pathlib, select, sys
|
|
root = pathlib.Path(sys.argv[2])
|
|
(root / 'pid').write_text(str(os.getpid()))
|
|
print('READY 262144 stop', flush=True)
|
|
while True:
|
|
line = sys.stdin.readline()
|
|
if not line or line.strip() == 'QUIT': break
|
|
if not line.startswith('GEN '): continue
|
|
with (root / 'wire').open('a') as log: log.write(line)
|
|
canceled = False
|
|
while not (root / 'release').exists():
|
|
if select.select([sys.stdin], [], [], .02)[0]:
|
|
command = sys.stdin.readline().strip()
|
|
if command == 'QUIT': sys.exit(0)
|
|
if command == 'STOP':
|
|
(root / 'stopped').touch()
|
|
print('DONE 0 7 1.0 2.0 stop', flush=True)
|
|
canceled = True
|
|
break
|
|
if not canceled: print((root / 'output').read_text(), end='', flush=True)
|
|
''')
|
|
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_MODEL_ID': 'fixture',
|
|
'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
|
|
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_IN_FLIGHT_REQUESTS': '1',
|
|
'STRATA_MAX_WORKER_RESTARTS': '0'}
|
|
|
|
def open_request(method, target, payload=None):
|
|
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=22)
|
|
conn.request(method, target, json.dumps(payload) if payload is not None else None,
|
|
{'Content-Type': 'application/json', 'anthropic-version': '2023-06-01'})
|
|
r = conn.getresponse()
|
|
assert r.status == 200, (kind, r.status, r.read())
|
|
return conn, r
|
|
|
|
def get(target):
|
|
conn, r = open_request('GET', target)
|
|
try: return json.loads(r.read())
|
|
finally: conn.close()
|
|
|
|
def until_comment(r):
|
|
started = time.monotonic()
|
|
body = bytearray()
|
|
while True:
|
|
line = r.readline()
|
|
assert line, (kind, 'stream ended before idle comment')
|
|
body.extend(line)
|
|
assert len(body) < 65536, (kind, 'unexpected prefill output')
|
|
if line.startswith(b':'):
|
|
assert line.strip() == b': keep-alive', line
|
|
assert r.readline() == b'\n'
|
|
body.extend(b'\n')
|
|
assert 13 <= time.monotonic() - started < 22, (kind, 'idle interval')
|
|
return body.decode()
|
|
|
|
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)
|
|
try:
|
|
deadline = time.monotonic() + 10
|
|
while True:
|
|
try:
|
|
if get('/status')['ready']: break
|
|
except (OSError, AssertionError): pass
|
|
assert process.poll() is None and time.monotonic() < deadline, kind
|
|
time.sleep(.02)
|
|
pid = (root / 'pid').read_text()
|
|
conn, r = open_request('POST', path, {**response, 'stream': True})
|
|
assert r.getheader('Content-Type').startswith('text/event-stream')
|
|
before = until_comment(r)
|
|
assert 'output_text.delta' not in before and 'content_block_delta' not in before
|
|
(root / 'release').touch()
|
|
body = before + r.read().decode() # Must end, not keep ticking after terminal.
|
|
conn.close()
|
|
events = [json.loads(line[5:]) for line in body.splitlines()
|
|
if line.startswith('data:') and line[5:].strip() != '[DONE]']
|
|
if path == '/v1/responses':
|
|
terminal, _ = replay.verify_sse(body)
|
|
expected = replay.semantic(terminal)
|
|
elif kind == 'chat':
|
|
assert body.count('data: [DONE]') == 1
|
|
assert ''.join(e['choices'][0]['delta'].get('content', '') for e in events) == 'A'
|
|
assert [e['choices'][0]['finish_reason'] for e in events
|
|
if e['choices'][0]['finish_reason'] is not None] == ['stop']
|
|
else:
|
|
assert events[-1]['type'] == 'message_stop'
|
|
assert sum(e['type'] == 'message_stop' for e in events) == 1
|
|
assert ''.join(e.get('delta', {}).get('text', '') for e in events) == 'A'
|
|
(root / 'release').unlink()
|
|
conn, r = open_request('POST', path, {**response, 'stream': True})
|
|
until_comment(r)
|
|
conn.sock.shutdown(socket.SHUT_RDWR)
|
|
r.close()
|
|
conn.close()
|
|
deadline = time.monotonic() + 5
|
|
while not (root / 'stopped').exists() or get('/admin/lifecycle')['generation_jobs']:
|
|
assert time.monotonic() < deadline, (kind, 'disconnect retained work')
|
|
time.sleep(.02)
|
|
assert get('/admin/lifecycle')['requests_in_flight'] == 0
|
|
(root / 'release').touch()
|
|
conn, r = open_request('POST', path, {**response, 'stream': False})
|
|
result = json.loads(r.read())
|
|
conn.close()
|
|
if path == '/v1/responses':
|
|
assert replay.semantic(result) == expected
|
|
assert result['usage'] == terminal['usage']
|
|
elif kind == 'chat':
|
|
assert result['choices'][0]['message']['content'] == 'A'
|
|
else:
|
|
assert result['content'] == [{'type': 'text', 'text': 'A'}]
|
|
wires = (root / 'wire').read_text().splitlines()
|
|
assert len(wires) == 3 and wires[0] == wires[1] == wires[2]
|
|
assert (root / 'pid').read_text() == pid
|
|
print(f'{kind}: idle comment, exact output/GEN parity, terminal EOF, disconnect and same-worker reuse passed')
|
|
finally:
|
|
if process.poll() is None:
|
|
os.killpg(process.pid, signal.SIGTERM)
|
|
try: process.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
process.wait(timeout=5)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
binary = str(Path(sys.argv[1]).resolve())
|
|
fixture = load('fixture', 'smoke-worker-cancel.py')
|
|
replay = load('replay', 'replay-live-responses.py')
|
|
with ThreadPoolExecutor(max_workers=5) as pool:
|
|
futures = [pool.submit(check, binary, kind, fixture, replay)
|
|
for kind in ('text', 'structured', 'tools', 'chat', 'messages')]
|
|
for future in futures: future.result()
|