Files
leleka/scripts/smoke-messages.py
T
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

360 lines
23 KiB
Python

#!/usr/bin/env python3
"""Native Messages real HTTP fixture: wire parity, named SSE and cancellation."""
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-messages-') as directory:
root = Path(directory)
fixture.tokenizer(root)
key = 'fixture-only-messages-key-0000001'
(root / 'key').write_text(key)
(root / 'key').chmod(0o600)
engine = root / 'engine.sh'
engine.write_text('''#!/bin/sh
printf '%s' "$$" > "$2/pid"
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')}
path = '/v1/messages'
count_path = path + '/count_tokens'
def open_request(method, target, payload=None, headers=None, raw=None):
h = {'Content-Type': 'application/json'}
h.update({'x-api-key': key, 'anthropic-version': '2023-06-01'} if target in (path, count_path) else {'Authorization': 'Bearer ' + key})
if headers:
h.update(headers)
h = {k: v for k, v in h.items() if v is not None}
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=6)
conn.request(method, target, raw if raw is not None else json.dumps(payload) if payload is not None else None, h)
return conn, conn.getresponse()
def request(method, target, payload=None, **kwargs):
conn, response = open_request(method, target, payload, **kwargs)
try:
data = response.read().decode()
if response.getheader('Content-Type', '').startswith('text/event-stream'):
assert '[DONE]' not in data
events = []
for frame in data.strip().split('\n\n'):
lines = frame.splitlines()
name = next(line[7:] for line in lines if line.startswith('event: '))
value = json.loads(next(line[6:] for line in lines if line.startswith('data: ')))
assert value['type'] == name
events.append(value)
return response.status, events
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 {b}\n' for b in data) + f'DONE {len(data)} 7 1.0 2.0 {reason} 0 0 2\n')
def wire():
return (root / 'wire').read_text().splitlines() if (root / 'wire').exists() else []
def count(current, expected=200, **kwargs):
payload = {k: v for k, v in current.items() if k not in ('max_tokens', 'stream')}
before = wire()
stored = {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()}
code, value = request('POST', count_path, payload, **kwargs)
assert code == expected, (code, value)
assert wire() == before
assert stored == {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()}
if code == 200:
assert set(value) == {'input_tokens'} and isinstance(value['input_tokens'], int) and value['input_tokens'] > 0
return value['input_tokens']
assert value['type'] == 'error'
def rebuild(events):
assert events[0]['type'] == 'message_start' and events[-1] == {'type': 'message_stop'}
assert sum(e['type'] == 'message_stop' for e in events) == 1
message = events[0]['message']
assert message['content'] == [] and message['stop_reason'] is None
active = None
args = ''
for e in events[1:]:
kind = e['type']
if kind == 'content_block_start':
assert active is None and e['index'] == len(message['content'])
active = e['index']
message['content'].append(e['content_block'])
args = ''
elif kind == 'content_block_delta':
assert e['index'] == active
if e['delta']['type'] == 'text_delta':
message['content'][active]['text'] += e['delta']['text']
else:
assert e['delta']['type'] == 'input_json_delta'
args += e['delta']['partial_json']
elif kind == 'content_block_stop':
assert active == e['index']
if message['content'][active]['type'] == 'tool_use':
message['content'][active]['input'] = json.loads(args)
active = None
elif kind == 'message_delta':
assert active is None
message.update(e['delta'])
message['usage'].update(e['usage'])
elif kind == 'message_stop':
assert active is None
else:
raise AssertionError(e)
return message
def normalized(message):
value = json.loads(json.dumps(message))
del value['id']
for block in value['content']:
if block['type'] == 'tool_use':
assert block['id'].startswith('call_')
block['id'] = 'ID'
return value
base = {'model': 'fixture', 'max_tokens': 1024, 'messages': [{'role': 'user', 'content': 'Привіт 🌍'}]}
native_base = {'model': 'fixture', 'max_output_tokens': 1024, 'input': base['messages'], 'store': False, 'reasoning': {'effort': 'none'}}
tool = {'name': 'lookup', 'input_schema': {'type': 'object', 'properties': {'key': {'type': 'string'}}}}
native_tool = {'type': 'function', 'name': 'lookup', 'parameters': tool['input_schema']}
tool_text = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
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)
before = wire()
for headers, status in [({'x-api-key': None}, 401), ({'x-api-key': 'wrong'}, 401),
({'Authorization': 'Bearer ' + key}, 401), ({'anthropic-version': None}, 400),
({'anthropic-version': 'future'}, 400), ({'anthropic-beta': 'anything'}, 400)]:
code, value = request('POST', path, base, headers=headers)
assert code == status and value['type'] == 'error' and 'error' in value, value
count(base, status, headers=headers)
assert wire() == before
for duplicate, expected in [('x-api-key', 401), ('anthropic-version', 400)]:
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=6)
conn.putrequest('POST', path)
conn.putheader('Content-Type', 'application/json')
conn.putheader('x-api-key', key)
conn.putheader('anthropic-version', '2023-06-01')
conn.putheader(duplicate, key if duplicate == 'x-api-key' else '2023-06-01')
body = json.dumps(base).encode()
conn.putheader('Content-Length', str(len(body)))
conn.endheaders(body)
response = conn.getresponse()
assert response.status == expected and json.loads(response.read())['type'] == 'error'
conn.close()
assert wire() == before
assert request('POST', path, raw='{')[0] == 400
assert request('GET', path)[0] == 405
assert request('GET', count_path)[0] == 405
assert request('POST', count_path, raw='{')[0] == 400
count(base, 413, raw=json.dumps({'model': 'fixture', 'messages': [{'role': 'user', 'content': 'x' * (16 * 1024 * 1024)}]}))
for extra in [{'max_tokens': 1}, {'stream': False}, {'temperature': 0}, {'unknown': True}]:
payload = {k: v for k, v in base.items() if k != 'max_tokens'}
code, value = request('POST', count_path, {**payload, **extra})
assert code == 400 and value['type'] == 'error', value
count({**base, 'model': 'wrong'}, 404)
count(base, headers={'x-api-key': None, 'Authorization': 'Bearer ' + key})
assert request('GET', '/status', headers={'Authorization': None, 'x-api-key': key})[0] == 401
output('A')
assert request('POST', path, base, headers={'x-api-key': None, 'Authorization': 'Bearer ' + key})[0] == 200
cases = [(base, native_base, 'Вітаю 🌍', 'stop'),
({**base, 'system': [{'type': 'text', 'text': 'A'}, {'type': 'text', 'text': 'B'}], 'messages': [{'role': 'user', 'content': 'Hi'}, {'role': 'user', 'content': [{'type': 'text', 'text': '!'}]}]},
{**native_base, 'instructions': 'A\nB', 'input': [{'role': 'user', 'content': 'Hi\n!'}]}, 'Limited', 'length')]
for choice, mapped in [({'type': 'auto'}, 'auto'), ({'type': 'any'}, 'required'), ({'type': 'tool', 'name': 'lookup'}, {'type': 'function', 'name': 'lookup'})]:
cases.append(({**base, 'tools': [tool], 'tool_choice': choice},
{**native_base, 'tools': [native_tool], 'tool_choice': mapped}, tool_text, 'stop'))
cases.append(({**base, 'tools': [tool]}, {**native_base, 'tools': [native_tool]}, 'Before\n' + tool_text + '\nAfter', 'stop'))
cases.append(({**base, 'tools': [tool], 'tool_choice': {'type': 'auto', 'disable_parallel_tool_use': False}},
{**native_base, 'tools': [native_tool], 'tool_choice': 'auto', 'parallel_tool_calls': True}, tool_text + '\n' + tool_text, 'stop'))
cases.append((base, native_base, '', 'stop'))
for current, native, text, reason in cases:
measured = count(current)
output(text, reason)
code, reference = request('POST', '/v1/responses', native)
assert code == 200, reference
expected_wire = wire()[-1]
assert measured == len(expected_wire.split()[-1].split(','))
code, result = request('POST', path, current)
assert code == 200 and wire()[-1] == expected_wire, result
assert result['type'] == 'message' and result['role'] == 'assistant' and result['model'] == 'fixture'
expected_content = []
for item in reference['output']:
if item['type'] == 'message':
expected_content.extend({'type': 'text', 'text': p['text']} for p in item['content'])
elif item['type'] == 'function_call':
expected_content.append({'type': 'tool_use', 'id': 'ID', 'name': item['name'], 'input': json.loads(item['arguments'])})
assert normalized(result)['content'] == expected_content, (result, reference)
assert result['stop_reason'] == ('max_tokens' if reason == 'length' else 'tool_use' if any(b['type'] == 'tool_use' for b in result['content']) else 'end_turn')
assert result['usage'] == {'input_tokens': 5, 'cache_read_input_tokens': 2, 'cache_creation_input_tokens': 0, 'output_tokens': reference['usage']['output_tokens']}
code, events = request('POST', path, {**current, 'stream': True})
assert code == 200 and wire()[-1] == expected_wire
streamed = rebuild(events)
assert normalized(streamed) == normalized(result), (streamed, result)
if sum(b['type'] == 'tool_use' for b in streamed['content']) == 2:
parallel_result = streamed
streamed = parallel_result
# Use the stream's actual call IDs/objects in the next request.
calls = [b for b in streamed['content'] if b['type'] == 'tool_use']
results = [{'type': 'tool_result', 'tool_use_id': b['id'], 'content': [{'type': 'text', 'text': 'Found 🌍'}]} for b in calls]
transcript = base['messages'] + [{'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': results}]
native_input = base['messages'] + [{'type': 'function_call', 'call_id': b['id'], 'name': b['name'], 'arguments': json.dumps(b['input'], separators=(',', ':'))} for b in calls] + [{'type': 'function_call_output', 'call_id': b['id'], 'output': 'Found 🌍'} for b in calls]
measured = count({**base, 'messages': transcript, 'tools': [tool]})
output('Continued')
assert request('POST', '/v1/responses', {**native_base, 'input': native_input, 'tools': [native_tool]})[0] == 200
expected_wire = wire()[-1]
assert measured == len(expected_wire.split()[-1].split(','))
code, result = request('POST', path, {**base, 'messages': transcript, 'tools': [tool]})
assert code == 200 and wire()[-1] == expected_wire and result['content'] == [{'type': 'text', 'text': 'Continued'}], result
# Tool execution failures and empty results continue in the tool role.
error_text = 'Connection failed 🌍\n"quoted" \\ path\u0000'
variants = [
([{'content': [{'type': 'text', 'text': error_text}], 'is_error': True}, {}],
[json.dumps({'content': error_text, 'is_error': True}, ensure_ascii=False, separators=(',', ':'), sort_keys=True), '']),
([{'is_error': True}, {'content': [], 'is_error': False}],
['{"content":"","is_error":true}', '']),
([{'content': 'Found 🌍', 'is_error': False}, {'content': 'Found 🌍'}],
['Found 🌍', 'Found 🌍']),
]
for fields, expected_outputs in variants:
results = [{'type': 'tool_result', 'tool_use_id': b['id'], **f} for b, f in zip(calls, fields)]
transcript = base['messages'] + [{'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': results}]
current = {**base, 'messages': transcript, 'tools': [tool]}
native_input = base['messages'] + [{'type': 'function_call', 'call_id': b['id'], 'name': b['name'], 'arguments': json.dumps(b['input'], separators=(',', ':'))} for b in calls] + [{'type': 'function_call_output', 'call_id': b['id'], 'output': v} for b, v in zip(calls, expected_outputs)]
measured = count(current)
output('Continued after result')
assert request('POST', '/v1/responses', {**native_base, 'input': native_input, 'tools': [native_tool]})[0] == 200
expected_wire = wire()[-1]
assert measured == len(expected_wire.split()[-1].split(','))
code, result = request('POST', path, current)
assert code == 200 and wire()[-1] == expected_wire and result['stop_reason'] == 'end_turn', result
assert result['content'] == [{'type': 'text', 'text': 'Continued after result'}]
code, events = request('POST', path, {**current, 'stream': True})
assert code == 200 and wire()[-1] == expected_wire
assert normalized(rebuild(events)) == normalized(result)
before = wire()
for bad in [
{'content': None, 'is_error': True}, {'is_error': 'true'},
{'content': [{'type': 'image', 'source': {}}], 'is_error': True},
{'tool_use_id': 'orphan', 'is_error': True},
{'tool_use_id': calls[1]['id'], 'is_error': True},
]:
bad_results = [{'type': 'tool_result', 'tool_use_id': calls[0]['id'], **bad},
{'type': 'tool_result', 'tool_use_id': calls[1]['id']}]
current = {**base, 'tools': [tool], 'messages': base['messages'] + [
{'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': bad_results}]}
for streaming in [False, True]:
code, value = request('POST', path, {**current, 'stream': streaming})
assert code == 400 and value['type'] == 'error', value
count(current, 400)
assert wire() == before
for text, extra, reason in [(tool_text.replace('lookup', 'wrong'), {'tools': [tool]}, 'stop'), ('A', {'tools': [tool], 'tool_choice': {'type': 'any'}}, 'stop'), (tool_text[:35], {'tools': [tool]}, 'length')]:
output(text, reason)
code, value = request('POST', path, {**base, **extra})
assert code == 502 and value['type'] == 'error', value
code, events = request('POST', path, {**base, **extra, 'stream': True})
assert code == 200 and events[-1]['type'] == 'error' and not any(e['type'] == 'message_stop' for e in events)
before = wire()
for extra in [{'thinking': {'type': 'enabled', 'budget_tokens': 10}}, {'stop_sequences': ['END']}, {'top_k': 1},
{'messages': [{'role': 'assistant', 'content': 'prefix'}]}, {'system': [{'type': 'text', 'text': 'secret', 'cache_control': {'type': 'ephemeral'}}]},
{'tools': [{'type': 'web_search', 'name': 'web_search'}]}, {'messages': [{'role': 'user', 'content': [{'type': 'image', 'source': {}}]}]}]:
code, value = request('POST', path, {**base, **extra})
assert code == 400 and value['type'] == 'error', value
count({**base, **extra}, 400)
assert wire() == before and not list((root / 'history').glob('*.json'))
(root / 'hold').touch()
conn, response = open_request('POST', path, {**base, 'stream': True})
while True:
line = response.readline()
assert line
if line.startswith(b'data:'):
event = json.loads(line[5:])
if event.get('delta', {}).get('text') == 'A': break
# Admission counts the streaming Messages request until it disconnects.
blocked_conn, blocked = open_request('POST', path, base)
assert blocked.status == 429 and blocked.getheader('Retry-After') == '1'
assert json.loads(blocked.read())['error']['type'] == 'rate_limit_error'
blocked_conn.close()
count(base, 429)
conn.sock.shutdown(socket.SHUT_RDWR)
response.close()
conn.close()
deadline = time.monotonic() + 3
while not (root / 'stopped').exists():
assert time.monotonic() < deadline, 'STOP not delivered'
time.sleep(.02)
(root / 'hold').unlink()
output('Fresh')
assert request('POST', path, base)[1]['content'] == [{'type': 'text', 'text': 'Fresh'}]
assert request('POST', '/admin/drain', {})[0] == 200
code, value = request('POST', path, base)
assert code == 503 and value['type'] == 'error' and value['error']['type'] == 'overloaded_error', value
count(base, 503)
assert request('POST', '/admin/resume', {})[0] == 200
(root / 'output').write_text('ERR fixture error\n')
assert request('POST', path, base)[0] == 502
code, events = request('POST', path, {**base, 'stream': True})
assert code == 200 and events[-1]['type'] == 'error' and not any(e['type'] == 'message_stop' for e in events)
measured = count(base)
os.kill(int((root / 'pid').read_text()), signal.SIGKILL)
deadline = time.monotonic() + 3
while request('GET', '/ready')[0] == 200:
assert time.monotonic() < deadline
time.sleep(.02)
assert count(base) == measured # tokenizer available without a ready worker
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('Messages error/empty/parallel tool results + count/actual GEN equality/no mutation/outage + JSON/named live SSE/block order/tools/continuation/usage/header auth/errors/STOP/fresh: PASS; actual GEN and greedy parity tolerance=0, CPU only')
if __name__ == '__main__':
main()