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>
214 lines
11 KiB
Python
214 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Actual isolated native HTTP replay plus independent corrupted-evidence tests."""
|
|
import copy
|
|
import http.client
|
|
import http.server
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
|
|
|
|
def load(name, filename):
|
|
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename))
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def main():
|
|
replay = load('replay', 'replay-live-responses.py')
|
|
fixture = load('fixture', 'smoke-worker-cancel.py')
|
|
binary = str(Path(sys.argv[1]).resolve())
|
|
script = Path(__file__).with_name('replay-live-responses.py')
|
|
with tempfile.TemporaryDirectory(prefix='strata-live-replay-') as directory:
|
|
root = Path(directory)
|
|
fixture.tokenizer(root)
|
|
key = 'fixture-private-key-not-in-captures-0001'
|
|
(root / 'key').write_text(key)
|
|
(root / 'key').chmod(0o600)
|
|
tool = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
|
|
for name, text in [('one', tool), ('two', 'CONFIRMED-731')]:
|
|
data = text.encode()
|
|
(root / name).write_text(''.join(f'T {b}\n' for b in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n')
|
|
engine = root / 'engine.sh'
|
|
engine.write_text('''#!/bin/sh
|
|
printf 'READY 262144 stop\\n'
|
|
n=0
|
|
while IFS= read -r line; do
|
|
case "$line" in
|
|
'GEN '*) n=$((n+1)); printf x >> "$2/generations"
|
|
if [ $((n % 2)) = 1 ]; then cat "$2/one"; else cat "$2/two"; fi ;;
|
|
QUIT) exit 0 ;;
|
|
esac
|
|
done
|
|
''')
|
|
engine.chmod(0o700)
|
|
with socket.socket() as probe:
|
|
probe.bind(('127.0.0.1', 0))
|
|
port = probe.getsockname()[1]
|
|
origin = f'http://127.0.0.1:{port}'
|
|
env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}',
|
|
'STRATA_MODEL_ID': 'fixture', 'STRATA_API_KEY_FILE': str(root / 'key'),
|
|
'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
|
|
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'}
|
|
function = {'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object',
|
|
'properties': {'key': {'type': 'string'}}, 'required': ['key'], 'additionalProperties': False}}
|
|
base = {'model': 'fixture', 'max_output_tokens': 1024, 'reasoning': {'effort': 'none'}, 'tools': [function]}
|
|
episode = {'schema': 1, 'sanitized': True, 'provenance': {'class': 'synthetic CPU worker'}, 'steps': [
|
|
{'request': {**base, 'input': 'Use lookup', 'tool_choice': {'type': 'function', 'name': 'lookup'}},
|
|
'expect': [{'type': 'function_call', 'name': 'lookup', 'arguments': {'key': 'value'}}]},
|
|
{'request': {**base, 'input': 'Confirm the tool result', 'tool_choice': 'none'},
|
|
'tool_results': ['CONFIRMED-731'], 'expect': [{'type': 'text', 'text': 'CONFIRMED-731'}]}]}
|
|
suite = root / 'episode.json'
|
|
suite.write_text(json.dumps(episode))
|
|
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() + 10
|
|
while True:
|
|
try:
|
|
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=.5)
|
|
conn.request('GET', '/ready', headers={'Authorization': 'Bearer ' + key})
|
|
ready = conn.getresponse().status == 200
|
|
conn.close()
|
|
if ready:
|
|
break
|
|
except OSError:
|
|
pass
|
|
if process.poll() is not None or time.monotonic() >= deadline:
|
|
logs.seek(0)
|
|
raise AssertionError(logs.read().decode())
|
|
time.sleep(.02)
|
|
out = root / 'evidence'
|
|
command = [sys.executable, str(script), '--endpoint', origin, '--fixture', str(suite),
|
|
'--output', str(out), '--key-file', str(root / 'key'), '--timeout', '8']
|
|
result = subprocess.run(command, capture_output=True, text=True, timeout=45)
|
|
assert result.returncode == 0, (result.stderr, (out / 'report.json').read_text() if out.exists() else '')
|
|
report = json.loads((out / 'report.json').read_text())
|
|
assert report['protocol_passed'] and len(report['arms']) == 2
|
|
assert (root / 'generations').read_bytes() == b'xxxx'
|
|
for path in out.iterdir():
|
|
assert path.stat().st_mode & 0o777 == 0o600
|
|
assert key not in path.read_text()
|
|
assert out.stat().st_mode & 0o777 == 0o700
|
|
continuation = json.loads((out / 'sse-001-request.json').read_text())['input']
|
|
call = next(x for x in continuation if x.get('type') == 'function_call')
|
|
result_item = next(x for x in continuation if x.get('type') == 'function_call_output')
|
|
assert call['call_id'] == result_item['call_id'] and result_item['output'] == 'CONFIRMED-731'
|
|
assert subprocess.run(command, capture_output=True, timeout=10).returncode != 0
|
|
assert (root / 'generations').read_bytes() == b'xxxx'
|
|
cases = 0
|
|
for filename in ['sse-000-body.txt', 'sse-001-body.txt']:
|
|
body = (out / filename).read_text()
|
|
replay.verify_sse(body)
|
|
with_comments = ': keep-alive\n\n' + body.replace('\n\n', '\n\n: keep-alive\n\n')
|
|
assert replay.verify_sse(with_comments) == replay.verify_sse(body)
|
|
events = [json.loads(line[5:]) for line in body.splitlines() if line.startswith('data:')]
|
|
|
|
def reject(changed):
|
|
nonlocal cases
|
|
for i, e in enumerate(changed):
|
|
e['sequence_number'] = i
|
|
wire = ''.join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in changed)
|
|
try:
|
|
replay.verify_sse(wire)
|
|
except (replay.Invalid, KeyError, TypeError, IndexError, ValueError):
|
|
cases += 1
|
|
else:
|
|
raise AssertionError('corrupt stream passed')
|
|
|
|
reject(copy.deepcopy(events[:-1]))
|
|
reject(copy.deepcopy(events + events[-1:]))
|
|
reject(copy.deepcopy(events[:2] + events[1:]))
|
|
reject([copy.deepcopy(e) for e in events if e['type'] != 'response.output_item.done'])
|
|
reject([copy.deepcopy(e) for e in events if not e['type'].endswith('_arguments.done') and e['type'] != 'response.output_text.done'])
|
|
bad = copy.deepcopy(events)
|
|
next(e for e in bad if e['type'].endswith('.delta'))['delta'] += 'tampered'
|
|
reject(bad)
|
|
bad = copy.deepcopy(events)
|
|
next(e for e in bad if e['type'] == 'response.output_item.added')['item']['id'] = 'wrong'
|
|
reject(bad)
|
|
bad = copy.deepcopy(events)
|
|
bad[-1]['response']['usage']['total_tokens'] += 1
|
|
reject(bad)
|
|
bad = copy.deepcopy(events)
|
|
bad[-1]['response']['status'] = 'failed'
|
|
reject(bad)
|
|
if filename == 'sse-000-body.txt':
|
|
bad = copy.deepcopy(events)
|
|
next(e for e in bad if e['type'] == 'response.output_item.added')['item']['arguments'] = 'unverified'
|
|
reject(bad)
|
|
bad = copy.deepcopy(events)
|
|
bad[-1]['response']['output'][0]['arguments'] = 'not JSON'
|
|
reject(bad)
|
|
bad = copy.deepcopy(events)
|
|
next(e for e in bad if e['type'] == 'response.output_item.added')['item']['name'] = 'other_tool'
|
|
reject(bad)
|
|
command[command.index('--output') + 1] = str(root / 'unauthorized')
|
|
at = command.index('--key-file')
|
|
del command[at:at + 2]
|
|
assert subprocess.run(command, capture_output=True, timeout=10).returncode != 0
|
|
assert (root / 'generations').read_bytes() == b'xxxx'
|
|
assert not json.loads((root / 'unauthorized/report.json').read_text())['protocol_passed']
|
|
finally:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=8)
|
|
except subprocess.TimeoutExpired:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
process.wait()
|
|
class Drip(http.server.BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
try:
|
|
if self.path in ('/large', '/secret'):
|
|
body = b'x' * (replay.LIMIT + 1) if self.path == '/large' else key.encode()
|
|
self.send_response(200)
|
|
self.send_header('Content-Length', str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
for _ in range(100):
|
|
self.wfile.write(b'H')
|
|
self.wfile.flush()
|
|
time.sleep(.05)
|
|
except OSError:
|
|
pass
|
|
def log_message(self, *_):
|
|
pass
|
|
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Drip)
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
thread.start()
|
|
try:
|
|
for path in ('/large', '/secret'):
|
|
try:
|
|
replay.exchange(f'http://127.0.0.1:{server.server_port}', key, path, None, 5)
|
|
except replay.Invalid:
|
|
pass
|
|
else:
|
|
raise AssertionError('oversize body or credential reflection passed')
|
|
started = time.monotonic()
|
|
try:
|
|
replay.exchange(f'http://127.0.0.1:{server.server_port}', '', '/ready', None, .4)
|
|
except replay.Invalid:
|
|
assert time.monotonic() - started < 2
|
|
else:
|
|
raise AssertionError('drip-fed headers escaped wall deadline')
|
|
finally:
|
|
server.shutdown()
|
|
server.server_close()
|
|
thread.join()
|
|
print(f'Live Responses replay: actual native CPU tool continuation in JSON/SSE, {cases} corrupt streams, private evidence, auth, no-overwrite and wall deadline passed')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|