"""World model: builds runtime state from a task spec, derives metrics deterministically. Everything the agent observes is derived from state. There are no scripted metric curves: fix the state and the metrics follow. Randomness is seeded and stable across processes (no builtin hash()). """ from __future__ import annotations import copy import hashlib import json def stable_hash(*parts) -> int: h = hashlib.sha256("|".join(str(p) for p in parts).encode("utf-8")).digest() return int.from_bytes(h[:8], "big") def build_world(spec: dict) -> dict: """Deep-copy the static spec into a mutable runtime world.""" w = copy.deepcopy(spec) w["t"] = 0.0 # minutes since sim start; alert fires at t=0 w["restarts"] = {} w["report"] = None w["drained_hosts"] = [] for name, svc in w["services"].items(): svc["initial_replicas"] = svc["replicas"] svc["initial_version"] = svc["deploys"][-1]["version"] svc["initial_config"] = copy.deepcopy(svc["config"]) return w def current_version(w: dict, svc: str) -> str: return w["services"][svc]["deploys"][-1]["version"] def replicas_on_host(w: dict, svc: str, host: str) -> int: hosts = w["services"][svc]["hosts"] if not hosts: return 0 # replicas are distributed round-robin over the host list total = w["services"][svc]["replicas"] if host not in hosts: return 0 return total // len(hosts) + (1 if hosts.index(host) < total % len(hosts) else 0) def frac_on_host(w: dict, svc: str, host: str) -> float: total = w["services"][svc]["replicas"] if total == 0: return 0.0 return replicas_on_host(w, svc, host) / total def contributions(w: dict) -> list[tuple[str, dict]]: """Yield (label, {svc: {error_pct, p99_ms, mem_pct}}) for every fault and decoy.""" from . import faults as F out = [] for f in w["faults"]: cls = F.FAULT_TYPES[f["type"]] out.append((f["type"], cls.impact(w, f["params"]))) for d in w["decoys"]: cls = F.DECOY_ALIASES[d["type"]] out.append(("decoy:" + d["type"], cls.impact(w, d["params"]))) return out def agg(w: dict, svc: str, key: str) -> float: total = 0.0 for _, contrib in contributions(w): total += contrib.get(svc, {}).get(key, 0.0) return total def metrics(w: dict, svc: str) -> dict: s = w["services"][svc] seed = w["seed"] err = s["base_error_pct"] + agg(w, svc, "error_pct") err += (stable_hash(seed, svc, w["t"] // 5, "err") % 100) / 10000.0 p99 = s["base_p99_ms"] + agg(w, svc, "p99_ms") p99 += (stable_hash(seed, svc, w["t"] // 5, "p99") % 100) / 10.0 per_replica = s["runbook"].get("rps_per_replica", 150) cpu = 70.0 * s["rps"] / max(1, s["replicas"] * per_replica) cpu = min(99.0, cpu) + (stable_hash(seed, svc, "cpu") % 50) / 10.0 mem = 30.0 + agg(w, svc, "mem_pct") mem = min(99.0, mem) if s["kind"] == "external": return {"status": s.get("status", "up")} return { "error_pct": round(err, 3), "p99_ms": round(p99, 1), "cpu_pct": round(cpu, 1), "mem_pct": round(mem, 1), "rps": s["rps"], "slo_error_pct": s["slo_error_pct"], "degraded": err > s["slo_error_pct"], } def per_host_metrics(w: dict, svc: str) -> dict: out = {} base = w["services"][svc]["base_error_pct"] for h in w["services"][svc]["hosts"]: if h in w["drained_hosts"] or not w["hosts"][h]["healthy"]: e = 55.0 else: e = base + agg(w, svc, "error_pct") out[h] = {"replicas": replicas_on_host(w, svc, h), "error_pct": round(e, 2)} return out def fmt_clock(w: dict, t: float | None = None) -> str: t = w["t"] if t is None else t total = int(round(t)) hh, mm = 9 + (total // 60) % 24, total % 60 return f"{hh:02d}:{mm:02d}" def log(w: dict, svc: str, level: str, msg: str) -> None: w["events"].append({"t": round(w["t"], 1), "svc": svc, "level": level, "msg": msg}) def to_json(obj) -> str: return json.dumps(obj, ensure_ascii=False, separators=(",", ":")) def is_managed(w: dict, svc: str) -> bool: s = w["services"].get(svc) return bool(s and s["kind"] != "external")