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>
263 lines
16 KiB
Python
263 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""Real HTTP Chat/Responses wire parity and stream isolation on a CPU fixture."""
|
|
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('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-chat-') as directory:
|
|
root = Path(directory)
|
|
fixture.tokenizer(root)
|
|
key = 'fixture-only-chat-key-00000000001'
|
|
(root / 'key').write_text(key)
|
|
(root / 'key').chmod(0o600)
|
|
engine = root / 'engine.sh'
|
|
engine.write_text('''#!/bin/sh
|
|
printf 'READY 262144 stop\n'
|
|
while IFS= read -r line; do
|
|
case "$line" in
|
|
'GEN '*)
|
|
printf '%s\n' "$line" >> "$2/wire"
|
|
if [ -e "$2/hold" ]; then
|
|
printf 'T 65\n'
|
|
IFS= read -r line || exit 3
|
|
[ "$line" = STOP ] || exit 4
|
|
: > "$2/stopped"
|
|
printf 'DONE 1 7 1.0 2.0 stop\n'
|
|
else
|
|
cat "$2/output"
|
|
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_MODEL_ID': 'fixture',
|
|
'STRATA_API_KEY_FILE': str(root / 'key'), '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',
|
|
'STRATA_RESPONSE_HISTORY_DIR': str(root / 'history')}
|
|
|
|
def open_request(method, path, payload=None, auth=True, raw=None):
|
|
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=6)
|
|
headers = {'Content-Type': 'application/json'}
|
|
if auth:
|
|
headers['Authorization'] = 'Bearer ' + key
|
|
conn.request(method, path, raw if raw is not None else json.dumps(payload) if payload is not None else None, headers)
|
|
return conn, conn.getresponse()
|
|
|
|
def request(method, path, payload=None, **kwargs):
|
|
conn, response = open_request(method, path, payload, **kwargs)
|
|
try:
|
|
data = response.read().decode()
|
|
if response.getheader('Content-Type', '').startswith('text/event-stream'):
|
|
lines = [line[5:].strip() for line in data.splitlines() if line.startswith('data:')]
|
|
assert lines[-1] == '[DONE]' and lines.count('[DONE]') == 1, lines
|
|
return response.status, [json.loads(line) for line in lines[:-1]]
|
|
return response.status, json.loads(data) if data else None
|
|
finally:
|
|
conn.close()
|
|
|
|
def output(text, reason='stop'):
|
|
data = text.encode()
|
|
(root / 'output').write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 {reason}\n')
|
|
|
|
def wire():
|
|
return (root / 'wire').read_text().splitlines() if (root / 'wire').exists() else []
|
|
|
|
chat_path = '/v1/chat/completions'
|
|
user = {'role': 'user', 'content': 'Привіт 🌍'}
|
|
base = {'model': 'fixture', 'messages': [user], 'max_completion_tokens': 1024}
|
|
response_base = {'model': 'fixture', 'input': [user], 'max_output_tokens': 1024,
|
|
'reasoning': {'effort': 'none'}, 'store': False}
|
|
tool = {'type': 'function', 'function': {'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'key': {'type': 'string'}}}}}
|
|
response_tool = {'type': 'function', **tool['function']}
|
|
tool_text = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
|
|
|
|
def check_stream(events, text, finish='stop', include_usage=False):
|
|
assert events[0]['choices'][0]['delta'] == {'role': 'assistant', 'content': ''}, events
|
|
chunks = [e for e in events if e.get('choices')]
|
|
assert all(e['object'] == 'chat.completion.chunk' and e['model'] == 'fixture' for e in events)
|
|
assert len({(e['id'], e['created']) for e in events}) == 1
|
|
assert all(e['choices'][0]['index'] == 0 for e in chunks)
|
|
assert ''.join(e['choices'][0]['delta'].get('content', '') for e in chunks) == text
|
|
assert [e['choices'][0]['finish_reason'] for e in chunks if e['choices'][0]['finish_reason'] is not None] == [finish]
|
|
assert chunks[-1]['choices'][0]['delta'] == {}
|
|
if include_usage:
|
|
assert all(e['usage'] is None for e in chunks)
|
|
assert events[-1]['choices'] == [] and events[-1]['usage']['prompt_tokens'] == 7
|
|
else:
|
|
assert all('usage' not in e for e in events)
|
|
return chunks
|
|
|
|
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 request('GET', '/ready')[0] == 200:
|
|
break
|
|
except OSError:
|
|
pass
|
|
assert process.poll() is None and time.monotonic() < deadline
|
|
time.sleep(.02)
|
|
assert request('POST', chat_path, base, auth=False)[0] == 401
|
|
assert request('GET', chat_path)[0] == 405
|
|
assert request('POST', chat_path, raw='{')[0] == 400
|
|
cases = [(base, response_base, 'Вітаю 🌍', 'stop'),
|
|
({**base, 'messages': [{'role': 'system', 'content': 'Be brief.'}, {'role': 'developer', 'content': 'Text.'},
|
|
{'role': 'user', 'content': [{'type': 'text', 'text': 'Hi'}, {'type': 'text', 'text': '!'}]}]},
|
|
{**response_base, 'input': [{'role': 'system', 'content': 'Be brief.'}, {'role': 'developer', 'content': 'Text.'}, {'role': 'user', 'content': 'Hi!'}]}, 'A', 'length'),
|
|
({**base, 'response_format': {'type': 'json_object'}},
|
|
{**response_base, 'text': {'format': {'type': 'json_object'}}}, '{"x":1}', 'stop')]
|
|
schema = {'name': 'answer', 'strict': True, 'schema': {'type': 'object', 'properties': {'x': {'type': 'integer'}}, 'required': ['x'], 'additionalProperties': False}}
|
|
cases.append(({**base, 'response_format': {'type': 'json_schema', 'json_schema': schema}},
|
|
{**response_base, 'text': {'format': {'type': 'json_schema', **schema}}}, '{"x":1}', 'stop'))
|
|
for chat, responses, text, reason in cases:
|
|
output(text, reason)
|
|
code, native = request('POST', '/v1/responses', responses)
|
|
assert code == 200, native
|
|
baseline = wire()[-1]
|
|
code, result = request('POST', chat_path, chat)
|
|
assert code == 200 and wire()[-1] == baseline, (code, result)
|
|
assert result['object'] == 'chat.completion' and result['model'] == 'fixture'
|
|
assert result['choices'][0]['message']['content'] == native['output'][0]['content'][0]['text'] == text
|
|
assert result['choices'][0]['finish_reason'] == reason
|
|
assert result['usage']['completion_tokens'] == native['usage']['output_tokens']
|
|
for include in (False, True):
|
|
code, events = request('POST', chat_path, {**chat, 'stream': True, 'stream_options': {'include_usage': include}})
|
|
assert code == 200 and wire()[-1] == baseline
|
|
check_stream(events, text, reason, include)
|
|
output(tool_text)
|
|
for choice, mapped in [('auto', 'auto'), ('required', 'required'),
|
|
({'type': 'function', 'function': {'name': 'lookup'}}, {'type': 'function', 'name': 'lookup'})]:
|
|
chat = {**base, 'tools': [tool], 'tool_choice': choice}
|
|
code, native = request('POST', '/v1/responses', {**response_base, 'tools': [response_tool], 'tool_choice': mapped})
|
|
assert code == 200, native
|
|
baseline = wire()[-1]
|
|
code, result = request('POST', chat_path, chat)
|
|
assert code == 200 and wire()[-1] == baseline, result
|
|
message = result['choices'][0]['message']
|
|
assert message['content'] is None and result['choices'][0]['finish_reason'] == 'tool_calls'
|
|
calls = message['tool_calls']
|
|
assert len(calls) == 1 and calls[0]['function'] == {'name': 'lookup', 'arguments': native['output'][0]['arguments']}
|
|
assert calls[0]['id'].startswith('call_')
|
|
code, events = request('POST', chat_path, {**chat, 'stream': True})
|
|
chunks = check_stream(events, '', 'tool_calls')
|
|
deltas = [c for e in chunks for c in e['choices'][0]['delta'].get('tool_calls', [])]
|
|
assert len(deltas) == 1 and deltas[0]['index'] == 0 and deltas[0]['function'] == calls[0]['function']
|
|
assert wire()[-1] == baseline
|
|
output(tool_text + '\n' + tool_text)
|
|
code, events = request('POST', chat_path, {**base, 'tools': [tool], 'parallel_tool_calls': True, 'stream': True})
|
|
chunks = check_stream(events, '', 'tool_calls')
|
|
deltas = [c for e in chunks for c in e['choices'][0]['delta'].get('tool_calls', [])]
|
|
assert [d['index'] for d in deltas] == [0, 1] and len({d['id'] for d in deltas}) == 2
|
|
output('Alias')
|
|
alias = {**base, 'max_tokens': base['max_completion_tokens'], 'n': 1, 'reasoning_effort': 'none', 'store': False}
|
|
del alias['max_completion_tokens']
|
|
code, result = request('POST', chat_path, alias)
|
|
assert code == 200 and result['choices'][0]['message']['content'] == 'Alias'
|
|
# Chat's emitted ID and exact argument string survive a full continuation.
|
|
call_id, arguments = calls[0]['id'], calls[0]['function']['arguments']
|
|
transcript = [user, message, {'role': 'tool', 'tool_call_id': call_id, 'content': 'Found 🌍'}]
|
|
native_input = [user, {'type': 'function_call', 'call_id': call_id, 'name': 'lookup', 'arguments': arguments},
|
|
{'type': 'function_call_output', 'call_id': call_id, 'output': 'Found 🌍'}]
|
|
output('Continued')
|
|
assert request('POST', '/v1/responses', {**response_base, 'input': native_input, 'tools': [response_tool]})[0] == 200
|
|
baseline = wire()[-1]
|
|
code, result = request('POST', chat_path, {**base, 'messages': transcript, 'tools': [tool]})
|
|
assert code == 200 and wire()[-1] == baseline and result['choices'][0]['message']['content'] == 'Continued', result
|
|
# Model-output validation failures must not become a successful terminal chunk.
|
|
for text, extra in [('not JSON', {'response_format': {'type': 'json_object'}}),
|
|
(tool_text.replace('lookup', 'undeclared'), {'tools': [tool]}),
|
|
('A', {'tools': [tool], 'tool_choice': 'required'})]:
|
|
output(text)
|
|
assert request('POST', chat_path, {**base, **extra})[0] == 502
|
|
code, events = request('POST', chat_path, {**base, **extra, 'stream': True})
|
|
assert code == 200 and 'error' in events[-1], events
|
|
assert not any(e.get('choices', [{}])[0].get('finish_reason') for e in events)
|
|
assert not any(e.get('choices', [{}])[0].get('delta', {}).get('tool_calls') for e in events)
|
|
before = wire()
|
|
for extra in [{'n': 2}, {'store': True}, {'reasoning_effort': 'high'}, {'stop': ['END']},
|
|
{'frequency_penalty': 3}, {'logprobs': True}, {'stream_options': {}},
|
|
{'max_tokens': 1}, {'messages': [{'role': 'user', 'content': [{'type': 'image_url', 'image_url': {'url': 'x'}}]}]},
|
|
{'tools': [{'type': 'custom', 'name': 'x'}]}, {'messages': [{'role': 'tool', 'content': 'orphan', 'tool_call_id': 'missing'}]}]:
|
|
assert request('POST', chat_path, {**base, **extra})[0] == 400, extra
|
|
assert wire() == before, 'unsupported input reached worker'
|
|
assert not list((root / 'history').glob('*.json')), 'Chat must be stateless'
|
|
# Exhaust the shared admission limit with an incomplete Chat body.
|
|
with socket.create_connection(('127.0.0.1', port), timeout=5) as held:
|
|
held.sendall(('POST ' + chat_path + ' HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\n'
|
|
'Content-Length: 100\r\nAuthorization: Bearer ' + key + '\r\n\r\n{').encode())
|
|
deadline = time.monotonic() + 3
|
|
while request('GET', '/admin/lifecycle')[1]['requests_in_flight'] == 0:
|
|
assert time.monotonic() < deadline
|
|
time.sleep(.02)
|
|
assert request('POST', chat_path, base)[0] == 429
|
|
deadline = time.monotonic() + 3
|
|
while request('GET', '/admin/lifecycle')[1]['requests_in_flight']:
|
|
assert time.monotonic() < deadline
|
|
time.sleep(.02)
|
|
# A genuine live delta arrives while the worker withholds DONE; disconnect sends STOP.
|
|
(root / 'hold').touch()
|
|
conn, response = open_request('POST', chat_path, {**base, 'stream': True})
|
|
assert response.status == 200
|
|
while True:
|
|
line = response.readline()
|
|
assert line, 'no live token before terminal'
|
|
if line.startswith(b'data:') and json.loads(line[5:])['choices'][0]['delta'].get('content') == 'A':
|
|
break
|
|
conn.sock.shutdown(socket.SHUT_RDWR)
|
|
response.close()
|
|
conn.close()
|
|
deadline = time.monotonic() + 3
|
|
while not (root / 'stopped').exists():
|
|
assert time.monotonic() < deadline, 'Chat disconnect did not deliver STOP'
|
|
time.sleep(.02)
|
|
(root / 'hold').unlink()
|
|
output('Fresh')
|
|
code, result = request('POST', chat_path, base)
|
|
assert code == 200 and result['choices'][0]['message']['content'] == 'Fresh', result
|
|
assert request('POST', '/admin/drain', {})[0] == 200
|
|
before = wire()
|
|
assert request('POST', chat_path, base)[0] == 503 and wire() == before
|
|
assert request('POST', '/admin/resume', {})[0] == 200
|
|
(root / 'output').write_text('ERR fixture worker error\n')
|
|
assert request('POST', chat_path, base)[0] == 502
|
|
code, events = request('POST', chat_path, {**base, 'stream': True})
|
|
assert code == 200 and 'error' in events[-1]
|
|
assert not any(e.get('choices', [{}])[0].get('finish_reason') for e in events)
|
|
finally:
|
|
os.killpg(process.pid, signal.SIGTERM)
|
|
try:
|
|
process.wait(timeout=8)
|
|
except subprocess.TimeoutExpired:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
process.wait(timeout=3)
|
|
if process.returncode != 0:
|
|
logs.seek(0)
|
|
raise AssertionError(logs.read().decode())
|
|
print('Chat JSON/live SSE/usage/text/tools/history/errors/auth/drain/STOP and fresh request: PASS; actual GEN/greedy parity tolerance=0 (CPU fixture)')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|