Files
leleka/scripts/smoke-response-history.py
T

147 lines
7.5 KiB
Python

#!/usr/bin/env python3
"""CPU HTTP response resource lifecycle, exact terminal JSON and auth gates."""
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)
key = 'fixture-only-response-resource-key-0001'
with tempfile.TemporaryDirectory(prefix='strata-response-history-') as directory:
root = Path(directory)
fixture.tokenizer(root)
key_file = root / 'api.key'
key_file.write_text(key)
key_file.chmod(0o600)
engine = root / 'engine.sh'
engine.write_text('''#!/bin/sh
printf '%s' "$$" > "$2/worker.pid"
printf 'READY 262144 stop\n'
while IFS= read -r line; do
case "$line" in
'GEN '*) cat "$2/output" ;;
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(key_file),
'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(method, path, payload=None, auth=True):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
headers = {'Content-Type': 'application/json'}
if auth:
headers['Authorization'] = 'Bearer ' + key
try:
connection.request(method, path, json.dumps(payload) if payload is not None else None, headers)
response = connection.getresponse()
data = response.read().decode()
if response.getheader('Content-Type', '').startswith('text/event-stream'):
events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')]
assert events[-1]['type'] in ('response.completed', 'response.incomplete'), events[-1]
data = events[-1]['response']
else:
data = json.loads(data)
return response.status, data
finally:
connection.close()
def generate(text, options=None, finish='stop'):
data = text.encode()
staged = root / 'output.new'
staged.write_text(''.join(f'T {token}\n' for token in data) + f'DONE {len(data)} 7 1.0 2.0 {finish}\n')
staged.replace(root / 'output')
code, result = request('POST', '/v1/responses', {
'model': 'fixture', 'input': 'Respond', 'max_output_tokens': 1024,
'reasoning': {'effort': 'none'}, 'metadata': {'fixture': 'kept'}, **(options or {})})
assert code == 200, result
return result
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs)
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)
tool = '<tool_call>\n<function=run>\n<parameter=input>\nprint(1)\n</parameter>\n</function>\n</tool_call>'
function = '<tool_call>\n<function=lookup>\n<parameter=x>1</parameter>\n</function>\n</tool_call>'
cases = [('A', {}, 'stop'), ('Think.</think>\n\nA', {'reasoning': {'effort': 'low'}}, 'stop'),
('{"answer":"A"}', {'text': {'format': {'type': 'json_object'}}}, 'stop'),
(tool, {'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]}, 'stop'),
('Think.</think>\n\n' + tool, {'reasoning': {'effort': 'low'},
'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]}, 'stop'),
(function, {'tools': [{'type': 'function', 'name': 'lookup', 'parameters':
{'type': 'object', 'properties': {'x': {'type': 'integer'}}}}]}, 'stop'),
('A', {}, 'length')]
for text, options, finish in cases:
for stream in (False, True):
for store in (False, True):
result = generate(text, {**options, 'stream': stream, 'store': store}, finish)
path = '/v1/responses/' + result['id']
assert request('GET', path, auth=False)[0] == 401
assert request('DELETE', path, auth=False)[0] == 401
if not store:
assert request('GET', path)[0] == request('DELETE', path)[0] == 404
continue
assert request('GET', path) == (200, result)
assert request('GET', path + '?stream=true')[0] == 400
assert request('DELETE', path + '?unknown=1')[0] == 400
assert request('GET', path) == (200, result)
assert request('DELETE', path) == (200, {'id': result['id'], 'object': 'response.deleted', 'deleted': True})
assert request('GET', path)[0] == request('DELETE', path)[0] == 404
parent = generate('A')
child = generate('A', {'previous_response_id': parent['id']})
assert request('DELETE', '/v1/responses/' + parent['id'])[0] == 200
code, result = request('POST', '/v1/responses', {'model': 'fixture', 'input': 'again', 'previous_response_id': parent['id']})
assert code == 404 and result['error']['code'] == 'response_not_found'
assert request('GET', '/v1/responses/' + child['id']) == (200, child)
assert request('POST', '/admin/drain', {})[0] == 200
worker_pid = int((root / 'worker.pid').read_text())
os.kill(worker_pid, signal.SIGKILL)
deadline = time.monotonic() + 5
while request('GET', '/status')[1]['ready']:
assert time.monotonic() < deadline
time.sleep(.02)
assert request('GET', '/v1/responses/' + child['id']) == (200, child)
assert request('DELETE', '/v1/responses/' + child['id'])[0] == 200
assert request('GET', '/v1/responses/missing')[0] == 404
process.terminate()
assert process.wait(timeout=10) == 0
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
print('Response resources: 28 generation variants, exact retrieval, auth, deletion, continuation and drain/worker-outage access passed')
if __name__ == '__main__':
main()