Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
338 lines
19 KiB
Python
338 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Offline evaluator: explicit sanitized episodes, real HTTP, no tool execution.
|
|
|
|
Each HTTP exchange runs in a bounded child; even drip-fed headers cannot extend
|
|
the parent deadline. This is intentionally separate from production serving.
|
|
"""
|
|
import argparse
|
|
import copy
|
|
from datetime import datetime, timezone
|
|
import hashlib
|
|
import http.client
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from urllib.parse import urlsplit
|
|
|
|
LIMIT = 8 * 1024 * 1024
|
|
|
|
|
|
class Invalid(Exception):
|
|
pass
|
|
|
|
|
|
def require(condition, message):
|
|
if not condition:
|
|
raise Invalid(message)
|
|
|
|
|
|
def endpoint(value):
|
|
url = urlsplit(value)
|
|
require(url.scheme == 'http' and not url.username and not url.password
|
|
and url.path in ('', '/') and not url.query and not url.fragment
|
|
and url.port is not None, 'endpoint must be an explicit HTTP loopback origin with port')
|
|
require(ipaddress.ip_address(url.hostname).is_loopback, 'use a loopback endpoint or an SSH tunnel')
|
|
return url.hostname, url.port
|
|
|
|
|
|
def exchange_worker():
|
|
spec = json.loads(sys.stdin.buffer.read(LIMIT))
|
|
host, port = endpoint(spec['endpoint'])
|
|
connection = http.client.HTTPConnection(host, port, timeout=spec['timeout'])
|
|
try:
|
|
headers = {'Content-Type': 'application/json'}
|
|
if spec['key']:
|
|
headers['Authorization'] = 'Bearer ' + spec['key']
|
|
payload = spec['payload']
|
|
connection.request('POST' if payload is not None else 'GET', spec['path'],
|
|
None if payload is None else json.dumps(payload), headers)
|
|
response = connection.getresponse()
|
|
body = response.read(LIMIT + 1)
|
|
require(len(body) <= LIMIT, 'HTTP body limit exceeded')
|
|
print(json.dumps({'status': response.status, 'content_type': response.getheader('Content-Type', ''),
|
|
'body': body.decode('utf-8')}))
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def exchange(origin, key, path, payload, timeout):
|
|
started = time.monotonic()
|
|
spec = json.dumps(dict(endpoint=origin, key=key, path=path, payload=payload, timeout=timeout))
|
|
require(len(spec.encode()) < LIMIT, 'request limit exceeded')
|
|
try:
|
|
child = subprocess.run([sys.executable, __file__, '--exchange-worker'], input=spec,
|
|
capture_output=True, text=True, timeout=timeout)
|
|
except subprocess.TimeoutExpired:
|
|
raise Invalid('HTTP wall deadline exceeded') from None
|
|
require(child.returncode == 0, 'HTTP exchange failed') # Never echo credential-bearing diagnostics.
|
|
result = json.loads(child.stdout)
|
|
require(not key or key not in result['body'], 'credential found in response; capture refused')
|
|
result['wall_seconds'] = time.monotonic() - started
|
|
return result
|
|
|
|
|
|
def semantic(response):
|
|
require(response.get('object') == 'response' and isinstance(response.get('output'), list)
|
|
and response['output'], 'invalid response envelope')
|
|
require(response.get('status') == 'completed' and response.get('error') is None,
|
|
'response did not complete successfully')
|
|
require(isinstance(response.get('id'), str) and response['id'], 'missing response identity')
|
|
usage = response['usage']
|
|
for field in ('input_tokens', 'output_tokens', 'total_tokens'):
|
|
require(type(usage[field]) is int and usage[field] >= 0, 'invalid token usage')
|
|
require(usage['input_tokens'] + usage['output_tokens'] == usage['total_tokens'], 'inconsistent token usage')
|
|
result, ids, calls = [], set(), set()
|
|
for item in response['output']:
|
|
require(isinstance(item.get('id'), str) and item['id'] and item['id'] not in ids, 'duplicate or missing item identity')
|
|
ids.add(item['id'])
|
|
require(item.get('status') == 'completed', 'incomplete output item')
|
|
kind = item['type']
|
|
if kind == 'message':
|
|
require(item['role'] == 'assistant', 'unexpected message role')
|
|
require(all(p['type'] == 'output_text' for p in item['content']), 'unsupported message part')
|
|
result.append({'type': 'text', 'text': ''.join(p['text'] for p in item['content'])})
|
|
elif kind in ('function_call', 'custom_tool_call'):
|
|
require(isinstance(item.get('call_id'), str) and item['call_id'] and item['call_id'] not in calls,
|
|
'duplicate or missing call identity')
|
|
calls.add(item['call_id'])
|
|
field = 'arguments' if kind == 'function_call' else 'input'
|
|
value = json.loads(item[field]) if field == 'arguments' else item[field]
|
|
require(isinstance(value, dict if field == 'arguments' else str), 'invalid tool input')
|
|
out = {'type': kind, 'name': item['name'], field: value}
|
|
if 'namespace' in item:
|
|
out['namespace'] = item['namespace']
|
|
result.append(out)
|
|
elif kind == 'reasoning':
|
|
result.append({'type': kind, 'content': item.get('content', []), 'summary': item.get('summary', [])})
|
|
else:
|
|
raise Invalid('unsupported output item')
|
|
return result
|
|
|
|
|
|
def verify_sse(body):
|
|
# Native SSE uses named JSON events; refuse incomplete final frames and [DONE]
|
|
# aliases. Save raw evidence before validation so failures remain inspectable.
|
|
body = body.replace('\r\n', '\n')
|
|
require(body.endswith('\n\n'), 'truncated SSE frame')
|
|
events = []
|
|
for frame in body.split('\n\n'):
|
|
if not frame or all(line.startswith(':') for line in frame.splitlines()):
|
|
continue
|
|
names = [line[6:].strip() for line in frame.splitlines() if line.startswith('event:')]
|
|
data = '\n'.join(line[5:].lstrip(' ') for line in frame.splitlines() if line.startswith('data:'))
|
|
event = json.loads(data)
|
|
require(names == [event['type']], 'SSE event name mismatch')
|
|
require(type(event['sequence_number']) is int and event['sequence_number'] == len(events), 'noncontiguous SSE sequence')
|
|
events.append(event)
|
|
require(len(events) >= 3 and events[0]['type'] == 'response.created'
|
|
and events[1]['type'] == 'response.in_progress', 'missing SSE opening lifecycle')
|
|
require([e['type'] for e in events if e['type'] in ('response.created', 'response.in_progress')]
|
|
== ['response.created', 'response.in_progress'], 'repeated SSE opening lifecycle')
|
|
require(all(e['response']['status'] == 'in_progress' and e['response']['output'] == []
|
|
for e in events[:2]), 'invalid opening response state')
|
|
terminals = [e for e in events if e['type'] in ('response.completed', 'response.failed', 'response.incomplete')]
|
|
require(len(terminals) == 1 and terminals[0] is events[-1]
|
|
and terminals[0]['type'] == 'response.completed', 'missing, repeated or failed SSE terminal')
|
|
response = events[-1]['response']
|
|
semantic(response)
|
|
rid = response['id']
|
|
added, done, chunks, sealed, parts, part_done = {}, {}, {}, set(), {}, set()
|
|
families = {'response.output_text': 'text', 'response.reasoning_text': 'text',
|
|
'response.function_call_arguments': 'arguments', 'response.custom_tool_call_input': 'input'}
|
|
for event in events:
|
|
kind = event['type']
|
|
if kind in ('response.created', 'response.in_progress', 'response.completed'):
|
|
require(event['response']['id'] == rid, 'response identity changed')
|
|
continue
|
|
require(event.get('response_id') == rid, 'SSE response identity mismatch')
|
|
index = event['output_index']
|
|
require(type(index) is int and index >= 0, 'invalid SSE output index')
|
|
if kind == 'response.output_item.added':
|
|
require(index == len(added), 'invalid added output index')
|
|
pending = event['item']
|
|
require(pending.get('status') == 'in_progress', 'invalid pending item status')
|
|
field = {'function_call': 'arguments', 'custom_tool_call': 'input'}.get(pending['type'])
|
|
require(pending.get(field) == '' if field else pending.get('content', []) == [],
|
|
'pending item carries unverified content')
|
|
added[index] = event['item']
|
|
continue
|
|
require(index in added and index not in done, 'event outside open output item')
|
|
if kind == 'response.output_item.done':
|
|
require(event['item']['id'] == added[index]['id'], 'item identity changed')
|
|
for field in ('type', 'name', 'namespace', 'call_id', 'role'):
|
|
require(event['item'].get(field) == added[index].get(field), 'published item identity changed')
|
|
done[index] = event['item']
|
|
continue
|
|
require(event.get('item_id') == added[index]['id'], 'delta item identity mismatch')
|
|
if kind in ('response.content_part.added', 'response.content_part.done'):
|
|
key = (index, event['content_index'])
|
|
if kind.endswith('.added'):
|
|
require(key not in parts, 'duplicate content part')
|
|
require(event['part']['type'] == response['output'][index]['content'][key[1]]['type']
|
|
and event['part'].get('text') == '', 'invalid initial content part')
|
|
parts[key] = event['part']
|
|
else:
|
|
require(key in parts and key not in part_done, 'unexpected content part done')
|
|
part_done.add(key)
|
|
require(event['part'] == response['output'][index]['content'][key[1]], 'content part differs from terminal')
|
|
continue
|
|
family, suffix = kind.rsplit('.', 1)
|
|
require(family in families and suffix in ('delta', 'done'), 'unsupported SSE event')
|
|
field = families[family]
|
|
content_index = event.get('content_index')
|
|
key = (index, family, content_index)
|
|
require(key not in sealed, 'delta or done after field done')
|
|
if field == 'text':
|
|
require((index, content_index) in parts and (index, content_index) not in part_done,
|
|
'text outside content part')
|
|
if suffix == 'delta':
|
|
chunks[key] = chunks.get(key, '') + event['delta']
|
|
else:
|
|
require(chunks.get(key, '') == event[field], 'delta/done content mismatch')
|
|
final_item = response['output'][index]
|
|
expected = final_item['content'][content_index]['text'] if field == 'text' else final_item[field]
|
|
require(event[field] == expected, 'field differs from terminal')
|
|
sealed.add(key)
|
|
require(len(added) == len(done) == len(response['output']) and
|
|
[done[i] for i in range(len(done))] == response['output'], 'terminal output differs from item events')
|
|
require(set(chunks) <= sealed and set(parts) == part_done, 'unclosed streamed content')
|
|
for index, item in enumerate(response['output']):
|
|
if item['type'] in ('function_call', 'custom_tool_call'):
|
|
family = 'response.function_call_arguments' if item['type'] == 'function_call' else 'response.custom_tool_call_input'
|
|
require((index, family, None) in sealed, 'missing tool input done')
|
|
else:
|
|
family = 'response.reasoning_text' if item['type'] == 'reasoning' else 'response.output_text'
|
|
for ci in range(len(item.get('content', []))):
|
|
require((index, family, ci) in sealed, 'missing text done')
|
|
return response, len(events)
|
|
|
|
|
|
def save(root, name, data):
|
|
with (root / name).open('xb') as output:
|
|
os.fchmod(output.fileno(), 0o600)
|
|
output.write(data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False, indent=2).encode())
|
|
|
|
|
|
def idle(origin, key, timeout):
|
|
ready = exchange(origin, key, '/ready', None, timeout)
|
|
require(ready['status'] == 200, 'runtime is not ready')
|
|
metrics = exchange(origin, key, '/metrics', None, timeout)
|
|
require(metrics['status'] == 200, 'metrics unavailable')
|
|
data = json.loads(metrics['body'])
|
|
state = exchange(origin, key, '/admin/lifecycle', None, timeout)
|
|
require(state['status'] == 200, 'lifecycle status unavailable')
|
|
data['lifecycle'] = json.loads(state['body'])
|
|
require(data['active'] is False and data['queue_used'] == 0 and data['lifecycle']['requests_in_flight'] == 0
|
|
and data['lifecycle']['generation_jobs'] == 0, 'runtime has active or orphaned work')
|
|
return data
|
|
|
|
|
|
def run(args):
|
|
endpoint(args.endpoint)
|
|
require(0 < args.timeout <= 3600, 'timeout must be between 0 and 3600 seconds')
|
|
with Path(args.fixture).open('rb') as source:
|
|
raw = source.read(LIMIT + 1)
|
|
require(len(raw) <= LIMIT, 'fixture limit exceeded')
|
|
fixture = json.loads(raw)
|
|
require(fixture.get('schema') == 1 and fixture.get('sanitized') is True, 'explicit sanitized schema 1 fixture required')
|
|
steps = fixture['steps']
|
|
require(isinstance(steps, list) and 0 < len(steps) <= 100, 'episode needs 1..100 steps')
|
|
for i, step in enumerate(steps):
|
|
require(set(step) <= {'request', 'expect', 'tool_results'} and isinstance(step['expect'], list), 'invalid step')
|
|
require(not set(step['request']) & {'stream', 'previous_response_id', 'store'}, 'runner owns stream/history policy')
|
|
require(i > 0 or 'tool_results' not in step, 'first step cannot continue tools')
|
|
key = ''
|
|
if args.key_file:
|
|
fd = os.open(args.key_file, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
with os.fdopen(fd, 'rb') as source:
|
|
info = os.fstat(source.fileno())
|
|
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and not info.st_mode & 0o077,
|
|
'key file must be owned, private and regular')
|
|
data = source.read(515)
|
|
require(len(data) < 515, 'key file too large')
|
|
key = data.decode('ascii').strip()
|
|
require(32 <= len(key) <= 512 and all(33 <= ord(c) <= 126 for c in key), 'invalid key file')
|
|
require(key.encode() not in raw, 'fixture must not contain bearer credential')
|
|
root = Path(args.output)
|
|
root.mkdir(mode=0o700) # Never overwrite or resume previous evidence.
|
|
os.chmod(root, 0o700)
|
|
save(root, 'fixture.json', raw)
|
|
report = {'schema': 1, 'protocol_passed': False, 'fixture_sha256': hashlib.sha256(raw).hexdigest(),
|
|
'started_at_utc': datetime.now(timezone.utc).isoformat(),
|
|
'declared_provenance': fixture.get('provenance', {}), 'arms': [],
|
|
'limits': 'Explicit replay only; no tool execution, fault injection, quality or speed claim.'}
|
|
try:
|
|
for stream in (False, True):
|
|
arm = {'mode': 'sse' if stream else 'json', 'steps': [], 'before': idle(args.endpoint, key, args.timeout)}
|
|
report['arms'].append(arm)
|
|
previous = None
|
|
history = []
|
|
for i, step in enumerate(steps):
|
|
request = copy.deepcopy(step['request'])
|
|
request.update(stream=stream, store=False)
|
|
new_input = request['input']
|
|
new_input = [{'role': 'user', 'content': new_input}] if isinstance(new_input, str) else new_input
|
|
calls = [] if previous is None else [x for x in previous['output'] if x['type'] in ('function_call', 'custom_tool_call')]
|
|
require(not calls or 'tool_results' in step, 'missing fixture tool results')
|
|
if 'tool_results' in step:
|
|
require(len(calls) == len(step['tool_results']), 'tool result count differs from previous calls')
|
|
for call, output in zip(calls, step['tool_results']):
|
|
require(isinstance(output, str), 'tool results must be fixture text')
|
|
history.append({'type': 'function_call_output' if call['type'] == 'function_call' else 'custom_tool_call_output',
|
|
'call_id': call['call_id'], 'output': output})
|
|
request['input'] = history + new_input
|
|
prefix = f"{arm['mode']}-{i:03}"
|
|
save(root, prefix + '-request.json', request)
|
|
result = exchange(args.endpoint, key, '/v1/responses', request, args.timeout)
|
|
# Captures contain only explicitly supplied sanitized fixture traffic.
|
|
save(root, prefix + '-body.txt', result['body'].encode())
|
|
require(result['status'] == 200, 'Responses HTTP status was not 200')
|
|
require(result['content_type'].startswith('text/event-stream' if stream else 'application/json'), 'unexpected content type')
|
|
previous, count = verify_sse(result['body']) if stream else (json.loads(result['body']), 0)
|
|
require(previous.get('model') == request['model'], 'response model differs from request')
|
|
normalized = semantic(previous)
|
|
require(normalized == step['expect'], 'output differs from exact fixture expectation')
|
|
arm['steps'].append({'index': i, 'events': count, 'wall_seconds': result['wall_seconds'],
|
|
'usage': previous['usage'], 'semantic_sha256': hashlib.sha256(json.dumps(normalized, sort_keys=True).encode()).hexdigest()})
|
|
history = request['input'] + previous['output']
|
|
arm['after'] = idle(args.endpoint, key, args.timeout)
|
|
before, after = arm['before']['generation'], arm['after']['generation']
|
|
require(arm['before']['model'] == arm['after']['model'], 'model changed during replay')
|
|
require(after['started'] - before['started'] == len(steps)
|
|
and after['completed'] - before['completed'] == len(steps)
|
|
and after['cancelled'] == before['cancelled']
|
|
and after['failed_or_interrupted'] == before['failed_or_interrupted'],
|
|
'generation counters disagree with isolated replay')
|
|
require([x['semantic_sha256'] for x in report['arms'][0]['steps']] ==
|
|
[x['semantic_sha256'] for x in report['arms'][1]['steps']], 'JSON/SSE semantic mismatch')
|
|
report['protocol_passed'] = True
|
|
except (Invalid, KeyError, ValueError, TypeError, IndexError) as error:
|
|
report['failure'] = str(error) if isinstance(error, Invalid) else 'malformed evidence; inspect private captures'
|
|
raise
|
|
finally:
|
|
report['finished_at_utc'] = datetime.now(timezone.utc).isoformat()
|
|
save(root, 'report.json', report)
|
|
print(json.dumps({'protocol_passed': True, 'steps_per_arm': len(steps)}))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
if sys.argv[1:] == ['--exchange-worker']:
|
|
exchange_worker()
|
|
else:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--endpoint', required=True)
|
|
parser.add_argument('--fixture', required=True)
|
|
parser.add_argument('--output', required=True)
|
|
parser.add_argument('--key-file')
|
|
parser.add_argument('--timeout', type=float, default=120)
|
|
run(parser.parse_args())
|
|
except Exception:
|
|
print('live Responses replay failed; inspect private evidence (if created)', file=sys.stderr)
|
|
sys.exit(1)
|