#!/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 = '\n\n\nvalue\n\n\n' custom_call = f'\n\n\n{source}\n\n\n' 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), ]) # Expected visible prefix counts are fixture expectations, independent # of the server's subset validation. Reasoning buffers calls until DONE. cases = [(*case, None) for case in cases] allow_function = {'type': 'allowed_tools', 'mode': 'auto', 'tools': [forced]} allow_custom = {'type': 'allowed_tools', 'mode': 'required', 'tools': [forced_custom]} allow_both = {'type': 'allowed_tools', 'mode': 'auto', 'tools': [forced, forced_custom]} allow_empty = {'type': 'allowed_tools', 'mode': 'auto', 'tools': []} cases.extend([ (allow_function, True, 'OK', 0, True, 'stop', False, 0), (allow_function, True, function_call, 1, True, 'stop', False, 1), (allow_function, True, patch_call, 1, False, 'stop', False, 0), (allow_function, True, custom_call, 1, False, 'stop', False, 0), (allow_function, True, function_call + '\n' + patch_call, 2, False, 'stop', False, 1), (allow_function, True, patch_call + '\n' + function_call, 2, False, 'stop', False, 0), (allow_custom, True, 'OK', 0, False, 'stop', False, 0), (allow_custom, True, patch_call, 1, True, 'stop', True, 1), (allow_custom, True, function_call, 1, False, 'stop', False, 0), (allow_custom, True, patch_call + '\n' + patch_call, 2, True, 'stop', False, 2), (allow_custom, False, patch_call + '\n' + patch_call, 2, False, 'stop', False, 1), (allow_custom, True, 'OK', 0, True, 'length', False, 0), (allow_custom, True, function_call, 1, False, 'length', False, 0), (allow_custom, True, patch_call + '\n' + function_call, 2, False, 'length', False, 1), (allow_both, True, function_call + '\n' + patch_call, 2, True, 'stop', False, 2), (allow_both, True, both, 2, False, 'stop', False, 1), (allow_empty, True, 'OK', 0, True, 'stop', False, 0), (allow_empty, True, function_call, 1, False, 'stop', False, 0), (allow_empty, True, custom_call, 1, False, 'stop', False, 0), (allow_empty, True, 'OK', 0, True, 'length', False, 0), ]) 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() + 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, expected_prefix in cases: data = (('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')] published_ids = {item['id'] for item in published} for event in events: if 'function_call_arguments' in event['type'] or 'custom_tool_call_input' in event['type']: assert event['item_id'] in published_ids, body 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)))) if expected_prefix is not None: allowed = expected_prefix if effort == 'none' else 0 assert len(published) == allowed, body inputs = [e for e in events if 'custom_tool_call_input' in e['type']] if allowed and published[0]['type'] == 'custom_tool_call': 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 if stream: custom_count = sum(call['type'] == 'custom_tool_call' for call in calls) assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source * custom_count assert [e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done'] == [source] * custom_count assert [i['call_id'] for i in published] == [call['call_id'] for call in calls] for call in calls: if call['type'] == 'custom_tool_call': assert call['input'] == source if call['name'] == 'patch': assert 'namespace' not in call 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' invalid_choices = [ {'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'}}, ] for choice in [ {'type': 'allowed_tools'}, {**allow_function, 'mode': 'none'}, {**allow_function, 'mode': None}, {**allow_function, 'extra': True}, {**allow_function, 'tools': None}, {**allow_function, 'tools': {}}, {**allow_empty, 'mode': 'required'}, {**allow_function, 'tools': [forced, forced]}, {**allow_function, 'tools': [{'type': 'function', 'name': 'patch'}]}, {**allow_function, 'tools': [{'type': 'custom', 'name': 'lookup'}]}, {**allow_function, 'tools': [{'type': 'function', 'name': 'missing'}]}, {**allow_function, 'tools': [{'type': 'custom', 'name': alias}]}, {**allow_function, 'tools': [{'type': 'custom', 'name': 'run', 'namespace': 'code'}]}, {**allow_function, 'tools': [{'type': 'mcp', 'server_label': 'fixture'}]}, {**allow_function, 'tools': [{'type': 'function'}]}, {**allow_function, 'tools': [{'type': 'function', 'name': 1}]}, {**allow_function, 'tools': [None]}, {**allow_function, 'tools': [forced, {'type': 'function', 'name': 'missing'}]}, ]: invalid_choices.append({'tool_choice': choice}) for invalid in invalid_choices: assert request('/v1/responses', {**payload, **invalid})[0] == 400, invalid for unsupported in [{'type': 'unknown'}]: payload['tool_choice'] = unsupported assert request('/v1/responses', payload)[0] == 501 assert json.loads(request('/metrics')[1])['generation']['started'] == total == 216 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: 216 CPU HTTP cases passed; auto/none/required/forced/allowed_tools, single-call, incomplete, mixed tools, reasoning, JSON/SSE, 33 malformed choices, metadata and exact accepted input') if __name__ == '__main__': main()