Files
leleka/scripts/smoke-tool-policy.py
T

186 lines
10 KiB
Python

#!/usr/bin/env python3
"""CPU HTTP tool-choice and single-call policy acceptance."""
import hashlib
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-tool-policy-') as directory:
root = Path(directory)
fixture.tokenizer(root)
engine = root / 'engine.sh'
engine.write_text('''#!/bin/sh
printf 'READY 262144 stop\\n'
while IFS= read -r line; do
case "$line" in
'GEN '*) 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, payload=None):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
try:
connection.request('POST' if payload is not None else 'GET', path,
json.dumps(payload) if payload is not None else None,
{'Content-Type': 'application/json'})
response = connection.getresponse()
return response.status, response.read().decode()
finally:
connection.close()
tools = [
{'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object',
'properties': {'key': {'type': 'string'}}, 'required': ['key'], 'additionalProperties': False}},
{'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]},
]
alias = 'ns_' + hashlib.sha256(b'code/run').hexdigest()[:24]
source = "print('Привіт 🌍')"
function_call = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
custom_call = f'<tool_call>\n<function={alias}>\n<parameter=input>\n{source}\n</parameter>\n</function>\n</tool_call>'
both = function_call + '\n' + custom_call
cases = [
('auto', True, both, 2, True),
(None, None, both, 2, True),
('auto', False, 'OK', 0, True),
('auto', False, function_call, 1, True),
('auto', False, custom_call, 1, True),
('auto', False, both, 2, False),
('none', True, 'OK', 0, True),
('none', True, custom_call, 1, False),
('none', False, both, 2, False),
]
forced = {'type': 'function', 'name': 'lookup'}
cases.extend([
('required', True, 'OK', 0, False),
('required', True, function_call, 1, True),
('required', True, custom_call, 1, True),
('required', True, both, 2, True),
('required', False, both, 2, False),
(forced, True, function_call, 1, True),
(forced, True, custom_call, 1, False),
(forced, True, both, 2, False),
(forced, True, function_call + '\n' + function_call, 2, False),
(forced, True, 'OK', 0, False),
])
cases = [(*case, 'stop') for case in cases]
cases.extend((choice, True, 'OK', 0, True, 'length') for choice in ['required', forced])
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.01)
total = 0
for effort in ['none', 'low']:
for stream in [False, True]:
for choice, parallel, output, count, valid, reason in cases:
data = (('Think.</think>\n\n' if effort == 'low' else '') + output).encode()
# An early failed SSE response can precede the worker's
# final read/EOF. Never truncate the inode cat is reading:
# doing so can splice the next case into this generation.
staged = root / 'next.new'
staged.write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 {reason}\n')
staged.replace(root / 'next')
payload = {'model': 'fixture', 'input': 'Use policy', 'max_output_tokens': 1024,
'reasoning': {'effort': effort}, 'stream': stream, 'tools': tools,
'metadata': {'fixture': 'policy'}}
if choice is not None:
payload['tool_choice'] = choice
if parallel is not None:
payload['parallel_tool_calls'] = parallel
code, body = request('/v1/responses', payload)
total += 1
if stream:
assert code == 200, (code, body)
events = [json.loads(line[5:]) for line in body.splitlines() if line.startswith('data:')]
assert [e['sequence_number'] for e in events] == list(range(len(events)))
assert events[-1]['type'] == (('response.incomplete' if reason == 'length' else 'response.completed') if valid else 'response.failed'), body
published = [e['item'] for e in events if e['type'] == 'response.output_item.added'
and e['item']['type'] in ('function_call', 'custom_tool_call')]
if not valid:
allowed = 1 if choice != 'none' and effort == 'none' and output.startswith(function_call) else 0
assert len(published) == allowed, body
assert not any('custom_tool_call_input' in e['type'] for e in events), body
continue
assert len(published) == count
result = events[-1]['response']
else:
if not valid:
assert code == 502 and 'output' not in json.loads(body), (code, body)
continue
assert code == 200, (code, body)
result = json.loads(body)
assert result['status'] == ('incomplete' if reason == 'length' else 'completed')
assert result['tool_choice'] == (choice or 'auto')
assert result['parallel_tool_calls'] == (parallel if parallel is not None else True)
assert result['tools'] == tools and result['metadata'] == {'fixture': 'policy'}
calls = [item for item in result['output'] if item['type'] in ('function_call', 'custom_tool_call')]
assert len(calls) == count
for call in calls:
if call['type'] == 'custom_tool_call':
assert call['input'] == source and call['name'] == 'run' and call['namespace'] == 'code'
else:
assert json.loads(call['arguments']) == {'key': 'value'}
if count == 0:
assert result['output'][-1]['content'][0]['text'] == 'OK'
for invalid in [
{'tool_choice': 'required', 'tools': []},
{'tool_choice': 'required', 'tools': [{'type': 'namespace', 'name': 'empty', 'tools': []}]},
{'tool_choice': {'type': 'function'}},
{'tool_choice': {'type': 'function', 'name': 'missing'}},
{'tool_choice': {'type': 'function', 'name': alias}},
{'tool_choice': {'type': 'function', 'name': 1}},
{'tool_choice': {**forced, 'namespace': 'code'}},
{'tool_choice': forced, 'tools': [{'type': 'custom', 'name': 'lookup'}]},
]:
assert request('/v1/responses', {**payload, **invalid})[0] == 400, invalid
for unsupported in [{'type': 'allowed_tools', 'mode': 'auto', 'tools': []}, {'type': 'custom', 'name': 'run'}]:
payload['tool_choice'] = unsupported
assert request('/v1/responses', payload)[0] == 501
assert json.loads(request('/metrics')[1])['generation']['started'] == total == 84
except Exception:
logs.seek(0)
print('Synthetic tool-policy worker log:', logs.read().decode(errors='replace'), file=sys.stderr)
raise
finally:
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
print('Tool policy: 84 CPU HTTP cases passed; auto/none/required/forced, single-call, incomplete, mixed tools, reasoning, JSON/SSE, 8 malformed choices, metadata and exact accepted input')
if __name__ == '__main__':
main()