Files
Pavlo RatushnyiandClaude Sonnet 5.5 36b526ee64 Soak harness: Codex-style session driver with fault injection, a holder job, an identity job, a self-test
scripts/soak/soak.py (stdlib Python, offline tooling): a never-ending agent session (streamed /v1/responses, a shell tool, grown from the frozen
782-file corpus, digest checked) with faults injected while a request is in flight: engine kill -9, engine hang (SIGSTOP), API kill, gateway kill /
SIGTERM, supervisor kill (the holder), client abort mid-stream, log flood, parallel burst. Judges eight criteria (recovery within bounds, no hang and
no silent truncation of any request, identical greedy probe before/after every fault, log directory bounded, no secret in logs, bounded descriptors,
progress, ready at the end), writes soak-result.json and a capped events.jsonl, exits 0 only if all hold.
scripts/soak/test_soak.py: the harness against a fake service (fake API, a supervisor that respawns a dummy engine, log rotation) - no GPU.
scripts/soak/soak-job.sh: the holder job for the real model (guards, gpu.lock, seal-probe on real files, `leleka up --mode none` from nothing,
cold-load A/B new vs LELEKA_LOAD_READ=legacy with shards evicted by posix_fadvise, then the soak under a restart loop that plays systemd).
scripts/soak/identity-job.sh: the replay identity gate for the fast cold load (adapted from draftround-id.sh: legacy bank read vs the new read,
one test binary, top-16 logprob rows and the draft trace must be identical).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 21:13:29 +01:00

177 lines
7.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Self-test of soak.py against a fake service (no GPU, no model): a fake Responses API, a fake supervisor that restarts a dummy
"engine" process, and a state directory shaped like the real one. Checks that the driver injects the faults, measures recovery,
judges the criteria and exits with the right code. python3 scripts/soak/test_soak.py"""
import http.server
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
HERE = os.path.dirname(os.path.abspath(__file__))
KEY = "test-api-key-0123456789abcdef0123456789abcdef"
class Fake:
def __init__(self, root):
self.root = root
os.makedirs(os.path.join(root, "state", "run"), exist_ok=True)
os.makedirs(os.path.join(root, "state", "logs"), exist_ok=True)
open(os.path.join(root, "state", "api-key"), "w").write(KEY)
open(os.path.join(root, "state", "runtime.env"), "w").write("LELEKA_RUNTIME_TOKEN=" + "r" * 40 + "\n")
self.engine = None
self.api_pid = None
self.restarts = 0
self.stop = False
self.spawn_engine()
threading.Thread(target=self.supervise, daemon=True).start()
threading.Thread(target=self.rotate, daemon=True).start()
self.write_status()
def spawn_engine(self):
self.engine = subprocess.Popen(["sleep", "3600"])
self.write_status()
def write_status(self):
doc = {"phase": "ready" if self.engine and self.engine.poll() is None else "engine_restarting",
"supervisor_pid": os.getpid(), "engine_pid": self.engine.pid if self.engine else None,
"gateway_pid": os.getpid(), "api_pid": os.getpid(), "restarts_total": self.restarts, "updated_unix": int(time.time())}
tmp = os.path.join(self.root, "state", "run", "status.json.tmp")
json.dump(doc, open(tmp, "w"))
os.replace(tmp, os.path.join(self.root, "state", "run", "status.json"))
def supervise(self):
while not self.stop:
if self.engine.poll() is not None:
self.write_status()
time.sleep(2)
self.restarts += 1
self.spawn_engine()
time.sleep(0.2)
def rotate(self):
"""What the real supervisor does every 10 s (logs.rs): truncate a log past its limit."""
logs = os.path.join(self.root, "state", "logs")
while not self.stop:
for name in os.listdir(logs):
p = os.path.join(logs, name)
if os.path.getsize(p) > 3 << 20:
open(p, "r+b").truncate(0)
time.sleep(1)
def alive(self):
return self.engine.poll() is None
def make_handler(fake):
class H(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def authorized(self):
return self.headers.get("Authorization") == "Bearer " + KEY
def do_GET(self):
if self.path == "/ready":
code = 200 if fake.alive() else 503
body = b"{}"
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(n) or b"{}")
if not self.authorized():
self.send_response(401)
self.send_header("Content-Length", "0")
self.end_headers()
return
if not fake.alive():
data = b'{"error":{"message":"engine unavailable"}}'
self.send_response(503)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Connection", "close")
self.end_headers()
self.close_connection = True
probe = "green blue red" if body.get("temperature") == 0 else "ok"
words = (probe + " ") * (40 if body.get("max_output_tokens", 0) > 100 else 1)
try:
for w in words.split():
if not fake.alive():
# the engine died mid-stream: a proper failure event
self.wfile.write(b'data: {"type":"response.failed","response":{"status":"failed","error":{"message":"engine lost"}}}\n\n')
return
self.wfile.write(("data: " + json.dumps({"type": "response.output_text.delta", "delta": w + " "}) + "\n\n").encode())
self.wfile.flush()
time.sleep(0.1 if len(words) > 50 else 0.01)
done = {"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 5000, "output_tokens": len(words.split())}}}
self.wfile.write(("data: " + json.dumps(done) + "\n\n").encode())
except (BrokenPipeError, ConnectionResetError):
pass
return H
def main():
root = tempfile.mkdtemp(prefix="soak-selftest-")
corpus = os.path.join(root, "corpus")
os.makedirs(corpus)
for i in range(40):
open(os.path.join(corpus, "f%02d.rs" % i), "w").write("// file %d\n" % i + ("fn x() { let a = %d; }\n" % i) * 2000)
fake = Fake(root)
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), make_handler(fake))
port = srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
out = os.path.join(root, "out")
cmd = [sys.executable, os.path.join(HERE, "soak.py"), "--base", "http://127.0.0.1:%d" % port, "--state-dir", os.path.join(root, "state"), "--out", out,
"--corpus", corpus, "--expect-corpus-sha256", "", "--duration-s", "55", "--faults", "abort@6,engine@12,burst@26,logs@32",
"--session-tokens", "30000", "--turn-tokens", "6000", "--max-output", "200", "--probe-every-s", "100000", "--recover-engine-s", "30",
"--fail-fast-s", "20", "--log-cap-mib", "8", "--flood-mib", "12", "--sample-s", "5", "--start-wait-s", "20"]
rc = subprocess.run(cmd, timeout=180).returncode
result = json.load(open(os.path.join(out, "soak-result.json")))
failures = []
def check(what, ok):
if not ok:
failures.append(what)
print(("ok " if ok else "FAIL ") + what)
check("exit code 0 when every criterion holds", rc == 0)
check("four faults were injected", [f["fault"] for f in result["faults"]] == ["abort", "engine", "burst", "logs"])
engine = next(f for f in result["faults"] if f["fault"] == "engine")
check("the engine kill recovered and the in-flight request ended with an error in time", engine["pass"] and engine["recovered_s"] is not None and (engine["ended_request"] or 0) < 20)
check("the supervisor restarted the engine once", result["status_end"].get("restarts_total") == 1)
check("the greedy probe matched before and after", result["probe_reference"] == "green blue red" and not result["probe_mismatch"])
flood = next(f for f in result["faults"] if f["fault"] == "logs")
check("the log flood was written, the cap held", flood.get("flood_bytes", 0) >= 12 << 20 and flood.get("log_cap_ok") is True)
check("no secret reached the logs", not result["secret_hits"])
shutil.rmtree(root, ignore_errors=True)
fake.stop = True
if failures:
print("self-test FAILED:", failures)
return 1
print("self-test passed")
return 0
if __name__ == "__main__":
sys.exit(main())