fake_runtime is a leleka.runtime.v1 server (the real RuntimeServer) whose engine is the same engine.sh the smokes already use; fixture.runtime_stack() swaps strata-next's engine child for it when STRATA_TEST_FAKE_RUNTIME is set, otherwise nothing changes. scripts/test-api-over-runtime.py runs the ten smokes whose assertions do not depend on strata-next owning the engine process. The HTTP layer clamps reasoning_tokens to the engine-reported output total, which a text-level engine's re-tokenized pieces can otherwise exceed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
292 lines
18 KiB
Python
292 lines
18 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()
|
|
durable = "--durable" in sys.argv[2:]
|
|
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 '*) printf x >> "$2/generations"; 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'}
|
|
|
|
history_dir = root / 'private-history'
|
|
if durable:
|
|
env['STRATA_RESPONSE_HISTORY_DIR'] = str(history_dir)
|
|
|
|
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', 'response.failed'), 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
|
|
|
|
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
|
|
with tempfile.TemporaryFile() as logs:
|
|
def start():
|
|
proc = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs)
|
|
try:
|
|
deadline = time.monotonic() + 10
|
|
while True:
|
|
try:
|
|
if request('GET', '/ready')[0] == 200:
|
|
return proc
|
|
except OSError:
|
|
pass
|
|
assert proc.poll() is None and time.monotonic() < deadline
|
|
time.sleep(.02)
|
|
except BaseException:
|
|
proc.kill()
|
|
proc.wait(timeout=5)
|
|
raise
|
|
|
|
def restart():
|
|
nonlocal process
|
|
process.terminate()
|
|
assert process.wait(timeout=10) == 0
|
|
process = start()
|
|
|
|
if durable:
|
|
checked = subprocess.run([binary, 'check-config'], env=env, capture_output=True, timeout=5)
|
|
assert checked.returncode == 0 and json.loads(checked.stdout)['response_history'] == 'durable_unchecked'
|
|
assert not history_dir.exists()
|
|
process = start()
|
|
try:
|
|
if durable:
|
|
assert history_dir.stat().st_mode & 0o777 == 0o700
|
|
duplicate = subprocess.run([binary, 'serve'], env=env, stdout=logs, stderr=logs, timeout=5)
|
|
assert duplicate.returncode != 0
|
|
assert request('GET', '/ready')[0] == 200
|
|
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']
|
|
if durable:
|
|
restart()
|
|
assert request('GET', path, auth=False)[0] == 401
|
|
assert request('DELETE', path, auth=False)[0] == 401
|
|
assert request('GET', path + '/input_items', auth=False)[0] == 401
|
|
if not store:
|
|
assert request('GET', path + '/input_items')[0] == 404
|
|
assert request('GET', path)[0] == request('DELETE', path)[0] == 404
|
|
continue
|
|
assert request('GET', path) == (200, result)
|
|
generations = (root / 'generations').read_bytes()
|
|
code, page = request('GET', path + '/input_items')
|
|
assert code == 200 and page['object'] == 'list' and not page['has_more'], page
|
|
assert len(page['data']) == 1 and page['first_id'] == page['last_id']
|
|
assert page['data'][0]['content'] == [{'type': 'input_text', 'text': 'Respond'}]
|
|
assert request('GET', path + '/input_items') == (code, page)
|
|
assert (root / 'generations').read_bytes() == generations
|
|
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})
|
|
if durable:
|
|
restart()
|
|
assert request('GET', path)[0] == request('DELETE', path)[0] == 404
|
|
assert request('GET', path + '/input_items')[0] == 404
|
|
parent = generate('A')
|
|
if durable:
|
|
restart()
|
|
child = generate('A', {'previous_response_id': parent['id']})
|
|
child_path = '/v1/responses/' + child['id'] + '/input_items'
|
|
code, child_page = request('GET', child_path + '?order=asc')
|
|
assert code == 200 and len(child_page['data']) == 3, child_page
|
|
assert [item['role'] for item in child_page['data']] == ['user', 'assistant', 'user']
|
|
assert child_page['data'][1]['content'] == parent['output'][0]['content']
|
|
assert request('DELETE', '/v1/responses/' + parent['id'])[0] == 200
|
|
assert request('GET', child_path + '?order=asc') == (200, child_page)
|
|
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)
|
|
for stream in (False, True):
|
|
messages = [{'role': 'user', 'id': 'repeated-client-id', 'content': f'Input {i}'} for i in range(25)]
|
|
response = generate('A', {'input': messages, 'stream': stream})
|
|
path = '/v1/responses/' + response['id'] + '/input_items'
|
|
generations = (root / 'generations').read_bytes()
|
|
code, first = request('GET', path)
|
|
assert code == 200 and len(first['data']) == 20 and first['has_more']
|
|
assert first['data'][0]['content'][0]['text'] == 'Input 24'
|
|
code, second = request('GET', path + '?after=' + first['last_id'])
|
|
assert code == 200 and len(second['data']) == 5 and not second['has_more']
|
|
desc = first['data'] + second['data']
|
|
assert len({item['id'] for item in desc}) == 25
|
|
code, asc = request('GET', path + '?order=asc&limit=100')
|
|
assert code == 200 and asc['data'] == list(reversed(desc)) and not asc['has_more']
|
|
code, empty = request('GET', path + '?order=asc&after=' + asc['last_id'])
|
|
assert code == 200 and empty == {'object': 'list', 'data': [], 'first_id': None, 'last_id': None, 'has_more': False}
|
|
for query in ['limit=0', 'limit=101', 'limit=no', 'limit=1&limit=2', 'order=bad',
|
|
'order=asc&order=desc', 'after=', 'after=a&after=b', 'after=missing',
|
|
'after=' + child_page['first_id'], 'include=reasoning.encrypted_content', 'stream=true']:
|
|
code, error = request('GET', path + '?' + query)
|
|
assert code == 400 and error['error']['code'] == 'invalid_input_items_query', error
|
|
assert (root / 'generations').read_bytes() == generations
|
|
|
|
typed = generate('A', {'stream': stream, 'input': [
|
|
{'role': 'assistant', 'content': [{'type': 'input_text', 'text': 'Prior answer'}]},
|
|
{'role': 'user', 'content': [{'type': 'output_text', 'text': 'Continue'}]}]})
|
|
code, typed_page = request('GET', '/v1/responses/' + typed['id'] + '/input_items?order=asc')
|
|
assert code == 200
|
|
assert typed_page['data'][0]['content'] == [{'type': 'output_text', 'text': 'Prior answer', 'annotations': []}]
|
|
assert typed_page['data'][1]['content'] == [{'type': 'input_text', 'text': 'Continue'}]
|
|
|
|
history_input = [
|
|
{'role': 'user', 'content': 'Use tools'},
|
|
{'type': 'function_call', 'call_id': 'call_fn', 'namespace': 'files', 'name': 'lookup', 'arguments': '{"x": 1}'},
|
|
{'type': 'function_call_output', 'call_id': 'call_fn', 'output': 'result'},
|
|
{'type': 'custom_tool_call', 'call_id': 'call_custom', 'namespace': 'files', 'name': 'run', 'input': 'line1\nline2'},
|
|
{'type': 'custom_tool_call_output', 'call_id': 'call_custom', 'output': 'done'}]
|
|
tools = [{'type': 'namespace', 'name': 'files', 'tools': [
|
|
{'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'x': {'type': 'integer'}}}},
|
|
{'type': 'custom', 'name': 'run'}]}]
|
|
response = generate('A', {'input': history_input, 'tools': tools, 'stream': stream})
|
|
if durable:
|
|
restart()
|
|
path = '/v1/responses/' + response['id'] + '/input_items?order=asc'
|
|
code, page = request('GET', path)
|
|
assert code == 200 and len(page['data']) == 5, page
|
|
for original, projected in zip(history_input[1:], page['data'][1:]):
|
|
assert {k: v for k, v in projected.items() if k != 'id'} == original
|
|
# Returned items remain usable for stateless continuation.
|
|
assert generate('A', {'input': page['data'], 'tools': tools, 'stream': stream})['status'] == 'completed'
|
|
if durable:
|
|
snapshot = history_dir / 'history-v1.json'
|
|
assert snapshot.stat().st_mode & 0o777 == 0o600
|
|
for stream in (False, True):
|
|
committed = snapshot.read_bytes()
|
|
stage = history_dir / 'history-v1.pending'
|
|
stage.mkdir()
|
|
code, error = request('POST', '/v1/responses', {
|
|
'model': 'fixture', 'input': 'storage-fault',
|
|
'reasoning': {'effort': 'none'}, 'stream': stream})
|
|
if stream:
|
|
assert code == 200 and error['status'] == 'failed', error
|
|
assert request('GET', '/v1/responses/' + error['id'])[0] == 404
|
|
else:
|
|
assert code == 507 and error['error']['code'] == 'response_storage_failed', error
|
|
assert snapshot.read_bytes() == committed
|
|
assert request('GET', '/v1/responses/' + child['id']) == (200, child)
|
|
assert request('DELETE', '/v1/responses/' + child['id'])[0] == 507
|
|
stage.rmdir()
|
|
restart()
|
|
assert request('GET', '/v1/responses/' + child['id']) == (200, child)
|
|
# A hard control-plane kill restores the latest acknowledged commit.
|
|
process.kill()
|
|
process.wait(timeout=5)
|
|
process = start()
|
|
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('GET', child_path + '?order=asc') == (200, child_page)
|
|
assert request('DELETE', '/v1/responses/' + child['id'])[0] == 200
|
|
assert request('GET', child_path)[0] == 404
|
|
assert request('GET', '/v1/responses/missing')[0] == 404
|
|
process.terminate()
|
|
assert process.wait(timeout=10) == 0
|
|
if durable:
|
|
# Corruption fails before any new worker spawn, retaining the file.
|
|
snapshot = history_dir / 'history-v1.json'
|
|
worker_identity = (root / 'worker.pid').read_bytes()
|
|
original = snapshot.read_bytes()
|
|
snapshot.write_bytes(b'{broken-private-fixture')
|
|
failed = subprocess.run([binary, 'serve'], env=env, capture_output=True, timeout=5)
|
|
assert failed.returncode != 0
|
|
assert b'broken-private-fixture' not in failed.stderr
|
|
assert (root / 'worker.pid').read_bytes() == worker_identity
|
|
assert snapshot.read_bytes() == b'{broken-private-fixture'
|
|
snapshot.write_bytes(original)
|
|
process = start()
|
|
assert request('GET', '/v1/responses/' + child['id'])[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(('Durable restart/fault mode: ' if durable else '') + 'Response resources: 28 original variants plus input-items pagination, exact tool replay, auth/deletion/outage and no extra generation passed')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|