#!/usr/bin/env python3 """Actual HTTP deadline/admission checks for native GET-only deployment readiness.""" 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 main(): binary = Path(sys.argv[1]).resolve() key = 'fixture-only-wait-ready-key-00001' ready = {'service': 'strata-control', 'model': 'fixture', 'worker': 'ready', 'ready': True} state = {'mode': 'ready', 'calls': 0, 'paths': [], 'auth': []} stopped = threading.Event() class Handler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *_): pass def do_GET(self): self.close_connection = True state['calls'] += 1 state['paths'].append(self.path) state['auth'].append(self.headers.get('Authorization') == 'Bearer ' + key) mode = state['mode'] body = dict(ready) status = 200 try: if mode == 'headers': self.wfile.write(b'HTTP/1.1 200 OK\r\nX-Drip: ') while not stopped.wait(.1): self.wfile.write(b'x') self.wfile.flush() return if mode == 'loading' and state['calls'] < 3: body.update(worker='starting', ready=False) if mode == 'unavailable' and state['calls'] < 3: status = 503 if mode == 'wrong_model': body['model'] = 'other' if mode == 'wrong_service': body['service'] = 'other' if mode == 'inconsistent': body['worker'] = 'failed' if mode == 'wrong_type': body['ready'] = 'true' if mode == 'auth': status = 401 if mode == 'redirect': status = 302 encoded = json.dumps(body).encode() if mode == 'malformed': encoded = b'not-json-fixture-peer-body' if mode in ('oversize', 'chunked_oversize'): encoded = b'x' * 65537 self.send_response(status) if mode == 'redirect': self.send_header('Location', f'http://127.0.0.1:{self.server.server_port}/redirect-leak') if mode == 'chunked_oversize': self.send_header('Transfer-Encoding', 'chunked') else: self.send_header('Content-Length', str(len(encoded))) self.end_headers() if mode == 'body': for byte in encoded: if stopped.wait(.1): break self.wfile.write(bytes([byte])) self.wfile.flush() elif mode == 'chunked_oversize': self.wfile.write(f'{len(encoded):x}\r\n'.encode() + encoded + b'\r\n0\r\n\r\n') else: self.wfile.write(encoded) except (BrokenPipeError, ConnectionResetError): pass server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) server.daemon_threads = True thread = threading.Thread(target=server.serve_forever) thread.start() with tempfile.TemporaryDirectory(prefix='strata-wait-ready-') as directory: root = Path(directory) key_file = root / 'key' initialized = subprocess.run([binary, 'api-key', 'init', '--file', key_file], capture_output=True, timeout=8) assert initialized.returncode == 0 key = key_file.read_text().strip() assert key.encode() not in initialized.stdout + initialized.stderr env = {'PATH': os.defpath, 'http_proxy': 'http://127.0.0.1:1', 'HTTP_PROXY': 'http://127.0.0.1:1', 'ALL_PROXY': 'http://127.0.0.1:1', 'NO_PROXY': '', 'no_proxy': ''} origin = f'http://127.0.0.1:{server.server_port}' def run(url=origin, budget='2', keyed=True): command = [binary, 'wait-ready', '--url', url, '--model', 'fixture', '--timeout-s', budget] if keyed: command += ['--key-file', str(key_file)] began = time.monotonic() result = subprocess.run(command, env=env, capture_output=True, timeout=6) elapsed = time.monotonic() - began assert key.encode() not in result.stdout + result.stderr assert b'not-json-fixture-peer-body' not in result.stdout + result.stderr return result, elapsed try: for mode in ['ready', 'loading', 'unavailable']: state.update(mode=mode, calls=0, paths=[], auth=[]) result, _ = run() assert result.returncode == 0, result.stderr data = json.loads(result.stdout) assert data == {**{'service': 'strata-control', 'model': 'fixture', 'ready': True}, 'attempts': state['calls']} assert state['calls'] == (1 if mode == 'ready' else 3) assert all(state['auth']) and set(state['paths']) == {'/status'} for mode, message in [('wrong_model', 'does not match'), ('wrong_service', 'does not match'), ('inconsistent', 'inconsistent'), ('wrong_type', 'invalid readiness flag'), ('auth', 'authentication rejected'), ('redirect', 'redirects'), ('malformed', 'invalid readiness JSON'), ('oversize', '64 KiB'), ('chunked_oversize', '64 KiB')]: state.update(mode=mode, calls=0, paths=[], auth=[]) result, _ = run() assert result.returncode != 0 and message.encode() in result.stderr, (mode, result.stderr) assert state['calls'] == 1 and state['paths'] == ['/status'] for mode in ['headers', 'body']: state.update(mode=mode, calls=0, paths=[], auth=[]) result, elapsed = run(budget='1') assert result.returncode != 0 and b'deadline expired' in result.stderr, (mode, result.stderr) assert .8 <= elapsed < 2.5, (mode, elapsed) state.update(mode='ready', calls=0) key_file.chmod(0o644) result, _ = run() assert result.returncode != 0 and state['calls'] == 0 key_file.chmod(0o600) key_file.write_text('bad-key') result, _ = run() assert result.returncode != 0 and state['calls'] == 0 key_file.write_text(key) # Same binary serves a real isolated native /status. No GEN permitted. 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) fixture.tokenizer(root) worker = root / 'engine.sh' worker.write_text('''#!/bin/sh printf '%s' "$$" > "$2/pid" printf 'READY 262144 stop\n' while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; *) printf x > "$2/unexpected-command"; exit 7 ;; esac done ''') worker.chmod(0o700) with socket.socket() as port_probe: port_probe.bind(('127.0.0.1', 0)) port = port_probe.getsockname()[1] with tempfile.TemporaryFile() as logs: process = subprocess.Popen([binary, 'serve'], env={'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', 'STRATA_MODEL_ID': 'fixture', 'STRATA_ENGINE_EXE': str(worker), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_API_KEY_FILE': str(key_file), 'STRATA_MAX_WORKER_RESTARTS': '0'}, stdout=logs, stderr=logs) try: result, _ = run(url=f'http://127.0.0.1:{port}') assert result.returncode == 0, result.stderr os.kill(int((root / 'pid').read_text()), signal.SIGKILL) # Observe actual readiness revocation before asking the waiter. deadline = time.monotonic() + 3 while True: connection = http.client.HTTPConnection('127.0.0.1', port, timeout=1) connection.request('GET', '/ready', headers={'Authorization': 'Bearer ' + key}) response = connection.getresponse() response.read() connection.close() if response.status == 503: break assert time.monotonic() < deadline time.sleep(.02) result, elapsed = run(url=f'http://127.0.0.1:{port}', budget='1') assert result.returncode != 0 and b'deadline expired' in result.stderr assert elapsed < 2.5 and not (root / 'unexpected-command').exists() finally: process.terminate() try: process.wait(timeout=8) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=5) logs.seek(0) assert key.encode() not in logs.read() finally: stopped.set() server.shutdown() server.server_close() thread.join(timeout=3) print('wait-ready: exact identity/loading/auth/redirect/no-proxy/64KiB/drip deadline/private key and native worker outage passed; GET only, no inference') if __name__ == '__main__': main()