#!/usr/bin/env python3 """Compare native HTTP input counts with actual GEN wire tokens, without a GPU.""" 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-input-tokens-') as directory: root = Path(directory) fixture.tokenizer(root) key = 'fixture-only-input-count-key-00001' (root / 'key').write_text(key) (root / 'key').chmod(0o600) engine = root / 'engine.sh' engine.write_text('''#!/bin/sh printf '%s' "$$" > "$2/pid" printf 'READY 262144 stop\n' while IFS= read -r line; do case "$line" in 'GEN '*) printf '%s\n' "$line" >> "$2/wire"; 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(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', 'STRATA_RESPONSE_HISTORY_DIR': str(root / 'history'), 'STRATA_MAX_IN_FLIGHT_REQUESTS': '1'} def request(method, path, payload=None, auth=True, raw=None): 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, raw if raw is not None else 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:')] data = events[-1]['response'] else: data = json.loads(data) if data else None return response.status, data finally: connection.close() def wire(): return (root / 'wire').read_bytes() if (root / 'wire').exists() else b'' def snapshot(): return {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()} def count(payload, expected=200): before, stored = wire(), snapshot() code, data = request('POST', '/v1/responses/input_tokens', payload) assert code == expected, (code, data) assert wire() == before and snapshot() == stored, 'count must not generate or write history' if code == 200: assert set(data) == {'object', 'input_tokens'} and data['object'] == 'response.input_tokens', data assert isinstance(data['input_tokens'], int) and data['input_tokens'] > 0 return data payload = {'model': 'fixture', 'input': 'Привіт 🌍', 'max_output_tokens': 8, 'reasoning': {'effort': 'none'}} 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) 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) assert request('POST', '/v1/responses/input_tokens', payload, auth=False)[0] == 401 assert request('POST', '/v1/responses/input_tokens', raw='{')[0] == 400 assert request('GET', '/v1/responses/input_tokens')[0] == 405 tools = [{'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'key': {'type': 'string'}}}}, {'type': 'custom', 'name': 'patch'}, {'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]}] cases = [payload, {**payload, 'stream': True, 'instructions': 'Answer briefly.'}, {**payload, 'tools': tools}, {**payload, 'reasoning': {'effort': 'high'}}, {**payload, 'input': [{'type': 'function_call', 'call_id': 'c1', 'name': 'lookup', 'arguments': '{"key":"value"}'}, {'type': 'function_call_output', 'call_id': 'c1', 'output': 'Found 🌍'}], 'tools': tools}] ordinary_output = 'T 65\nDONE 1 7 1.0 2.0 stop\n' parent = None for current in cases: (root / 'output').write_text(('T 259\nT 10\n' if current['reasoning']['effort'] == 'high' else '') + ordinary_output) measured = count(current)['input_tokens'] code, result = request('POST', '/v1/responses', current) assert code == 200 and result['status'] == 'completed', result ids = wire().decode().splitlines()[-1].split()[-1].split(',') assert measured == len(ids), (measured, len(ids)) # actual engine wire, not DONE usage parent = result['id'] (root / 'output').write_text(ordinary_output) continued = {**payload, 'previous_response_id': parent, 'instructions': 'New instruction.'} measured = count(continued)['input_tokens'] code, result = request('POST', '/v1/responses', continued) assert code == 200 and measured == len(wire().decode().splitlines()[-1].split()[-1].split(',')) assert request('DELETE', '/v1/responses/' + parent)[0] == 200 assert count(continued, 404)['error']['code'] == 'response_not_found' for bad, status in [({**payload, 'model': 'other'}, 404), ({**payload, 'input': []}, 400), ({**payload, 'input': [{'type': 'input_image'}]}, 400), ({**payload, 'truncation': 'auto'}, 501), ({**payload, 'unknown': True}, 400)]: counted = count(bad, status) code, generated = request('POST', '/v1/responses', bad) assert code == status and counted == generated, (counted, generated) count({**payload, 'store': False}) # Hold one admitted body open; count must respect shared capacity. with socket.create_connection(('127.0.0.1', port), timeout=5) as held: held.sendall(('POST /v1/responses/input_tokens HTTP/1.1\r\nHost: localhost\r\n' 'Content-Type: application/json\r\nContent-Length: 100\r\n' 'Authorization: Bearer ' + key + '\r\n\r\n{').encode()) deadline = time.monotonic() + 5 while request('GET', '/admin/lifecycle')[1]['requests_in_flight'] == 0: assert time.monotonic() < deadline time.sleep(.02) count(payload, 429) deadline = time.monotonic() + 5 while request('GET', '/admin/lifecycle')[1]['requests_in_flight']: assert time.monotonic() < deadline time.sleep(.02) request('POST', '/admin/drain', {}) count(payload, 503) request('POST', '/admin/resume', {}) expected = count(payload) os.kill(int((root / 'pid').read_text()), signal.SIGKILL) deadline = time.monotonic() + 5 while request('GET', '/ready')[0] == 200: assert time.monotonic() < deadline time.sleep(.02) assert count(payload) == expected assert request('POST', '/v1/responses', payload)[0] == 503 assert request('GET', '/admin/lifecycle')[1]['generation_jobs'] == 0 finally: process.terminate() try: process.wait(timeout=10) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=5) if process.returncode != 0: logs.seek(0) raise AssertionError(logs.read().decode()) print('input_tokens: exact GEN wire parity for text/stream/tools/reasoning/continuation, validation/auth/drain/outage and no history mutation PASS') if __name__ == '__main__': main()