Download code/oncallval/faults.py from Fektor/OnCallVal: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/datasets/Fektor/OnCallVal/resolve/main/code/oncallval/faults.py
- Command line
-
hf download hf://datasets/Fektor/OnCallVal/code/oncallval/faults.py
-
curl -L -o faults.py https://huggingface.co/datasets/Fektor/OnCallVal/resolve/main/code/oncallval/faults.py
19.6 kB
| """Fault and decoy library. | |
| Each fault type declares: | |
| BASE_WEIGHT -- difficulty contribution | |
| plan() -- pick targets from the generated fleet (or None if impossible) | |
| apply() -- mutate the spec (deploys, config, events, hosts, queues, secrets) | |
| impact() -- state-derived metric contributions (empty when fixed) | |
| active() -- True while the fault is unfixed | |
| services() -- affected services (excluded from collateral checks) | |
| alert_svc() -- service the page fires on | |
| solution() -- minimal action list + cause string (used by the oracle agent) | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import random | |
| from .world import current_version, frac_on_host | |
| def _hex(rng: random.Random, n: int = 6) -> str: | |
| return "".join(rng.choice("0123456789abcdef") for _ in range(n)) | |
| def _bump_version(v: str) -> str: | |
| a, b, c = v.lstrip("v").split(".") | |
| return f"v{a}.{int(b) + 1}.0" | |
| def _replicas_on(spec_svc: dict, host: str) -> int: | |
| hosts = spec_svc["hosts"] | |
| if host not in hosts: | |
| return 0 | |
| return spec_svc["replicas"] // len(hosts) + (1 if hosts.index(host) < spec_svc["replicas"] % len(hosts) else 0) | |
| def _every(rng: random.Random, start: int, end: int, step: tuple[int, int], svc: str, level: str, msg) -> list[dict]: | |
| out, t = [], start | |
| while t < end: | |
| out.append({"t": t, "svc": svc, "level": level, "msg": msg(t) if callable(msg) else msg}) | |
| t += rng.randint(*step) | |
| return out | |
| class Fault: | |
| BASE_WEIGHT = 3 | |
| NAME = "fault" | |
| def plan(cls, rng, fleet, spec): | |
| raise NotImplementedError | |
| def apply(cls, spec, params, rng): | |
| raise NotImplementedError | |
| def impact(cls, w, params): | |
| return {} | |
| def active(cls, w, params): | |
| raise NotImplementedError | |
| def services(cls, params): | |
| return [params["svc"]] | |
| def alert_svc(cls, params): | |
| return params["svc"] | |
| def solution(cls, w, params): | |
| raise NotImplementedError | |
| class BadDeploy(Fault): | |
| NAME = "bad_deploy" | |
| BASE_WEIGHT = 3 | |
| def plan(cls, rng, fleet, spec): | |
| cands = fleet["apis"] + fleet["workers"] + [fleet["gateway"]] | |
| return {"svc": rng.choice(cands)} | |
| def apply(cls, spec, params, rng): | |
| s = spec["services"][params["svc"]] | |
| buggy = _bump_version(s["deploys"][-1]["version"]) | |
| t0 = -rng.randint(8, 20) | |
| s["deploys"].append({"version": buggy, "t": t0, "by": "ci"}) | |
| params["buggy"] = buggy | |
| params["error_add"] = round(s["slo_error_pct"] * rng.uniform(4, 8), 2) | |
| params["p99_add"] = rng.randint(100, 300) | |
| msgs = [ | |
| "panic: runtime error: invalid memory address or nil pointer dereference", | |
| "http: superfluous response.WriteHeader call from handler", | |
| "ERROR: failed to marshal response: unexpected end of JSON input", | |
| ] | |
| spec["events"] += _every(rng, t0, 0, (2, 5), params["svc"], "ERROR", | |
| lambda t: msgs[int(t) % len(msgs)]) | |
| return params | |
| def impact(cls, w, params): | |
| if current_version(w, params["svc"]) == params["buggy"]: | |
| return {params["svc"]: {"error_pct": params["error_add"], "p99_ms": params["p99_add"]}} | |
| return {} | |
| def active(cls, w, params): | |
| return current_version(w, params["svc"]) == params["buggy"] | |
| def solution(cls, w, params): | |
| return [{"action": "rollback", "service": params["svc"]}], f"{cls.NAME}:{params['svc']}" | |
| class MemoryLeak(Fault): | |
| NAME = "memory_leak" | |
| BASE_WEIGHT = 4 | |
| def plan(cls, rng, fleet, spec): | |
| cands = fleet["apis"] + fleet["workers"] | |
| return {"svc": rng.choice(cands)} | |
| def apply(cls, spec, params, rng): | |
| s = spec["services"][params["svc"]] | |
| buggy = _bump_version(s["deploys"][-1]["version"]) | |
| t0 = -rng.randint(180, 360) | |
| s["deploys"].append({"version": buggy, "t": t0, "by": "ci"}) | |
| params.update(buggy=buggy, deploy_t=t0, leak_rate=round(rng.uniform(0.8, 1.5), 2)) | |
| params["error_add"] = round(s["slo_error_pct"] * rng.uniform(1.0, 2.5), 2) | |
| params["p99_add"] = rng.randint(50, 150) | |
| ev = [] | |
| t = -rng.randint(2, 10) # most recent OOM kill shortly before the page | |
| i = 0 | |
| floor = max(t0 + 60, -400) # leak needs time to build before first kill | |
| while t > floor and len(ev) < 12: | |
| ev.append({"t": t, "svc": params["svc"], "level": "ERROR", | |
| "msg": f"pod {params['svc']}-{i % 4} killed: OOMKilled (limit 2Gi)"}) | |
| t -= rng.randint(8, 18) | |
| i += 1 | |
| spec["events"] += ev | |
| return params | |
| def impact(cls, w, params): | |
| if current_version(w, params["svc"]) != params["buggy"]: | |
| return {} | |
| last = max(params["deploy_t"], w["restarts"].get(params["svc"], params["deploy_t"])) | |
| mem = params["leak_rate"] * max(0.0, w["t"] - last) | |
| return {params["svc"]: {"error_pct": params["error_add"], "p99_ms": params["p99_add"], "mem_pct": mem}} | |
| def active(cls, w, params): | |
| return current_version(w, params["svc"]) == params["buggy"] | |
| def solution(cls, w, params): | |
| return [{"action": "rollback", "service": params["svc"]}], f"{cls.NAME}:{params['svc']}" | |
| class ConfigDrift(Fault): | |
| NAME = "config_drift" | |
| BASE_WEIGHT = 3 | |
| KEYS = { | |
| "pool_size": ("db pool exhausted ({bad}/{bad} connections in use)", (2, 5), 60), | |
| "timeout_ms": ("upstream timeout after {bad}ms", (2, 4), 30), | |
| "retries": ("request failed after 0 retries: context deadline exceeded", (3, 6), 20), | |
| "cache_ttl_ms": ("cache hit ratio dropped to 0% (ttl=0)", (4, 8), 15), | |
| } | |
| def plan(cls, rng, fleet, spec): | |
| cands = [s for s in fleet["apis"] + fleet["workers"] + [fleet["gateway"]] | |
| if any(k in spec["services"][s]["config"] for k in cls.KEYS)] | |
| if not cands: | |
| return None | |
| svc = rng.choice(cands) | |
| keys = [k for k in cls.KEYS if k in spec["services"][svc]["config"]] | |
| return {"svc": svc, "key": rng.choice(keys)} | |
| def apply(cls, spec, params, rng): | |
| s = spec["services"][params["svc"]] | |
| key = params["key"] | |
| rec = s["runbook"]["recommended"][key] | |
| bad = max(0, int(rec * rng.choice([0.05, 0.1, 0.2]))) | |
| s["config"][key] = bad | |
| t0 = -rng.randint(10, 30) | |
| params.update(rec=rec, bad=bad) | |
| spec["events"].append({"t": t0, "svc": params["svc"], "level": "INFO", | |
| "msg": f"config {key}={bad} applied by deploy-bot (change #{_hex(rng, 4)})"}) | |
| tmpl, step, _ = cls.KEYS[key] | |
| spec["events"] += _every(rng, t0, 0, step, params["svc"], "ERROR", tmpl.format(bad=bad)) | |
| return params | |
| def impact(cls, w, params): | |
| s = w["services"][params["svc"]] | |
| if s["config"].get(params["key"]) == params["rec"]: | |
| return {} | |
| slo = s["slo_error_pct"] | |
| return {params["svc"]: {"error_pct": round(slo * random.Random(w["seed"]).uniform(2, 4), 2), "p99_ms": 150}} | |
| def active(cls, w, params): | |
| return w["services"][params["svc"]]["config"].get(params["key"]) != params["rec"] | |
| def solution(cls, w, params): | |
| return [{"action": "set_config", "service": params["svc"], "key": params["key"], | |
| "value": params["rec"]}], f"{cls.NAME}:{params['svc']}" | |
| class DependencyOutage(Fault): | |
| NAME = "dependency_outage" | |
| BASE_WEIGHT = 4 | |
| def plan(cls, rng, fleet, spec): | |
| cands = [s for s in fleet["apis"] + [fleet["gateway"]] | |
| if any(spec["services"][d]["kind"] == "external" for d in spec["services"][s].get("depends", {}))] | |
| if not cands: | |
| return None | |
| caller = rng.choice(cands) | |
| ext_deps = [d for d in spec["services"][caller]["depends"] | |
| if spec["services"][d]["kind"] == "external"] | |
| dep = rng.choice(ext_deps) | |
| return {"svc": caller, "dep": dep} | |
| def apply(cls, spec, params, rng): | |
| dep = spec["services"][params["dep"]] | |
| t0 = -rng.randint(5, 15) | |
| dep["status"] = "down" | |
| params["t0"] = t0 | |
| endpoint = spec["services"][params["svc"]]["config"][f"{params['dep']}.endpoint"] | |
| params["dead"] = endpoint | |
| spec["events"].append({"t": t0, "svc": params["dep"], "level": "ERROR", | |
| "msg": "healthcheck failing: all probes down (0/3 healthy)"}) | |
| spec["events"] += _every(rng, t0, 0, (1, 3), params["svc"], "ERROR", | |
| f"dial tcp {endpoint}: connect: connection refused") | |
| return params | |
| def impact(cls, w, params): | |
| caller = w["services"][params["svc"]] | |
| if caller["config"].get(f"{params['dep']}.endpoint") != params["dead"]: | |
| return {} | |
| slo = caller["slo_error_pct"] | |
| r = random.Random(w["seed"]) | |
| return {params["svc"]: {"error_pct": round(slo * r.uniform(3, 6), 2), "p99_ms": r.randint(200, 500)}} | |
| def active(cls, w, params): | |
| return w["services"][params["svc"]]["config"].get(f"{params['dep']}.endpoint") == params["dead"] | |
| def services(cls, params): | |
| return [params["svc"], params["dep"]] | |
| def alert_svc(cls, params): | |
| return params["svc"] | |
| def solution(cls, w, params): | |
| backup = w["services"][params["svc"]]["depends"][params["dep"]]["backup"] | |
| return [{"action": "set_config", "service": params["svc"], | |
| "key": f"{params['dep']}.endpoint", "value": backup}], f"{cls.NAME}:{params['svc']}" | |
| class CapacityShortfall(Fault): | |
| NAME = "capacity_shortfall" | |
| BASE_WEIGHT = 3 | |
| def plan(cls, rng, fleet, spec): | |
| cands = fleet["apis"] | |
| if not cands: | |
| return None | |
| svc = rng.choice(cands) | |
| per = spec["services"][svc]["runbook"].get("rps_per_replica", 150) | |
| required = math.ceil(spec["services"][svc]["rps"] / per) | |
| return {"svc": svc, "required": required} | |
| def apply(cls, spec, params, rng): | |
| s = spec["services"][params["svc"]] | |
| s["replicas"] = max(1, params["required"] - rng.randint(1, 2)) | |
| t0 = -rng.randint(20, 40) | |
| params["t0"] = t0 | |
| params["error_add"] = round(s["slo_error_pct"] * rng.uniform(1.5, 3.0), 2) | |
| spec["events"].append({"t": t0, "svc": params["svc"], "level": "INFO", | |
| "msg": f"traffic surge +{rng.randint(50, 80)}% (marketing campaign)"}) | |
| spec["events"] += _every(rng, t0, 0, (2, 4), params["svc"], "ERROR", | |
| "503: no healthy upstream available (saturated)") | |
| return params | |
| def impact(cls, w, params): | |
| s = w["services"][params["svc"]] | |
| deficit = 1.0 - s["replicas"] / params["required"] | |
| if deficit <= 0: | |
| return {} | |
| return {params["svc"]: {"error_pct": round(params["error_add"] * (1 + deficit), 2), | |
| "p99_ms": round(100 + 300 * deficit, 1)}} | |
| def active(cls, w, params): | |
| return w["services"][params["svc"]]["replicas"] < params["required"] | |
| def solution(cls, w, params): | |
| return [{"action": "scale", "service": params["svc"], "replicas": params["required"]}], \ | |
| f"{cls.NAME}:{params['svc']}" | |
| class SecretExpiry(Fault): | |
| NAME = "secret_expiry" | |
| BASE_WEIGHT = 3 | |
| def plan(cls, rng, fleet, spec): | |
| cands = fleet["apis"] + [fleet["gateway"]] | |
| return {"svc": rng.choice(cands), "key": "client_cert"} | |
| def apply(cls, spec, params, rng): | |
| s = spec["services"][params["svc"]] | |
| t0 = -rng.randint(5, 30) | |
| s["secrets"][params["key"]]["expires_at_min"] = t0 | |
| params["t0"] = t0 | |
| params["error_add"] = round(s["slo_error_pct"] * rng.uniform(3, 5), 2) | |
| params["p99_add"] = rng.randint(100, 200) | |
| spec["events"] += _every(rng, t0, 0, (2, 4), params["svc"], "ERROR", | |
| "tls: failed to verify certificate: x509: certificate has expired") | |
| return params | |
| def impact(cls, w, params): | |
| if w["services"][params["svc"]]["secrets"][params["key"]]["rotated_at"] is not None: | |
| return {} | |
| return {params["svc"]: {"error_pct": params["error_add"], "p99_ms": params["p99_add"]}} | |
| def active(cls, w, params): | |
| return w["services"][params["svc"]]["secrets"][params["key"]]["rotated_at"] is None | |
| def solution(cls, w, params): | |
| return [{"action": "rotate_secret", "service": params["svc"], "key": params["key"]}], \ | |
| f"{cls.NAME}:{params['svc']}" | |
| class PoisonMessage(Fault): | |
| NAME = "poison_message" | |
| BASE_WEIGHT = 4 | |
| def plan(cls, rng, fleet, spec): | |
| if not fleet["workers"]: | |
| return None | |
| svc = rng.choice(fleet["workers"]) | |
| return {"svc": svc, "queue": spec["services"][svc]["queue"]} | |
| def apply(cls, spec, params, rng): | |
| poison = f"msg_{_hex(rng, 8)}" | |
| q = spec["queues"][params["queue"]] | |
| q["messages"].append({"id": poison, "payload": {"amount": 0, "op": "divide"}, "redeliveries": rng.randint(30, 80)}) | |
| t0 = -rng.randint(10, 25) | |
| params.update(poison=poison, t0=t0) | |
| params["error_add"] = round(spec["services"][params["svc"]]["slo_error_pct"] * rng.uniform(2, 4), 2) | |
| spec["events"] += _every(rng, t0, 0, (3, 5), params["svc"], "ERROR", | |
| f"panic: runtime error: integer divide by zero while processing message {poison}") | |
| spec["events"] += _every(rng, t0, 0, (6, 10), params["svc"], "WARN", | |
| f"consumer restarting (crash loop backoff 30s, message {poison} redelivered)") | |
| return params | |
| def impact(cls, w, params): | |
| q = w["queues"][params["queue"]] | |
| if not any(m["id"] == params["poison"] for m in q["messages"]): | |
| return {} | |
| return {params["svc"]: {"error_pct": params["error_add"], "p99_ms": 80}} | |
| def active(cls, w, params): | |
| return any(m["id"] == params["poison"] for m in w["queues"][params["queue"]]["messages"]) | |
| def solution(cls, w, params): | |
| return [{"action": "peek_queue", "queue": params["queue"]}, | |
| {"action": "purge_message", "queue": params["queue"], "message_id": params["poison"]}], \ | |
| f"{cls.NAME}:{params['svc']}" | |
| class HostFailure(Fault): | |
| NAME = "host_failure" | |
| BASE_WEIGHT = 4 | |
| def plan(cls, rng, fleet, spec): | |
| # pick (svc, host) where the host runs ONLY this managed service | |
| cands = [] | |
| for svc in fleet["apis"] + fleet["workers"] + [fleet["gateway"]]: | |
| for h in spec["services"][svc]["hosts"]: | |
| others = [s2 for s2 in fleet["managed"] if s2 != svc and h in spec["services"][s2]["hosts"]] | |
| if not others: | |
| cands.append((svc, h)) | |
| if not cands: | |
| return None | |
| svc, host = rng.choice(cands) | |
| return {"svc": svc, "host": host} | |
| def apply(cls, spec, params, rng): | |
| spec["hosts"][params["host"]]["healthy"] = False | |
| t0 = -rng.randint(5, 15) | |
| params["t0"] = t0 | |
| spec["events"].append({"t": t0, "svc": params["host"], "level": "ERROR", | |
| "msg": "nvme0: media error detected, device marginal"}) | |
| spec["events"] += _every(rng, t0, 0, (2, 4), params["svc"], "ERROR", | |
| f"{params['host']}: read: connection reset by peer") | |
| return params | |
| def impact(cls, w, params): | |
| # blast radius: every managed service with replicas on the dead host degrades | |
| out = {} | |
| for name, s in w["services"].items(): | |
| if s["kind"] == "external" or params["host"] not in s["hosts"]: | |
| continue | |
| frac = frac_on_host(w, name, params["host"]) | |
| if frac > 0: | |
| out[name] = {"error_pct": round(frac * 30, 2), "p99_ms": round(frac * 400, 1)} | |
| return out | |
| def active(cls, w, params): | |
| return frac_on_host(w, params["svc"], params["host"]) > 0 | |
| def services(cls, params): | |
| return [params["svc"]] | |
| def solution(cls, w, params): | |
| return [{"action": "drain_host", "host": params["host"]}], f"{cls.NAME}:{params['svc']}" | |
| # ---------------------------------------------------------------- decoys | |
| class Decoy: | |
| def impact(cls, w, params): | |
| return {} | |
| def apply(cls, spec, params, rng): | |
| return params | |
| class IrrelevantDeploy(Decoy): | |
| def plan(cls, rng, fleet, spec, avoid): | |
| cands = [s for s in fleet["managed"] if s not in avoid] | |
| if not cands: | |
| return None | |
| svc = rng.choice(cands) | |
| v = _bump_version(spec["services"][svc]["deploys"][-1]["version"]) | |
| return {"svc": svc, "version": v, "t": -rng.randint(5, 25)} | |
| def apply(cls, spec, params, rng): | |
| spec["services"][params["svc"]]["deploys"].append( | |
| {"version": params["version"], "t": params["t"], "by": "ci"}) | |
| return params | |
| class KnownIssue(Decoy): | |
| def plan(cls, rng, fleet, spec, avoid): | |
| cands = [s for s in fleet["managed"] if s not in avoid] | |
| if not cands: | |
| return None | |
| return {"svc": rng.choice(cands), "ticket": f"OPS-{rng.randint(1000, 1999)}"} | |
| def apply(cls, spec, params, rng): | |
| spec["events"] += _every(rng, -rng.randint(120, 200), 0, (4, 9), params["svc"], "WARN", | |
| f"upstream latency spikes (known issue {params['ticket']}, retries succeed, no action)") | |
| return params | |
| class CosmeticSlow(Decoy): | |
| def plan(cls, rng, fleet, spec, avoid): | |
| cands = [s for s in fleet["managed"] if s not in avoid] | |
| if not cands: | |
| return None | |
| return {"svc": rng.choice(cands), "p99_add": rng.randint(40, 90)} | |
| def impact(cls, w, params): | |
| return {params["svc"]: {"p99_ms": params["p99_add"]}} | |
| def apply(cls, spec, params, rng): | |
| spec["events"].append({"t": -rng.randint(10, 60), "svc": params["svc"], "level": "WARN", | |
| "msg": "p99 elevated on /v1/suggest (investigating, within SLO)"}) | |
| return params | |
| FAULT_TYPES = {c.NAME: c for c in [BadDeploy, MemoryLeak, ConfigDrift, DependencyOutage, | |
| CapacityShortfall, SecretExpiry, PoisonMessage, HostFailure]} | |
| DECOY_TYPES = {c.__name__: c for c in [IrrelevantDeploy, KnownIssue, CosmeticSlow]} | |
| DECOY_ALIASES = {"irrelevant_deploy": IrrelevantDeploy, "known_issue": KnownIssue, "cosmetic_slow": CosmeticSlow} | |