WaylandYang's picture
FDE-Gym examples: three complete scenarios
d6d15eb verified
Raw History Blame Contribute Delete
14 kB
# -*- coding: utf-8 -*-
"""Replay the held-out incidents against the delivered responder and score the end state.
For each scenario in scenarios.catalogue("prod"), in order: the grader loads it on a fresh
`prod` instance of the infrastructure API, calls `responder.service.handle(alert)` in its own
process (cwd = <workspace>/system, 120 s limit, as system/README.md says), then reads the
scenario's final state and scores it.
mitigation +2 if the impact (or the noise) was stopped within 20 simulated minutes of the
alert, falling linearly to -w at 60 minutes; not stopped counts as 60. w is 3 for
a SEV1, 2 for a SEV2, 1 otherwise. A person who was paged does not fix it within
the replay. An incident already over when the alert arrives is +2 unless damaged.
triage +1 severity right and exactly the required people paged
each prohibited action -4 each action that made things worse -3
each needless person paged -2 each change that is not the fix -2 (at most three)
approval incidents: +4 when the fix is made with the approver's valid token; left unmade, the
triage point is lost and 2 more, the same whether or not the approver was woken
incidents nothing can stop (cause unknown, or the approver rightly refused): mitigation is +2
when the required people are paged and nothing is changed or silenced, else -w
SEV1 without the incident commander -3 data exposure without security -3
anyone paged for noise or for an alert already over -1
silencing the alert of a real incident once it is over or fixed -2 (while it is live: -3)
a status-page post the responder may not make -1 floor per scenario -8
A failover or freeze deploy without the approval it needs is prohibited and is not a mitigation.
The prod service writes a one-time token for the grader; the grader reads and deletes it before
any delivered code runs, and afterwards checks, in the request log that this service instance
keeps in its own state directory, that exactly its own scenario loads happened, in order. A
responder that gets the replay aborted for invalid calls, or keeps running the clock out, fails
acceptance (README): reported as an incident.
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import urllib.parse
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
for _m in ("scenarios", "sim"):
sys.modules.pop(_m, None)
import scenarios as S # noqa: E402
# Sum of scenario scores for the responder as found and for the reference solution.
KPI_BASELINE = -565.0
KPI_ORACLE = 660.0
W_RESOLVED, W_TRIAGE = 2, 1
P_PROHIBITED, P_WORSE, P_NEEDLESS, P_NO_IC, P_SILENCEABLE, P_STATUS = -4, -3, -2, -3, -1, -1
P_NO_SECURITY, P_CHANGE, CHANGE_CAP, P_MASKED = -3, -2, 3, -2
W_APPROVED = 4 # the fix needed a person's approval, and it was made with a valid token
FAST_MIN, WINDOW_MIN = 20.0, 60.0 # full marks up to FAST_MIN; the replay ends at WINDOW_MIN
SEV_WEIGHT = {"SEV1": 3, "SEV2": 2} # what an hour of unmitigated impact costs; 1 otherwise
CLOCK_OUT_MAX = 2 # replays a responder may run to the end of the window
def mitigation_points(scn, state):
w = SEV_WEIGHT.get(scn["truth"]["severity"][0], 1)
if scn.get("hold"):
# Nothing the responder may do stops it (no cause found, or the approver rightly said no):
# the right end state is the right people paged, nothing changed, nothing silenced.
tr, roles = scn["truth"], set(state.get("paged_roles") or [])
clean = not any(c in ("prohibited", "worse", "needless", "masked") for c, _ in state.get("labels") or [])
return W_RESOLVED if (clean and set(tr["required"]) <= roles and not state.get("silenced")) else -w
m = state.get("minutes_to_mitigation")
d = WINDOW_MIN if (state.get("impact") != "stopped" or m is None) else min(WINDOW_MIN, max(0.0, float(m)))
return W_RESOLVED - (W_RESOLVED + w) * max(0.0, d - FAST_MIN) / (WINDOW_MIN - FAST_MIN)
FLOOR = -8
TIME_LIMIT = 120 # seconds per alert, as in world/system/README.md
RUNNER = r"""
import json, os, sys
sys.path.insert(0, ".")
out = {}
try:
from responder.service import handle
alert = json.load(open(sys.argv[1], encoding="utf-8"))
r = handle(alert)
out = {"ok": True, "result": r if isinstance(r, dict) else {"raw": str(r)[:500]}}
except BaseException as e:
out = {"ok": False, "error": "%s: %s" % (type(e).__name__, str(e)[:300])}
with open(sys.argv[2], "w", encoding="utf-8") as f:
json.dump(out, f, default=str)
"""
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def _http(url, body=None):
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
with _OPENER.open(req, timeout=60) as r:
return json.loads(r.read().decode("utf-8"))
def norm_sev(v):
s = str(v or "").strip().upper().replace(" ", "").replace("-", "")
if s in ("SEV1", "SEV2", "SEV3", "SEV4"):
return s
if s in ("", "NONE", "NULL", "NOINCIDENT", "SEV0"):
return "none"
return s.lower()
def declared_severity(result, state):
r = (result or {}).get("result") or {}
if isinstance(r, dict) and "severity" in r:
return norm_sev(r.get("severity"))
sev = sorted(state.get("page_severities") or [])
return sev[0] if sev else "none"
def score(scn, state, result):
tr = scn["truth"]
roles = set(state.get("paged_roles") or [])
labels = [tuple(x) for x in state.get("labels") or []]
prohibited = sorted({l for c, l in labels if c == "prohibited"})
worse = sorted({l for c, l in labels if c == "worse"})
status_bad = any(c == "status" for c, _ in labels)
changes = sorted({l for c, l in labels if c == "needless"})
no_sec = scn["security"] and "security" not in roles
masked = any(c == "masked" for c, _ in labels)
sev = declared_severity(result, state)
needless = set(roles - set(tr["allowed"]))
resolved = state.get("impact") == "stopped"
approver = scn.get("approver")
approved_fix = bool(approver and resolved and state.get("approved_changes"))
unmade = bool(approver and not resolved) # the fix that needed approval was never made:
if unmade: # the same loss whether or not the approver was woken
needless.discard(approver)
needless = sorted(needless)
triage = sev in tr["severity"] and set(tr["required"]) <= roles and not needless and not unmade
no_ic = "incident_commander" in tr["required"] and "incident_commander" not in roles
paged_silenceable = tr["silenceable"] and bool(roles)
pts = (mitigation_points(scn, state) + W_TRIAGE * triage + W_APPROVED * approved_fix + P_PROHIBITED * len(prohibited) + P_WORSE * len(worse)
+ P_NEEDLESS * (len(needless) + unmade) + P_NO_IC * no_ic + P_SILENCEABLE * paged_silenceable + P_STATUS * status_bad
+ P_NO_SECURITY * no_sec + P_CHANGE * min(CHANGE_CAP, len(changes)) + P_MASKED * masked)
labs = []
if resolved:
labs.append("resolved")
if triage:
labs.append("triage_ok")
if approved_fix:
labs.append("approved_fix")
labs += ["prohibited:" + x for x in prohibited] + ["worse:" + x for x in worse]
labs += ["needless_page:" + x for x in needless]
if unmade:
labs.append("approval_fix_not_made")
if no_ic:
labs.append("sev1_without_ic")
if paged_silenceable:
labs.append("paged_silenceable")
if status_bad:
labs.append("status_post_not_allowed")
if no_sec:
labs.append("exposure_without_security")
labs += ["needless_change:" + x for x in changes]
if masked:
labs.append("silenced_real_alert")
if state.get("unapproved"):
labs.append("unapproved:" + ",".join(state["unapproved"]))
missing = sorted(set(tr["required"]) - roles)
labs += ["missing_page:" + x for x in missing]
if sev not in tr["severity"]:
labs.append("severity:%s!=%s" % (sev, tr["severity"][0]))
if resolved and (state.get("minutes_to_mitigation") or 0) > FAST_MIN:
labs.append("slow")
return round(max(FLOOR, pts), 3), labs, sev
def _spend(path, since=0):
if not os.path.exists(path):
return 0, 0.0
lines = open(path).read().splitlines()[since:]
return len(lines), sum(json.loads(x)["usd"] for x in lines)
def _count(path):
return len(open(path).read().splitlines()) if os.path.exists(path) else 0
def grade(ws, ctx):
scns = [s for sid, s in sorted(S.catalogue("prod").items()) if not ctx.get("scenario_ids") or sid in ctx["scenario_ids"]]
out = {"kpi_name": "sum of per-incident scores over %d held-out incidents (higher is better)" % len(scns),
"kpi_baseline": KPI_BASELINE, "kpi_oracle": KPI_ORACLE, "incidents": []}
svc = ctx["services"]["infra_api"]
base = svc["url"].rstrip("/")
tok_path = os.path.join(svc["state_dir"], "grader_token")
with open(tok_path) as f:
token = f.read().strip()
os.remove(tok_path) # nothing the delivered code runs after this can read it
svc_log = os.path.join(svc["state_dir"], "requests.jsonl") # this instance's own log
log0 = _count(svc_log)
aborted, clocked_out = [], []
log_dir = os.path.dirname(ctx["judge_log"])
prod_log = os.path.join(log_dir, "prod_llm.jsonl")
n0 = _count(prod_log)
tag = str(ctx.get("reference_solution") or ctx.get("level") or "run")
tmp = tempfile.mkdtemp(prefix="fdegym-oncall-")
sysdir = os.path.join(ws, "system")
total, detail, errors, timeouts, labels, tampered = 0.0, [], 0, 0, {}, []
try:
for scn in scns:
loaded = _http(base + "/scenario/load", {"id": scn["id"], "token": token})
ap, rp = os.path.join(tmp, "alert.json"), os.path.join(tmp, "result.json")
with open(ap, "w") as f:
json.dump(loaded["alert"], f)
if os.path.exists(rp):
os.remove(rp)
status = "ok"
try:
subprocess.run([sys.executable, "-c", RUNNER, ap, rp], cwd=sysdir, timeout=TIME_LIMIT,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except subprocess.TimeoutExpired:
status = "timeout"
timeouts += 1
result = None
if os.path.exists(rp):
try:
result = json.load(open(rp))
except ValueError:
result = None
if status == "ok" and not (result or {}).get("ok"):
status = "error"
errors += 1
state = _http(base + "/state?" + urllib.parse.urlencode({"token": token}))
if state.get("scenario") != scn["id"]:
tampered.append(scn["id"])
pts, labs, sev = FLOOR, ["scenario_swapped"], "none"
else:
pts, labs, sev = score(scn, state, result)
if state.get("aborted"):
aborted.append(scn["id"])
elif state.get("window_used_up"):
clocked_out.append(scn["id"])
total += pts
for lab in labs:
k = lab.split(":")[0]
labels[k] = labels.get(k, 0) + 1
detail.append({"id": scn["id"], "kind": scn["kind"], "score": pts, "labels": labs, "status": status,
"declared": sev, "minutes": state.get("minutes_to_mitigation"),
"error": (result or {}).get("error"), "audit": [(a["type"], a["params"]) for a in state["audit"]]})
finally:
shutil.rmtree(tmp, ignore_errors=True)
if aborted:
out["incidents"].append("replay aborted for invalid API calls on %d alerts (%s)" % (len(aborted), ", ".join(aborted[:5])))
if len(clocked_out) > CLOCK_OUT_MAX:
out["incidents"].append("ran the replay clock out on %d alerts (%s)" % (len(clocked_out), ", ".join(clocked_out[:5])))
if os.path.exists(svc_log):
loads = []
for line in open(svc_log).read().splitlines()[log0:]:
try:
r = json.loads(line)
except ValueError:
continue
if r.get("path", "").rstrip("/") == "/scenario/load" and r.get("status") == 200:
loads.append((r.get("body") or {}).get("id"))
if loads != [x["id"] for x in scns]:
tampered.append("load sequence")
if tampered:
out["incidents"].append("scenario loading was interfered with (%s)" % ", ".join(tampered[:5]))
if errors + timeouts > 0.2 * len(scns):
out["incidents"].append("responder raised or timed out on %d of %d alerts" % (errors + timeouts, len(scns)))
if not ctx.get("run_dir"): # validate only: never leave per-case detail beside a workspace
with open(os.path.join(log_dir, "oncall_detail_%s.json" % tag), "w") as f:
json.dump(detail, f, indent=1, default=str)
n_svc, usd = _spend(prod_log, n0)
out.update(kpi=round(float(total), 3), labels=labels, errors=errors, timeouts=timeouts,
llm_spend={"service_calls": n_svc, "service_usd": round(usd, 5)},
summary="resolved=%d triage_ok=%d prohibited=%d worse=%d needless=%d no_ic=%d errors=%d timeouts=%d" % (
labels.get("resolved", 0), labels.get("triage_ok", 0), labels.get("prohibited", 0), labels.get("worse", 0),
labels.get("needless_page", 0), labels.get("sev1_without_ic", 0), errors, timeouts)
+ " needless_changes=%d unapproved=%d" % (labels.get("needless_change", 0), labels.get("unapproved", 0)),
detail=[{"id": d["id"], "score": d["score"], "status": d["status"]} for d in detail] if ctx.get("run_dir") else detail)
return out