#!/usr/bin/env python3 """Exercise STOP isolation and optional crash recovery through real HTTP.""" import http.client import json import os import pathlib import signal import socket import subprocess import sys import tempfile import time def tokenizer(root): visible = set(range(33, 127)) | set(range(161, 173)) | set(range(174, 256)) shifted = iter(range(256, 512)) tokens = [chr(i if i in visible else next(shifted)) for i in range(256)] tokens += ["<|im_start|>", "<|im_end|>", "", ""] pattern = ( r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}" r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+" ) files = { "vocab.json": {token: i for i, token in enumerate(tokens)}, "token_type.json": [1] * 256 + [3] * 4, "tokenizer.json": { "model": "gpt2", "pre": "qwen35", "vocab_size": len(tokens), "n_merges": 0, "special_ids": {}, "pre_pattern": pattern, }, } for name, value in files.items(): (root / name).write_text(json.dumps(value)) (root / "merges.txt").write_text("") def runtime_stack(env, root): """Test-only. With STRATA_TEST_FAKE_RUNTIME= in the environment, run this script's scripted stdio engine behind the Rust runtime stack instead of as strata-next's own child: strata-next (runtime backend) -> gRPC -> fake_runtime -> the same engine.sh. The fake runtime ends when this process does (it exits when its stdin closes). Without the variable `env` is returned unchanged, so every script that calls this keeps its original meaning. Used by the smokes whose assertions do not depend on strata-next owning the engine process: test-live-responses-replay, smoke-{custom-tools,chat-completions,messages,tool-policy,input-tokens, response-history,sse-keepalive,native-drain,queue-deadline}. Not by smoke-worker-cancel (a wedged engine ends the stdio supervisor; the runtime backend re-attaches instead), smoke-signal-drain (expects QUIT on the engine's stdin) or smoke-generation-deadline.""" fake = os.environ.get("STRATA_TEST_FAKE_RUNTIME") if not fake: return env env = dict(env) engine = env.pop("STRATA_ENGINE_EXE") arguments = json.loads(env.pop("STRATA_ENGINE_ARGS_JSON", "[]")) directory = env.pop("STRATA_TOKENIZER_DIR") env.pop("STRATA_MAX_WORKER_RESTARTS", None) env.pop("STRATA_STARTUP_TIMEOUT_S", None) token = "fixture-runtime-credential-" + os.urandom(8).hex() command = [fake, "--listen", "127.0.0.1:0", "--token-env", "FAKE_RUNTIME_TOKEN", "--engine", engine, "--tokenizer", directory] for argument in arguments: command += ["--engine-arg", argument] child = subprocess.Popen(command, env={"PATH": os.defpath, "FAKE_RUNTIME_TOKEN": token}, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) line = child.stdout.readline() assert line.startswith("LISTENING "), "the fake runtime did not start: " + line address = line.split()[1] config = pathlib.Path(root) / "runtime-config.json" config.write_text(json.dumps({"runtime": { "address": address, "token_env": "FAKE_RUNTIME_TOKEN", "tokenizer_dir": str(directory), "model": {"family": "fixture_family", "architecture": "fixture_arch", "weight_format": "fixture:stdio", "artifact_digest": "sha256:" + "c" * 64}, "mode": {"type": "native"}, "max_context": 262144, "attach_retry_s": 0.05, "health_interval_s": 0.2}})) env["STRATA_CONFIG"] = str(config) env["FAKE_RUNTIME_TOKEN"] = token return env def main(): binary = pathlib.Path(sys.argv[1]).resolve() recovery = len(sys.argv) == 3 and sys.argv[2] == "--restart" with tempfile.TemporaryDirectory(prefix="strata-cancel-http-") as directory: root = pathlib.Path(directory) tokenizer(root) engine = root / "engine.sh" pid_path, stopped = root / "worker.pid", root / "stopped" engine.write_text("""#!/bin/sh printf '%s' "$$" > "$2" printf 'READY 262144 stop\n' IFS= read -r line || exit 3 case "$line" in 'GEN '*) ;; *) exit 4 ;; esac printf 'T 65\n' IFS= read -r line || exit 3 [ "$line" = STOP ] || exit 4 : > "$3" printf 'T 66\n' while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac done """) if recovery: engine.write_text("""#!/bin/sh printf '%s' "$$" > "$2" printf 'boot\n' >> "$3.boots" printf 'READY 262144 stop\n' while IFS= read -r line; do case "$line" in 'GEN '*) printf '%s\n' "$line" >> "$3.requests" if [ ! -e "$3.crashed" ]; then : > "$3.crashed" printf 'T 65\n' exit 7 fi printf 'T 65\nDONE 1 1 1.0 2.0 stop\n' ;; 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_ENGINE_EXE": str(engine), "STRATA_ENGINE_ARGS_JSON": json.dumps([str(pid_path), str(stopped)]), "STRATA_TOKENIZER_DIR": str(root), "STRATA_STARTUP_TIMEOUT_S": "5", "STRATA_MAX_WORKER_RESTARTS": "1" if recovery else "0", } def request(method, path, body=None, timeout=30): connection = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) connection.request(method, path, body, {"Content-Type": "application/json"}) return connection, connection.getresponse() with tempfile.TemporaryFile() as logs: runtime = subprocess.Popen([binary, "serve"], env=env, stdout=logs, stderr=logs, start_new_session=True) try: deadline = time.monotonic() + 8 while True: try: conn, response = request("GET", "/ready", timeout=1) ready = response.status == 200 response.read() conn.close() if ready: break except (OSError, http.client.HTTPException): pass assert time.monotonic() < deadline, "runtime did not become ready" time.sleep(0.02) payload = {"model": "fixture", "input": "hello", "max_output_tokens": 3, "reasoning": {"effort": "none"}, "stream": True} if recovery: payload["stream"] = False began = time.monotonic() conn, response = request("POST", "/v1/responses", json.dumps(payload)) assert response.status == 503, (response.status, response.read()) assert json.loads(response.read())["error"]["code"] == "worker_not_ready" conn.close() conn, response = request("GET", "/ready") state = json.loads(response.read()) assert response.status == 503 and state["worker"] == "restarting" assert state["max_context"] is None conn.close() conn, response = request("POST", "/v1/responses", json.dumps(payload)) assert response.status == 503 response.read() conn.close() while True: conn, response = request("GET", "/ready") ready = response.status == 200 response.read() conn.close() if ready: break assert time.monotonic() - began < 8, "worker did not recover" time.sleep(0.02) elapsed = time.monotonic() - began conn, response = request("POST", "/v1/responses", json.dumps(payload)) assert response.status == 200 answer = json.loads(response.read()) assert answer["output"][0]["content"][0]["text"] == "A" assert answer["status"] == "completed" conn.close() assert pathlib.Path(str(stopped) + ".boots").read_text().splitlines() == ["boot", "boot"] assert len(pathlib.Path(str(stopped) + ".requests").read_text().splitlines()) == 2 print(json.dumps({"restart_seconds": round(elapsed, 3), "failed_request": 503, "during_recovery": 503, "fresh_request": 200, "fresh_text": "A", "process_starts": 2, "generations": 2, "failed_generation_replayed": False})) return conn, response = request("POST", "/v1/responses", json.dumps(payload)) assert response.status == 200 while b"response.output_text.delta" not in response.readline(): assert not response.isclosed(), "stream ended before first token" conn.sock.shutdown(socket.SHUT_RDWR) response.close() conn.close() cancel_at = time.monotonic() while not stopped.exists(): assert time.monotonic() - cancel_at < 3, "STOP was not delivered" time.sleep(0.02) payload["stream"] = False conn, response = request("POST", "/v1/responses", json.dumps(payload)) assert response.status == 503, (response.status, response.read()) failure = json.loads(response.read()) assert failure["error"]["code"] == "worker_not_ready" conn.close() elapsed = time.monotonic() - cancel_at assert 19.5 <= elapsed < 25, elapsed conn, response = request("GET", "/ready") state = json.loads(response.read()) assert response.status == 503 and state["worker"] == "failed" assert state["max_context"] is None conn.close() conn, response = request("GET", "/health") assert response.status == 200 response.read() conn.close() try: os.kill(int(pid_path.read_text()), 0) except ProcessLookupError: pass else: raise AssertionError("worker was not reaped") print(json.dumps({"stop_drain_seconds": round(elapsed, 3), "queued_request": 503, "readiness": "failed", "worker_reaped": True, "health": 200})) finally: if runtime.poll() is None: os.killpg(runtime.pid, signal.SIGTERM) try: runtime.wait(timeout=5) except subprocess.TimeoutExpired: os.killpg(runtime.pid, signal.SIGKILL) runtime.wait() if __name__ == "__main__": main()