699 lines
32 KiB
Python
Executable File
699 lines
32 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Soak driver for the unattended Leleka service: a Codex-style agent session that never stops, with fault injection.
|
|
|
|
What it does (offline test tooling, stdlib only, Python 3.9+; the service itself is Rust):
|
|
|
|
* SESSION: one conversation at a time, grown turn by turn from a frozen source corpus up to --session-tokens, then a new one.
|
|
Requests are `POST /v1/responses` the way Codex sends them (streamed, `store:false`, a `shell` function tool, a function_call
|
|
answered with a canned function_call_output). After an error the driver retries with backoff, as a real client does.
|
|
* FAULTS: injected while a request is in flight (the schedule is --faults, see below): engine kill -9, engine hang (SIGSTOP),
|
|
gateway kill / restart, API kill, supervisor kill (the "holder": it owns the sealed archive), a client that aborts mid-stream,
|
|
a log flood, a burst of parallel requests.
|
|
* CHECKS: every request ends in a proper way (a completed response, an HTTP error, or an SSE failure event, within
|
|
--fail-fast-s of the fault); never a hang and never a stream that just stops. After each fault the service is ready again within
|
|
its bound and a fixed greedy probe returns the same text as before the first fault. Log directory, descriptors and memory stay
|
|
bounded, the logs hold no secret, and `restarts_total` of the supervisor matches what was injected.
|
|
* RESULT: `soak-result.json` (every criterion with its measured value), `events.jsonl` (bounded), exit code 0 only if all hold.
|
|
|
|
Pass criteria (defaults, all flags): see the soak test chapter of the unattended-operation spec node.
|
|
|
|
soak.py --state-dir STATE --out OUT --duration-s 5400 \
|
|
--faults "engine@900,hang@1800,api@2700,gateway@3000,abort@3300,logs@3500,burst@3800,supervisor@4200"
|
|
|
|
`--faults` is a comma list of NAME@SECONDS-AFTER-START or NAME@every:SECONDS. A fault waits until a request is in flight.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import os
|
|
import random
|
|
import re
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
|
|
PROBE_PROMPT = "Reply with exactly these three words and nothing else: green blue red"
|
|
QUESTIONS = [
|
|
"Which function in the code above is the most complex, and why? Answer in at most four sentences.",
|
|
"Name the module whose invariants matter most in the code above and say why, briefly.",
|
|
"List two risks you can see in the newest code and where they are. Be brief.",
|
|
"Summarise in three bullet points what the code so far does together.",
|
|
]
|
|
SHELL_TOOL = {
|
|
"type": "function",
|
|
"name": "shell",
|
|
"description": "Run a shell command and return its output.",
|
|
"parameters": {"type": "object", "properties": {"command": {"type": "array", "items": {"type": "string"}}}, "required": ["command"]},
|
|
}
|
|
PID_KEY = {"engine": "engine_pid", "hang": "engine_pid", "api": "api_pid", "gateway": "gateway_pid", "gateway-term": "gateway_pid", "supervisor": "supervisor_pid"}
|
|
TERMINAL = ("response.completed", "response.incomplete", "response.failed", "error")
|
|
|
|
|
|
def now():
|
|
return time.time()
|
|
|
|
|
|
class Events:
|
|
"""Append-only JSONL with a size cap (the soak must not become the unbounded file it tests for)."""
|
|
|
|
def __init__(self, path, cap=50 << 20):
|
|
self.path, self.cap, self.size, self.lock = path, cap, 0, threading.Lock()
|
|
self.f = open(path, "a", buffering=1)
|
|
|
|
def add(self, event, /, **fields):
|
|
line = json.dumps({"t": round(now(), 2), "event": event, **fields}, default=str)
|
|
with self.lock:
|
|
if self.size + len(line) < self.cap:
|
|
self.f.write(line + "\n")
|
|
self.size += len(line) + 1
|
|
return line
|
|
|
|
|
|
class Api:
|
|
def __init__(self, base, key, model):
|
|
u = urllib.parse.urlparse(base)
|
|
self.host, self.port, self.key, self.model = u.hostname, u.port or 80, key, model
|
|
|
|
def conn(self, timeout):
|
|
return http.client.HTTPConnection(self.host, self.port, timeout=timeout)
|
|
|
|
def get(self, path, timeout=5):
|
|
try:
|
|
c = self.conn(timeout)
|
|
c.request("GET", path, headers={"Authorization": "Bearer " + self.key})
|
|
r = c.getresponse()
|
|
body = r.read(1 << 20)
|
|
c.close()
|
|
try:
|
|
return r.status, json.loads(body)
|
|
except ValueError:
|
|
return r.status, None
|
|
except Exception as e: # noqa: BLE001 - any transport failure is "not answering"
|
|
return 0, str(e)
|
|
|
|
def body(self, items, max_out, tools=True, temperature=None):
|
|
b = {
|
|
"model": self.model,
|
|
"instructions": "You are a coding agent. Answer concisely. Use the shell tool only when you must run a command.",
|
|
"input": items,
|
|
"stream": True,
|
|
"store": False,
|
|
"parallel_tool_calls": False,
|
|
"reasoning": {"effort": "none"},
|
|
"max_output_tokens": max_out,
|
|
"prompt_cache_key": "019a0000-0000-7000-8000-000000050a4c",
|
|
}
|
|
if tools:
|
|
b["tools"] = [SHELL_TOOL]
|
|
b["tool_choice"] = "auto"
|
|
if temperature is not None:
|
|
b["temperature"] = temperature
|
|
return b
|
|
|
|
def stream(self, body, read_timeout, wall_limit=7200, abort_after_deltas=None, on_start=None):
|
|
"""One streamed request. Returns a dict: kind in completed|failed_event|http_error|conn_error|read_timeout|truncated|aborted."""
|
|
t0 = now()
|
|
out = {"t0": t0, "text": "", "calls": [], "deltas": 0, "usage": {}}
|
|
try:
|
|
c = self.conn(read_timeout)
|
|
c.request("POST", "/v1/responses", json.dumps(body), {"Authorization": "Bearer " + self.key, "Content-Type": "application/json"})
|
|
if on_start:
|
|
on_start()
|
|
r = c.getresponse()
|
|
if r.status != 200:
|
|
out.update(kind="http_error", status=r.status, detail=r.read(600).decode("utf8", "replace"))
|
|
return self._end(out)
|
|
terminal = None
|
|
for raw in r:
|
|
if now() - t0 > wall_limit:
|
|
out.update(kind="read_timeout", detail="wall limit")
|
|
return self._end(out)
|
|
line = raw.decode("utf8", "replace").strip()
|
|
if not line.startswith("data:"):
|
|
continue
|
|
try:
|
|
d = json.loads(line[5:])
|
|
except ValueError:
|
|
continue
|
|
ty = d.get("type", "")
|
|
if ty.endswith("output_text.delta"):
|
|
out["text"] += d.get("delta", "")
|
|
out["deltas"] += 1
|
|
out.setdefault("first_t", now())
|
|
if abort_after_deltas and out["deltas"] >= abort_after_deltas:
|
|
c.close()
|
|
out.update(kind="aborted")
|
|
return self._end(out)
|
|
elif ty == "response.output_item.done" and d.get("item", {}).get("type") == "function_call":
|
|
out["calls"].append(d["item"])
|
|
elif ty in TERMINAL:
|
|
terminal = d
|
|
resp = d.get("response") or {}
|
|
out["usage"] = resp.get("usage") or {}
|
|
out["status"] = resp.get("status") or ty
|
|
out["detail"] = json.dumps(resp.get("error") or d.get("error") or "")[:300]
|
|
break
|
|
if terminal is None:
|
|
out.update(kind="truncated", detail="the stream ended without a terminal event")
|
|
elif terminal.get("type") in ("response.failed", "error"):
|
|
out["kind"] = "failed_event"
|
|
else:
|
|
out["kind"] = "completed"
|
|
c.close()
|
|
except TimeoutError:
|
|
out.update(kind="read_timeout", detail="no data for %ss" % read_timeout)
|
|
except (ConnectionError, http.client.HTTPException, OSError) as e:
|
|
out.update(kind="conn_error", detail="%s: %s" % (type(e).__name__, e))
|
|
return self._end(out)
|
|
|
|
@staticmethod
|
|
def _end(out):
|
|
out["t1"] = now()
|
|
out["wall_s"] = round(out["t1"] - out["t0"], 2)
|
|
return out
|
|
|
|
|
|
def corpus_files(src):
|
|
files = []
|
|
for root, _d, names in os.walk(src):
|
|
for n in sorted(names):
|
|
if n.endswith(".rs"):
|
|
p = os.path.join(root, n)
|
|
try:
|
|
if os.path.getsize(p) > 1500:
|
|
files.append(p)
|
|
except OSError:
|
|
pass
|
|
files.sort()
|
|
return files
|
|
|
|
|
|
def corpus_digest(src, files):
|
|
h, chars = hashlib.sha256(), 0
|
|
for p in files:
|
|
d = open(p, "rb").read()
|
|
h.update(os.path.relpath(p, src).replace("\\", "/").encode() + b"\x00" + hashlib.sha256(d).digest())
|
|
chars += len(d)
|
|
return h.hexdigest(), chars
|
|
|
|
|
|
class Soak:
|
|
def __init__(self, a):
|
|
self.a = a
|
|
os.makedirs(a.out, exist_ok=True)
|
|
key = open(a.key_file or os.path.join(a.state_dir, "api-key")).read().strip()
|
|
self.key = key
|
|
self.api = Api(a.base, key, a.model)
|
|
self.ev = Events(os.path.join(a.out, "events.jsonl"))
|
|
self.stop = threading.Event()
|
|
self.in_flight = threading.Event()
|
|
self.t_start = now()
|
|
self.faults_done = [] # dicts, one per fault
|
|
self.turns = [] # per request outcome summary (kept small)
|
|
self.counts = {}
|
|
self.probe_ref = None
|
|
self.probe_mismatch = []
|
|
self.samples = []
|
|
self.lock = threading.Lock()
|
|
self.hung = None
|
|
self.files = corpus_files(a.corpus)
|
|
digest, chars = corpus_digest(a.corpus, self.files)
|
|
self.corpus = {"dir": a.corpus, "files": len(self.files), "chars": chars, "sha256": digest}
|
|
self.ev.add("corpus", **self.corpus)
|
|
|
|
# ---- helpers ------------------------------------------------------------------------------------------------
|
|
def status(self):
|
|
try:
|
|
return json.load(open(os.path.join(self.a.state_dir, "run", "status.json")))
|
|
except (OSError, ValueError):
|
|
return {}
|
|
|
|
def ready(self):
|
|
code, _ = self.api.get("/ready", 4)
|
|
return code == 200
|
|
|
|
def wait_ready(self, limit):
|
|
t0 = now()
|
|
while now() - t0 < limit and not self.stop.is_set():
|
|
if self.ready():
|
|
return round(now() - t0, 1)
|
|
time.sleep(2)
|
|
return None
|
|
|
|
def count(self, kind):
|
|
with self.lock:
|
|
self.counts[kind] = self.counts.get(kind, 0) + 1
|
|
|
|
def chunk(self, pos, tokens):
|
|
chars = int(tokens * 3.3)
|
|
parts, used, i = [], 0, pos
|
|
while used < chars:
|
|
p = self.files[i % len(self.files)]
|
|
t = open(p, encoding="utf-8", errors="replace").read()[: chars - used]
|
|
parts.append("// ==== " + os.path.relpath(p, self.a.corpus).replace("\\", "/") + "\n" + t)
|
|
used += len(t)
|
|
i += 1
|
|
return "\n".join(parts), i
|
|
|
|
# ---- the agent session --------------------------------------------------------------------------------------
|
|
def session_loop(self):
|
|
a, pos, session = self.a, random.Random(a_seed(self.a)).randrange(len(self.files)), 0
|
|
while not self.stop.is_set():
|
|
session += 1
|
|
items, used = [], 0
|
|
self.ev.add("session", n=session)
|
|
turn = 0
|
|
while not self.stop.is_set() and used < a.session_tokens:
|
|
turn += 1
|
|
text, pos = self.chunk(pos, min(a.turn_tokens, max(2000, a.session_tokens - used)))
|
|
items.append({"role": "user", "content": [{"type": "input_text", "text": text + "\n\n" + QUESTIONS[turn % len(QUESTIONS)]}]})
|
|
ok = self.one_turn(items, turn)
|
|
if ok is None: # could not complete after the retries: drop this session
|
|
break
|
|
used = ok
|
|
if self.probe_due():
|
|
self.probe("periodic")
|
|
|
|
def one_turn(self, items, turn):
|
|
"""Run one request, answer tool calls, retry errors with backoff. Returns the token count so far, or None."""
|
|
a = self.a
|
|
attempt, backoff = 0, 2.0
|
|
calls_left = 3
|
|
while not self.stop.is_set():
|
|
attempt += 1
|
|
self.in_flight.set()
|
|
out = self.api.stream(self.api.body(items, a.max_output), read_timeout=a.read_timeout)
|
|
self.in_flight.clear()
|
|
rec = {k: out.get(k) for k in ("kind", "status", "wall_s", "detail", "deltas")}
|
|
rec.update(turn=turn, attempt=attempt, input_tokens=out["usage"].get("input_tokens"), t0=round(out["t0"], 2), t1=round(out["t1"], 2))
|
|
if out.get("first_t"):
|
|
rec["ttft_s"] = round(out["first_t"] - out["t0"], 2)
|
|
self.ev.add("request", **rec)
|
|
self.count("req_" + out["kind"])
|
|
with self.lock:
|
|
self.turns.append((out["t0"], out["t1"], out["kind"], out.get("status")))
|
|
if out["kind"] == "completed" and out.get("status") in ("completed", "incomplete"):
|
|
if out["calls"] and calls_left > 0:
|
|
calls_left -= 1
|
|
for c in out["calls"]:
|
|
items.append(c)
|
|
items.append({"type": "function_call_output", "call_id": c.get("call_id"), "output": "src/lib.rs\nsrc/main.rs\nCargo.toml\n"})
|
|
continue
|
|
items.append({"role": "assistant", "content": [{"type": "output_text", "text": out["text"] or "(no text)"}]})
|
|
tokens = (out["usage"].get("input_tokens") or 0) + (out["usage"].get("output_tokens") or 0)
|
|
return tokens or sum(len(json.dumps(i)) for i in items) // 3
|
|
# An error: wait like Codex does and try the same request again (up to --retries).
|
|
if attempt > a.retries:
|
|
self.ev.add("turn_dropped", turn=turn, attempt=attempt)
|
|
return None
|
|
self.stop.wait(backoff)
|
|
backoff = min(backoff * 2, 30.0)
|
|
return None
|
|
|
|
# ---- the greedy probe -----------------------------------------------------------------------------------------
|
|
def probe_due(self):
|
|
return now() - getattr(self, "_last_probe", 0) > self.a.probe_every_s
|
|
|
|
def probe(self, why):
|
|
self._last_probe = now()
|
|
out = self.api.stream(self.api.body([{"role": "user", "content": [{"type": "input_text", "text": PROBE_PROMPT}]}], 24, tools=False, temperature=0), read_timeout=self.a.read_timeout)
|
|
ok = out["kind"] == "completed"
|
|
text = out["text"].strip()
|
|
self.ev.add("probe", why=why, kind=out["kind"], text=text[:80], wall_s=out["wall_s"])
|
|
if not ok:
|
|
return None
|
|
if self.probe_ref is None:
|
|
self.probe_ref = text
|
|
elif text != self.probe_ref:
|
|
self.probe_mismatch.append({"t": now(), "why": why, "text": text[:80], "ref": self.probe_ref[:80]})
|
|
return text
|
|
|
|
# ---- faults ---------------------------------------------------------------------------------------------------
|
|
def pid(self, name):
|
|
return self.status().get(name)
|
|
|
|
def inject(self, name, at):
|
|
a = self.a
|
|
rec = {"fault": name, "scheduled_s": at, "t": None}
|
|
st0 = self.status()
|
|
old_pid = st0.get(PID_KEY.get(name)) if name in PID_KEY else None
|
|
rec["restarts_before"] = st0.get("restarts_total")
|
|
# Wait (bounded) for a request in flight so the fault hits live work.
|
|
w0 = now()
|
|
while not self.in_flight.is_set() and now() - w0 < 600 and not self.stop.is_set():
|
|
time.sleep(0.2)
|
|
time.sleep(random.Random(at).uniform(2, 20) if name not in ("abort", "burst", "logs") else 1)
|
|
rec["t"] = now()
|
|
rec["in_flight"] = self.in_flight.is_set()
|
|
bound = a.recover_engine_s
|
|
try:
|
|
if name == "engine":
|
|
os.kill(self.pid("engine_pid"), signal.SIGKILL)
|
|
elif name == "hang":
|
|
self.hung = self.pid("engine_pid")
|
|
os.kill(self.hung, signal.SIGSTOP)
|
|
bound = a.hang_recover_s
|
|
elif name == "api":
|
|
os.kill(self.pid("api_pid"), signal.SIGKILL)
|
|
bound = a.recover_other_s
|
|
elif name == "gateway":
|
|
os.kill(self.pid("gateway_pid"), signal.SIGKILL)
|
|
bound = a.recover_other_s
|
|
elif name == "gateway-term":
|
|
os.kill(self.pid("gateway_pid"), signal.SIGTERM)
|
|
bound = a.recover_other_s
|
|
elif name == "supervisor":
|
|
children = [self.pid(k) for k in ("engine_pid", "gateway_pid", "api_pid")]
|
|
os.kill(self.pid("supervisor_pid"), signal.SIGKILL)
|
|
bound = a.recover_supervisor_s
|
|
if a.supervisor_cmd: # no systemd: do what it would do (its cgroup kill, then Restart=)
|
|
for child in children:
|
|
try:
|
|
os.kill(child, signal.SIGKILL)
|
|
except (OSError, TypeError):
|
|
pass
|
|
t_kill = now()
|
|
while now() - t_kill < 90 and any(child and os.path.exists("/proc/%d" % child) for child in children):
|
|
time.sleep(1)
|
|
subprocess.Popen(a.supervisor_cmd, shell=True, stdin=subprocess.DEVNULL, stdout=open(os.path.join(a.out, "supervisor-restarted.out"), "ab"), stderr=subprocess.STDOUT, start_new_session=True)
|
|
elif name == "abort":
|
|
out = self.api.stream(self.api.body([{"role": "user", "content": [{"type": "input_text", "text": "Count from 1 to 200, one number per line."}]}], 600, tools=False), a.read_timeout, abort_after_deltas=5)
|
|
rec["abort_kind"] = out["kind"]
|
|
bound = 60
|
|
elif name == "logs":
|
|
self.flood_logs(rec)
|
|
bound = 60
|
|
elif name == "burst":
|
|
self.burst(rec)
|
|
bound = 120
|
|
else:
|
|
raise ValueError("unknown fault " + name)
|
|
except Exception as e: # noqa: BLE001
|
|
rec["inject_error"] = "%s: %s" % (type(e).__name__, e)
|
|
# Recovery: ready again, and (for process faults) the in-flight request ended properly.
|
|
time.sleep(2)
|
|
outage = name in ("engine", "hang", "api", "gateway", "gateway-term", "supervisor")
|
|
rec["recovered_s"] = self.wait_for_recovery(rec["t"], bound, outage, PID_KEY.get(name), old_pid)
|
|
if name == "hang" and getattr(self, "hung", None):
|
|
if rec["recovered_s"] is None:
|
|
try:
|
|
os.kill(self.hung, signal.SIGKILL) # do not leave it stopped; the failure is recorded
|
|
except OSError:
|
|
pass
|
|
self.hung = None
|
|
rec["bound_s"] = bound
|
|
rec["ended_request"] = self.requests_ended_after(rec["t"])
|
|
text = self.probe("after-" + name) if rec["recovered_s"] is not None else None
|
|
rec["probe_ok"] = text is not None and text == self.probe_ref
|
|
st1 = self.status()
|
|
rec["restarts_after"] = st1.get("restarts_total")
|
|
rec["phase_after"] = st1.get("phase")
|
|
rec["pass"] = bool(rec["recovered_s"] is not None and rec["recovered_s"] <= bound and "inject_error" not in rec and rec["probe_ok"] is not False)
|
|
if name in ("engine", "hang", "api", "gateway", "gateway-term", "supervisor") and rec["ended_request"] is not None:
|
|
rec["pass"] = rec["pass"] and rec["ended_request"] <= a.fail_fast_s_for(name)
|
|
self.faults_done.append(rec)
|
|
self.ev.add("fault", **rec)
|
|
return rec
|
|
|
|
def wait_for_recovery(self, t_fault, bound, outage=True, pid_key=None, old_pid=None):
|
|
"""Seconds from the fault until the service answers /ready again. For a fault that takes the service down, first see it go
|
|
away (or, if it never does, give it 20 s to prove that); a fault that is no outage is judged by the first answer."""
|
|
t0 = now()
|
|
gone = False
|
|
while now() - t0 < bound + 30:
|
|
r = self.ready()
|
|
if not r:
|
|
gone = True
|
|
# A process fault is over when the process was replaced (a hung engine keeps answering /ready until the API has given up on it).
|
|
replaced = pid_key is None or old_pid is None or self.status().get(pid_key) not in (None, old_pid)
|
|
if r and replaced and (gone or not outage or now() - t_fault > 20):
|
|
return round(now() - t_fault, 1)
|
|
if self.stop.is_set() and now() - t0 > bound:
|
|
break
|
|
time.sleep(2 if outage else 0.5)
|
|
return None
|
|
|
|
def requests_ended_after(self, t_fault):
|
|
"""Seconds from the fault to the end of the first request that was running when it hit (None: none was)."""
|
|
with self.lock:
|
|
for t0, t1, kind, status in self.turns:
|
|
if t0 <= t_fault <= t1:
|
|
return round(t1 - t_fault, 1)
|
|
# a request still in flight at the fault that has not ended yet is recorded when it does; look again later
|
|
return None
|
|
|
|
def flood_logs(self, rec):
|
|
logs = os.path.join(self.a.state_dir, "logs")
|
|
before = dir_bytes(logs)
|
|
junk = ("flood " + "x" * 120 + "\n") * (1 << 15) # ~4 MiB
|
|
written = 0
|
|
t0 = now()
|
|
while written < self.a.flood_mib << 20 and now() - t0 < 120:
|
|
for name in ("engine.log", "api.log", "gateway.log"):
|
|
try:
|
|
with open(os.path.join(logs, name), "a") as f:
|
|
f.write(junk)
|
|
written += len(junk)
|
|
except OSError:
|
|
pass
|
|
time.sleep(0.2)
|
|
rec["flood_bytes"] = written
|
|
rec["log_bytes_before"] = before
|
|
# the supervisor checks every 10 s
|
|
deadline = now() + 60
|
|
while now() < deadline and dir_bytes(logs) > self.a.log_cap_mib << 20:
|
|
time.sleep(2)
|
|
rec["log_bytes_after"] = dir_bytes(logs)
|
|
rec["log_cap_ok"] = rec["log_bytes_after"] <= self.a.log_cap_mib << 20
|
|
|
|
def burst(self, rec):
|
|
results = []
|
|
|
|
def one(i):
|
|
out = self.api.stream(self.api.body([{"role": "user", "content": [{"type": "input_text", "text": "Say the number %d." % i}]}], 16, tools=False), self.a.read_timeout)
|
|
results.append((out["kind"], out.get("status"), out["wall_s"]))
|
|
|
|
ts = [threading.Thread(target=one, args=(i,)) for i in range(8)]
|
|
[t.start() for t in ts]
|
|
[t.join() for t in ts]
|
|
rec["burst"] = results
|
|
rec["burst_improper"] = [r for r in results if r[0] in ("truncated", "read_timeout")]
|
|
|
|
# ---- sampling -------------------------------------------------------------------------------------------------
|
|
def sample_loop(self):
|
|
logs = os.path.join(self.a.state_dir, "logs")
|
|
while not self.stop.wait(self.a.sample_s):
|
|
st = self.status()
|
|
s = {"t": round(now(), 1), "log_bytes": dir_bytes(logs), "phase": st.get("phase"), "restarts_total": st.get("restarts_total")}
|
|
for name in ("supervisor_pid", "api_pid", "engine_pid", "gateway_pid"):
|
|
pid = st.get(name)
|
|
if pid:
|
|
s[name.replace("_pid", "_rss_mib")] = rss_mib(pid)
|
|
s[name.replace("_pid", "_fds")] = fd_count(pid)
|
|
self.samples.append(s)
|
|
self.ev.add("sample", **s)
|
|
|
|
def fault_loop(self):
|
|
schedule = []
|
|
for spec in self.a.faults.split(","):
|
|
spec = spec.strip()
|
|
if not spec:
|
|
continue
|
|
name, _, when = spec.partition("@")
|
|
if when.startswith("every:"):
|
|
step = float(when[6:])
|
|
t = step
|
|
while t < self.a.duration_s - 60:
|
|
schedule.append((t, name))
|
|
t += step
|
|
else:
|
|
schedule.append((float(when), name))
|
|
schedule.sort()
|
|
for at, name in schedule:
|
|
while now() - self.t_start < at and not self.stop.is_set():
|
|
time.sleep(1)
|
|
if self.stop.is_set():
|
|
break
|
|
self.inject(name, at)
|
|
|
|
# ---- run -----------------------------------------------------------------------------------------------------
|
|
def run(self):
|
|
a = self.a
|
|
if len(self.files) < 20 or self.corpus["chars"] < 1_000_000:
|
|
print("soak: the corpus %s is too small (%d files, %d chars); refusing to run a toy session" % (a.corpus, len(self.files), self.corpus["chars"]), file=sys.stderr)
|
|
return 2
|
|
if a.expect_corpus_sha256 and a.expect_corpus_sha256 != self.corpus["sha256"]:
|
|
print("soak: corpus digest %s differs from the expected %s" % (self.corpus["sha256"], a.expect_corpus_sha256), file=sys.stderr)
|
|
return 2
|
|
if self.wait_ready(a.start_wait_s) is None:
|
|
print("soak: the service is not ready after %ss" % a.start_wait_s, file=sys.stderr)
|
|
return 3
|
|
self.status0 = self.status()
|
|
self.probe("start")
|
|
threads = [threading.Thread(target=f, daemon=True) for f in (self.session_loop, self.sample_loop, self.fault_loop)]
|
|
[t.start() for t in threads]
|
|
while now() - self.t_start < a.duration_s:
|
|
time.sleep(2)
|
|
self.stop.set()
|
|
time.sleep(3)
|
|
return self.finish()
|
|
|
|
def finish(self):
|
|
a = self.a
|
|
logs = os.path.join(a.state_dir, "logs")
|
|
st = self.status()
|
|
final_probe = self.probe("end") if self.ready() else None
|
|
injected_process_faults = sum(1 for f in self.faults_done if f["fault"] in ("engine", "hang", "api", "gateway", "gateway-term"))
|
|
improper = [t for t in self.turns if t[2] in ("truncated", "read_timeout")]
|
|
secrets = scan_secrets(logs, [self.key] + token_values(a.state_dir))
|
|
max_logs = max([s["log_bytes"] for s in self.samples] + [dir_bytes(logs)])
|
|
fds = [s.get("supervisor_fds") for s in self.samples if s.get("supervisor_fds")]
|
|
crit = {
|
|
"all faults recovered within their bound": all(f["pass"] for f in self.faults_done) and bool(self.faults_done),
|
|
"no request ended improperly (no hang, no silent truncation)": not improper,
|
|
"greedy probe identical before, after every fault and at the end": not self.probe_mismatch and final_probe == self.probe_ref and self.probe_ref is not None,
|
|
"log directory stayed under its cap": max_logs <= a.log_cap_mib << 20,
|
|
"no secret in the logs": not secrets,
|
|
"supervisor descriptors bounded (< 200, growth < 50)": (not fds) or (max(fds) < 200 and max(fds) - min(fds) < 50),
|
|
"the session made progress (completed requests)": self.counts.get("req_completed", 0) > 0,
|
|
"service ready at the end": self.ready(),
|
|
}
|
|
result = {
|
|
"duration_s": round(now() - self.t_start, 1),
|
|
"corpus": self.corpus,
|
|
"status_start": self.status0,
|
|
"status_end": st,
|
|
"request_counts": self.counts,
|
|
"faults": self.faults_done,
|
|
"probe_reference": self.probe_ref,
|
|
"probe_mismatch": self.probe_mismatch,
|
|
"improper_requests": improper[:20],
|
|
"secret_hits": secrets,
|
|
"max_log_bytes": max_logs,
|
|
"supervisor_restarts_total_at_end": st.get("restarts_total"),
|
|
"injected_process_faults": injected_process_faults,
|
|
"criteria": crit,
|
|
"pass": all(crit.values()),
|
|
}
|
|
with open(os.path.join(a.out, "soak-result.json"), "w") as f:
|
|
json.dump(result, f, indent=1, default=str)
|
|
for k, v in crit.items():
|
|
print(("PASS " if v else "FAIL ") + k)
|
|
for f_ in self.faults_done:
|
|
print("fault %-13s recovered %s s (bound %s) request ended %s s after, probe_ok=%s %s" % (f_["fault"], f_.get("recovered_s"), f_.get("bound_s"), f_.get("ended_request"), f_.get("probe_ok"), "ok" if f_["pass"] else "FAILED"))
|
|
return 0 if result["pass"] else 1
|
|
|
|
|
|
def a_seed(a):
|
|
return a.seed
|
|
|
|
|
|
def dir_bytes(d):
|
|
total = 0
|
|
try:
|
|
for n in os.listdir(d):
|
|
try:
|
|
total += os.path.getsize(os.path.join(d, n))
|
|
except OSError:
|
|
pass
|
|
except OSError:
|
|
pass
|
|
return total
|
|
|
|
|
|
def rss_mib(pid):
|
|
try:
|
|
for line in open("/proc/%d/status" % pid):
|
|
if line.startswith("VmRSS:"):
|
|
return int(line.split()[1]) // 1024
|
|
except OSError:
|
|
pass
|
|
return None
|
|
|
|
|
|
def fd_count(pid):
|
|
try:
|
|
return len(os.listdir("/proc/%d/fd" % pid))
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def token_values(state_dir):
|
|
out = []
|
|
try:
|
|
for line in open(os.path.join(state_dir, "runtime.env")):
|
|
if "=" in line:
|
|
v = line.split("=", 1)[1].strip()
|
|
if len(v) >= 16:
|
|
out.append(v)
|
|
except OSError:
|
|
pass
|
|
return out
|
|
|
|
|
|
def scan_secrets(logs, secrets):
|
|
"""File names (never contents) of logs that contain a secret value."""
|
|
hits = []
|
|
needles = [s.encode() for s in secrets if s]
|
|
try:
|
|
names = os.listdir(logs)
|
|
except OSError:
|
|
return hits
|
|
for n in names:
|
|
p = os.path.join(logs, n)
|
|
try:
|
|
with open(p, "rb") as f:
|
|
while True:
|
|
block = f.read(8 << 20)
|
|
if not block:
|
|
break
|
|
if any(s in block for s in needles):
|
|
hits.append(n)
|
|
break
|
|
except OSError:
|
|
pass
|
|
return hits
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
p.add_argument("--base", default="http://127.0.0.1:8081")
|
|
p.add_argument("--model", default="qwen-iq3")
|
|
p.add_argument("--state-dir", required=True, help="the service STATE directory (run/status.json, logs/, runtime.env, api-key)")
|
|
p.add_argument("--key-file")
|
|
p.add_argument("--out", required=True)
|
|
p.add_argument("--corpus", default="/data/leleka-e2e/decode/corpus/src/crates")
|
|
p.add_argument("--expect-corpus-sha256", default="1152f45acaa9a62591e50d8f6807f50ce6fe1249db659cdb9e8e4a041ed119a7", help="'' to skip the check")
|
|
p.add_argument("--duration-s", type=int, default=5400)
|
|
p.add_argument("--faults", default="engine@900,hang@1800,api@2700,gateway@3000,abort@3300,logs@3500,burst@3800,supervisor@4200")
|
|
p.add_argument("--session-tokens", type=int, default=200000)
|
|
p.add_argument("--turn-tokens", type=int, default=40000)
|
|
p.add_argument("--max-output", type=int, default=400)
|
|
p.add_argument("--read-timeout", type=int, default=900, help="client socket timeout per read (must exceed the API stall timeout)")
|
|
p.add_argument("--retries", type=int, default=40)
|
|
p.add_argument("--probe-every-s", type=int, default=1200)
|
|
p.add_argument("--sample-s", type=int, default=60)
|
|
p.add_argument("--recover-engine-s", type=int, default=900)
|
|
p.add_argument("--hang-recover-s", type=int, default=1500)
|
|
p.add_argument("--recover-other-s", type=int, default=120)
|
|
p.add_argument("--recover-supervisor-s", type=int, default=1500)
|
|
p.add_argument("--fail-fast-s", type=int, default=90, help="a request hit by a crash must end with an error this fast")
|
|
p.add_argument("--hang-error-s", type=int, default=700, help="a request hit by a hang must end with an error this fast (API stall timeout + drain)")
|
|
p.add_argument("--log-cap-mib", type=int, default=400)
|
|
p.add_argument("--flood-mib", type=int, default=64)
|
|
p.add_argument("--start-wait-s", type=int, default=3600)
|
|
p.add_argument("--supervisor-cmd", default="", help="how to start the supervisor again after the kill (omit under systemd)")
|
|
p.add_argument("--seed", type=int, default=1)
|
|
a = p.parse_args()
|
|
a.fail_fast_s_for = lambda name: a.hang_error_s if name == "hang" else (a.recover_supervisor_s if name == "supervisor" else a.fail_fast_s)
|
|
soak = Soak(a)
|
|
sys.exit(soak.run())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|