File size: 12,687 Bytes
6655381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""Episode environment: the action API an on-call agent operates through.



Read actions are free-form queries. Mutation actions change world state and

advance the simulated clock. The episode ends when the agent submits a report

or exhausts its action budget.

"""
from __future__ import annotations

import json

from . import world as W
from . import faults as F


PROMPT_VERSION = "v1"

ACTIONS_DOC = """Actions (send one JSON object per turn):



  {"action":"list_services"}

  {"action":"get_service","service":"<name>"}

  {"action":"get_metrics","service":"<name>"}

  {"action":"get_deploys","service":"<name>"}

  {"action":"get_runbook","service":"<name>"}

  {"action":"query_logs","service":"<name>","level":"ERROR|WARN|INFO","contains":"<substring>","limit":30}

  {"action":"restart","service":"<name>"}

  {"action":"rollback","service":"<name>"}

  {"action":"set_config","service":"<name>","key":"<key>","value":<json value>}

  {"action":"scale","service":"<name>","replicas":<int>}

  {"action":"rotate_secret","service":"<name>","key":"<key>"}

  {"action":"peek_queue","queue":"<name>"}

  {"action":"purge_message","queue":"<name>","message_id":"<id>"}

  {"action":"drain_host","host":"<name>"}

  {"action":"submit_report","cause":"<fault_type>:<service>","fix_summary":"<one line>"}



Rules: you have a limited action budget. All actions count, including reads.

End the episode with submit_report. `cause` must be "<fault_type>:<service>",

where fault_type is exactly one of:

  bad_deploy, memory_leak, config_drift, dependency_outage,

  capacity_shortfall, secret_expiry, poison_message, host_failure

and service is the PRIMARY affected service (the one whose fault it is).

"""


class Episode:
    def __init__(self, task: dict):
        self.task = task
        self.w = W.build_world(task["spec"])
        self.budget = task["budget"]
        self.used = 0
        self.done = False
        self.mutations_on_unrelated = 0

    # ------------------------------------------------------------ helpers

    def _obs(self, obj) -> str:
        return W.to_json(obj)

    def _err(self, msg: str) -> str:
        return self._obs({"error": msg})

    def _spend(self, n: float = 1.0) -> bool:
        self.used += 1
        self.w["t"] += n
        if self.used >= self.budget:
            self.done = True
        return self.done

    def _managed(self, svc) -> str | None:
        if svc not in self.w["services"]:
            return f"unknown service '{svc}'"
        if self.w["services"][svc]["kind"] == "external":
            return f"'{svc}' is an external dependency; it is not managed by you"
        return None

    def _fault_services(self) -> set:
        out = set()
        for f in self.w["faults"]:
            out |= set(F.FAULT_TYPES[f["type"]].services(f["params"]))
        return out

    # ------------------------------------------------------------ actions

    def step(self, action: dict) -> str:
        if self.done:
            return self._err("episode already ended")
        name = action.get("action")
        fn = getattr(self, "act_" + str(name), None)
        if fn is None:
            return self._err(f"unknown action '{name}'")
        try:
            obs = fn(action)
        except (KeyError, TypeError, ValueError) as e:
            return self._err(f"bad arguments for '{name}': {e}")
        return obs

    def act_list_services(self, a):
        self._spend(0.2)
        rows = []
        for name, s in self.w["services"].items():
            if s["kind"] == "external":
                rows.append({"name": name, "kind": s["kind"], "status": s.get("status", "up")})
            else:
                m = W.metrics(self.w, name)
                rows.append({"name": name, "kind": s["kind"], "replicas": s["replicas"],
                             "error_pct": m["error_pct"], "p99_ms": m["p99_ms"],
                             "degraded": m["degraded"]})
        return self._obs({"services": rows})

    def act_get_service(self, a):
        self._spend(0.2)
        svc = a["service"]
        if svc not in self.w["services"]:
            return self._err(f"unknown service '{svc}'")
        s = self.w["services"][svc]
        hosts = {h: {"healthy": self.w["hosts"][h]["healthy"] and h not in self.w["drained_hosts"],
                     "region": self.w["hosts"][h]["region"],
                     "replicas": W.replicas_on_host(self.w, svc, h)}
                 for h in s["hosts"]}
        secrets = {k: dict(v) for k, v in s.get("secrets", {}).items()}
        return self._obs({"name": svc, "kind": s["kind"], "version": W.current_version(self.w, svc),
                          "replicas": s["replicas"], "hosts": hosts, "config": s["config"],
                          "depends": s.get("depends", {}), "secrets": secrets})

    def act_get_metrics(self, a):
        self._spend(0.2)
        svc = a["service"]
        if svc not in self.w["services"]:
            return self._err(f"unknown service '{svc}'")
        m = W.metrics(self.w, svc)
        if self.w["services"][svc]["kind"] != "external":
            m["per_host"] = W.per_host_metrics(self.w, svc)
        return self._obs(m)

    def act_get_deploys(self, a):
        self._spend(0.2)
        svc = a["service"]
        if svc not in self.w["services"]:
            return self._err(f"unknown service '{svc}'")
        return self._obs({"deploys": self.w["services"][svc]["deploys"]})

    def act_get_runbook(self, a):
        self._spend(0.2)
        svc = a["service"]
        if svc not in self.w["services"]:
            return self._err(f"unknown service '{svc}'")
        return self._obs(self.w["services"][svc]["runbook"])

    def act_query_logs(self, a):
        self._spend(0.2)
        svc = a.get("service")
        limit = int(a.get("limit", 30))
        level = a.get("level")
        contains = a.get("contains")
        rows = [e for e in self.w["events"]
                if (svc is None or e["svc"] == svc)
                and (level is None or e["level"] == level)
                and (contains is None or contains.lower() in e["msg"].lower())]
        rows.sort(key=lambda e: -e["t"])
        return self._obs({"events": rows[:limit], "total": len(rows)})

    def act_restart(self, a):
        e = self._managed(a.get("service"))
        if e:
            return self._err(e)
        svc = a["service"]
        self.w["restarts"][svc] = self.w["t"]
        W.log(self.w, svc, "INFO", f"rolling restart initiated by oncall ({self.w['services'][svc]['replicas']} replicas)")
        done = self._spend(2)
        return self._obs({"ok": True, "restarted": svc, "episode_ended": done})

    def act_rollback(self, a):
        e = self._managed(a.get("service"))
        if e:
            return self._err(e)
        svc = a["service"]
        dep = self.w["services"][svc]["deploys"]
        if len(dep) < 2:
            return self._err(f"no previous version for '{svc}'")
        prev = dep[-2]["version"]
        dep.append({"version": prev, "t": round(self.w["t"]), "by": "oncall-rollback"})
        W.log(self.w, svc, "INFO", f"rollback to {prev} initiated by oncall")
        done = self._spend(5)
        return self._obs({"ok": True, "version": prev, "episode_ended": done})

    def act_set_config(self, a):
        e = self._managed(a.get("service"))
        if e:
            return self._err(e)
        svc = a["service"]
        s = self.w["services"][svc]
        key, value = a.get("key"), a.get("value")
        allowed = set(s["config"]) | set(s["runbook"].get("recommended", {})) \
            | {f"{d}.endpoint" for d in s.get("depends", {})}
        if key not in allowed:
            return self._err(f"unknown config key '{key}' for '{svc}'")
        old = s["config"].get(key)
        s["config"][key] = value
        W.log(self.w, svc, "INFO", f"config {key}: {old} -> {value} (oncall)")
        done = self._spend(1)
        return self._obs({"ok": True, "key": key, "old": old, "new": value, "episode_ended": done})

    def act_scale(self, a):
        e = self._managed(a.get("service"))
        if e:
            return self._err(e)
        svc = a["service"]
        n = a.get("replicas")
        if not isinstance(n, int) or not 1 <= n <= 40:
            return self._err("replicas must be an integer in [1, 40]")
        old = self.w["services"][svc]["replicas"]
        self.w["services"][svc]["replicas"] = n
        W.log(self.w, svc, "INFO", f"scaled {old} -> {n} by oncall")
        done = self._spend(3)
        return self._obs({"ok": True, "replicas": n, "episode_ended": done})

    def act_rotate_secret(self, a):
        e = self._managed(a.get("service"))
        if e:
            return self._err(e)
        svc, key = a["service"], a.get("key", "client_cert")
        s = self.w["services"][svc]
        if key not in s.get("secrets", {}):
            return self._err(f"no secret '{key}' on '{svc}'")
        s["secrets"][key]["rotated_at"] = round(self.w["t"], 1)
        W.log(self.w, svc, "INFO", f"secret '{key}' rotated by oncall")
        done = self._spend(2)
        return self._obs({"ok": True, "rotated": key, "episode_ended": done})

    def act_peek_queue(self, a):
        q = a.get("queue")
        if q not in self.w["queues"]:
            return self._err(f"unknown queue '{q}'")
        self._spend(0.2)
        msgs = [{"id": m["id"], "payload": m["payload"], "redeliveries": m["redeliveries"]}
                for m in self.w["queues"][q]["messages"][:50]]
        return self._obs({"queue": q, "depth": len(self.w["queues"][q]["messages"]),
                          "messages": msgs})

    def act_purge_message(self, a):
        q, mid = a.get("queue"), a.get("message_id")
        if q not in self.w["queues"]:
            return self._err(f"unknown queue '{q}'")
        msgs = self.w["queues"][q]["messages"]
        before = len(msgs)
        self.w["queues"][q]["messages"] = [m for m in msgs if m["id"] != mid]
        if len(msgs) == before:
            return self._err(f"message '{mid}' not found in '{q}'")
        W.log(self.w, q, "INFO", f"message {mid} purged by oncall")
        done = self._spend(1)
        return self._obs({"ok": True, "purged": mid, "episode_ended": done})

    def act_drain_host(self, a):
        h = a.get("host")
        if h not in self.w["hosts"]:
            return self._err(f"unknown host '{h}'")
        if h in self.w["drained_hosts"]:
            return self._err(f"host '{h}' already drained")
        survivors = [h2 for h2 in self.w["hosts"] if h2 != h and self.w["hosts"][h2]["healthy"]]
        if not survivors:
            return self._err("cannot drain the last healthy host")
        moved = {}
        for svc, s in self.w["services"].items():
            if s["kind"] == "external" or h not in s["hosts"]:
                continue
            s["hosts"] = [h2 for h2 in s["hosts"] if h2 != h] + [survivors[0]] \
                if s["hosts"] == [h] else [h2 for h2 in s["hosts"] if h2 != h]
            if not s["hosts"]:
                s["hosts"] = [survivors[0]]
            moved[svc] = s["replicas"]
        self.w["drained_hosts"].append(h)
        W.log(self.w, h, "INFO", f"host drained by oncall; migrated: {moved}")
        done = self._spend(6)
        return self._obs({"ok": True, "drained": h, "migrated": moved, "episode_ended": done})

    def act_submit_report(self, a):
        cause = a.get("cause", "")
        if ":" not in str(cause):
            return self._err("cause must be '<fault_type>:<service>'")
        self.w["report"] = {"cause": str(cause), "fix_summary": str(a.get("fix_summary", ""))[:500]}
        self.done = True
        return self._obs({"ok": True, "report": self.w["report"], "episode_ended": True})

    # ------------------------------------------------------------ prompt

    def system_prompt(self) -> str:
        return (
            "You are a senior on-call engineer. An alert page just fired:\n\n"
            f"ALERT: {self.task['alert']}\n\n"
            "You operate a simulated production fleet through the action API below. "
            "Diagnose the root cause, apply the minimal correct mitigation, and submit a report. "
            "Do not change anything unrelated to the incident: every unnecessary mutation is "
            "scored against you. Budget: " + str(self.budget) + " actions (reads count).\n\n"
            + ACTIONS_DOC
        )