Files
leleka/scripts/smoke-custom-tools.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

169 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""CPU HTTP custom-tool contract smoke; uses a synthetic byte-token engine."""
import http.client
import hashlib
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-custom-http-') as directory:
root = Path(directory)
fixture.tokenizer(root)
def publish(text):
# Keep any previous cat reader on an immutable inode until EOF.
staged = root / 'next.new'
staged.write_text(text)
staged.replace(root / 'next')
source = '\n print("Привіт 🌍")\n'
markup = '<tool_call>\n<function=run>\n<parameter=input>\n' + source + '\n</parameter>\n</function>\n</tool_call>'
for name, output in [('plain', markup), ('reason', 'Think.</think>\n\n' + markup), ('answer', 'OK')]:
data = output.encode()
(root / name).write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n')
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))
cat "$2/next" ;;
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 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'})
response = conn.getresponse()
status, data = response.status, response.read().decode()
conn.close()
return status, data
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
deadline = time.monotonic() + 8
while True:
try:
if request('/ready')[0] == 200:
break
except OSError:
pass
assert process.poll() is None and time.monotonic() < deadline
time.sleep(0.02)
for effort in ['none', 'low']:
for stream in [False, True]:
publish((root / ('plain' if effort == 'none' else 'reason')).read_text())
payload = {'model': 'fixture', 'input': 'Run source', 'max_output_tokens': 1024,
'reasoning': {'effort': effort}, 'stream': stream,
'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]}
code, data = request('/v1/responses', payload)
assert code == 200, (code, data)
if stream:
events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')]
assert [e['sequence_number'] for e in events] == list(range(len(events)))
assert events[-1]['type'] == 'response.completed'
assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source
assert next(e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done') == source
assert not any('function_call_arguments' in e['type'] for e in events)
result = events[-1]['response']
else:
result = json.loads(data)
call = result['output'][-1]
assert call['type'] == 'custom_tool_call' and call['input'] == source
assert call['name'] == 'run' and 'arguments' not in call
publish((root / 'answer').read_text())
code, data = request('/v1/responses', {'model': 'fixture', 'reasoning': {'effort': 'none'},
'previous_response_id': result['id'], 'input': [
{'type': 'custom_tool_call_output', 'call_id': call['call_id'], 'output': 'done'}]})
assert code == 200 and json.loads(data)['output'][0]['content'][0]['text'] == 'OK'
regex = r'\n print\("Привіт 🌍"\)\n'
for namespaced in [False, True]:
for effort in ['none', 'low']:
for stream in [False, True]:
for valid in [True, False]:
tool = {'type': 'custom', 'name': 'run', 'format': {
'type': 'grammar', 'syntax': 'regex', 'definition': regex if valid else 'NEVER_MATCH'}}
tools = [{'type': 'namespace', 'name': 'code', 'tools': [tool]}] if namespaced else [tool]
name = 'ns_' + hashlib.sha256(b'code/run').hexdigest()[:24] if namespaced else 'run'
output = markup.replace('<function=run>', f'<function={name}>')
if effort == 'low':
output = 'Think.</think>\n\n' + output
data = output.encode()
publish(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n')
payload = {'model': 'fixture', 'input': 'Run source', 'max_output_tokens': 1024,
'reasoning': {'effort': effort}, 'stream': stream, 'tools': tools}
code, data = request('/v1/responses', payload)
if stream:
assert code == 200, (code, data)
events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')]
assert [e['sequence_number'] for e in events] == list(range(len(events)))
assert events[-1]['type'] == ('response.completed' if valid else 'response.failed')
if not valid:
assert not any('custom_tool_call_input' in e['type'] for e in events)
assert not any(e.get('item', {}).get('type') == 'custom_tool_call' for e in events)
continue
assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source
result = events[-1]['response']
else:
if not valid:
assert code == 502, (code, data)
assert 'output' not in json.loads(data)
continue
assert code == 200, (code, data)
result = json.loads(data)
call = result['output'][-1]
assert call['type'] == 'custom_tool_call' and call['input'] == source
assert call['name'] == 'run' and 'arguments' not in call
assert call.get('namespace') == ('code' if namespaced else None)
saved_id, saved_call = result['id'], call['call_id']
publish((root / 'answer').read_text())
code, data = request('/v1/responses', {'model': 'fixture', 'reasoning': {'effort': 'none'},
'previous_response_id': saved_id, 'input': [
{'type': 'custom_tool_call_output', 'call_id': saved_call, 'output': 'done'}]})
assert code == 200 and json.loads(data)['output'][0]['content'][0]['text'] == 'OK'
payload['tools'] = [{'type': 'custom', 'name': 'run'}]
payload['tools'][0]['format'] = {'type': 'grammar', 'syntax': 'lark', 'definition': 'start: WORD'}
assert request('/v1/responses', payload)[0] == 400
for definition in ['[', '(?=a)', 'a*?', '(?x:a)', 'a\nb', 'a' * 8193]:
payload['tools'][0]['format'] = {'type': 'grammar', 'syntax': 'regex', 'definition': definition}
assert request('/v1/responses', payload)[0] == 400
assert json.loads(request('/metrics')[1])['generation']['started'] == 22
finally:
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
print('Custom text/regex tools passed: 22 generations, JSON/SSE, reasoning, namespace, exact input, no invalid call publication, continuation, invalid grammar rejection; CPU only')
if __name__ == '__main__':
main()