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

237 lines
14 KiB
Python

#!/usr/bin/env python3
"""CPU HTTP tool-choice and single-call policy acceptance."""
import copy
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': 'custom', 'name': 'patch', 'format': {'type': 'text'}},
{'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]},
]
alias = 'ns_' + hashlib.sha256(b'code/run').hexdigest()[:24]
source = "print('Привіт 🌍')\n # exact spacing"
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>'
patch_call = custom_call.replace(alias, 'patch')
forced_custom = {'type': 'custom', 'name': 'patch'}
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.extend([
(forced_custom, True, patch_call, 1, True),
(forced_custom, False, patch_call, 1, True),
(forced_custom, True, function_call, 1, False),
(forced_custom, True, custom_call, 1, False),
(forced_custom, True, patch_call + '\n' + patch_call, 2, False),
(forced_custom, True, patch_call + '\n' + function_call, 2, False),
(forced_custom, True, 'OK', 0, False),
])
cases = [(*case, 'stop') for case in cases]
cases.extend((choice, True, 'OK', 0, True, 'length') for choice in ['required', forced, forced_custom])
cases.extend([
(forced_custom, True, patch_call, 1, True, 'length'),
(forced_custom, True, function_call, 1, False, 'length'),
(forced_custom, True, patch_call + '\n' + patch_call, 2, False, 'length'),
])
cases = [(*case, False) for case in cases]
cases.extend([
(forced_custom, True, patch_call, 1, True, 'stop', True),
(forced_custom, True, patch_call.replace(source, 'FORBIDDEN'), 1, False, 'stop', True),
])
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, regex 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
expected_tools = copy.deepcopy(tools)
if regex:
expected_tools[1]['format'] = {'type': 'grammar', 'syntax': 'regex',
'definition': r"print\('Привіт 🌍'\)\n # exact spacing"}
payload['tools'] = expected_tools
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 = int(effort == 'none' and (
(choice == forced_custom and output.startswith(patch_call)) or
(choice not in ('none', forced_custom) and output.startswith(function_call))))
assert len(published) == allowed, body
inputs = [e for e in events if 'custom_tool_call_input' in e['type']]
if choice == forced_custom and allowed:
assert published[0]['name'] == 'patch'
assert ''.join(e['delta'] for e in inputs if e['type'].endswith('.delta')) == source
assert [e['input'] for e in inputs if e['type'].endswith('.done')] == [source]
else:
assert not inputs, 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'] == expected_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
if choice == forced_custom:
assert call['name'] == 'patch' and 'namespace' not in call
if stream:
assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source
assert [e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done'] == [source]
assert [i['call_id'] for i in published] == [call['call_id']]
else:
assert 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'}]},
{'tool_choice': {'type': 'custom'}},
{'tool_choice': {'type': 'custom', 'name': 'missing'}},
{'tool_choice': {'type': 'custom', 'name': alias}},
{'tool_choice': {'type': 'custom', 'name': 'run'}},
{'tool_choice': {'type': 'custom', 'name': 1}},
{'tool_choice': {'type': 'custom', 'name': 'lookup'}},
{'tool_choice': {**forced_custom, 'namespace': 'code'}},
]:
assert request('/v1/responses', {**payload, **invalid})[0] == 400, invalid
for unsupported in [{'type': 'allowed_tools', 'mode': 'auto', 'tools': []}]:
payload['tool_choice'] = unsupported
assert request('/v1/responses', payload)[0] == 501
assert json.loads(request('/metrics')[1])['generation']['started'] == total == 136
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: 136 CPU HTTP cases passed; auto/none/required/forced, single-call, incomplete, mixed tools, reasoning, JSON/SSE, 15 malformed choices, metadata and exact accepted input')
if __name__ == '__main__':
main()