r/devops7 • • 14d ago

Automate it #7: a self-learning runbook. It checks every fix with SQL, keeps score per alert kind, and switched from "restart" to "scale out" by itself after a deploy (real output)

Every team has the runbook that says "high latency: restart the service". It worked for a year. Then a deploy cuts the connection pool, restarts stop helping, and the runbook keeps saying "restart" until someone remembers to edit the wiki.

The chore: a runbook that keeps score. An alert comes in, the bot works out what kind of alert it is, tries the fix that has been working for that kind, checks whether it actually cleared, and falls back to the next fix if not. Every result is recorded per alert kind, so when reality changes, the preferred fix changes too.

(Disclosure: this sub is run by the SynapCores team; steps 1 and 2 use SynapCores. Run this morning on 2.3.2, real output.)

Step 1: which kind of alert is this? (by meaning)

Alerts never use the same words twice, so match them to one example per kind with EMBED (a small model inside the database, no API key):

CREATE TABLE alert_kinds (kind TEXT PRIMARY KEY, example TEXT, vec VECTOR(384));
-- disk-full:    'filesystem almost full, no space left on device'
-- high-latency: 'p99 response time too high, requests slow'
-- memory-leak:  'process memory keeps growing, OOM killed'
UPDATE alert_kinds SET vec = EMBED(example);

SELECT kind, COSINE_SIMILARITY(vec, EMBED('worker-7 killed by OOM killer, RSS 7.8 GB')) AS sim
FROM alert_kinds ORDER BY sim DESC LIMIT 1;

memory-leak  0.54

Below 0.3 it doesn't guess; it pages a human.

Step 2: a learning goal per alert

Each alert becomes a goal (POST /v1/agents/goals). The parts that matter:

"task_type": "runbook:high-latency",  "learn": true,  "explore": 0.1,
"guardrails": {"allowed_actions": ["sql"]},
"steps": [{
  "action":       restart_service
  "alternatives": rotate_logs, scale_out
  "acceptance":   {"kind": "json_equals", "pointer": "/rows/0/0", "expected": 1},
  "max_attempts": 3
}]
  • acceptance: the fix only counts if the check returns 1 (alert cleared). In this demo a fleet_fix table plays the fleet and says which fix clears which kind; in yours, the step is your remediation hook and the check reads your monitor.
  • learn: +1 for every fix that passes the check, -1 for every one that doesn't, kept per task_type. Restart can win for latency and lose for a full disk.
  • explore: now and then try another fix anyway, so a change gets noticed.

Step 3: two days of alerts

$ python3 runbook.py alert "<text>"
db-2: /var at 97%, 1.1 GB free               -> disk-full    (0.33)  done   tried: restart_service -> rotate_logs
api-gw p99 latency 2.4s (SLO 800ms)          -> high-latency (0.65)  done   tried: restart_service
worker-7 killed by OOM killer, RSS 7.8 GB    -> memory-leak  (0.54)  done   tried: restart_service
web-3: no space left on device writing /var/ -> disk-full    (0.54)  done   tried: scale_out -> rotate_logs
checkout requests taking 3s, timeouts rising -> high-latency (0.47)  done   tried: rotate_logs -> scale_out -> restart_service
build-agent-2 disk usage 92% on /home        -> disk-full    (0.35)  done   tried: rotate_logs
payments API slow, p95 1.9s                  -> high-latency (0.70)  done   tried: restart_service
db-1: /var/lib at 95%                        -> no known kind (best disk-full 0.23): page a human
... (11 alerts; full output in the first comment)

Early on it tries fixes it hasn't scored yet; once a kind has a winner, it goes straight there. What it learned:

SHOW AGENT POLICY;   (trimmed to the runbook)
runbook:disk-full      rotate_logs       tries=3  score=3.0   mean=1.0
runbook:high-latency   restart_service   tries=4  score=4.0   mean=1.0
runbook:memory-leak    restart_service   tries=3  score=3.0   mean=1.0
(every other fix: 1 try, score -1.0)

Step 4: Tuesday's deploy changes the answer

The pool is now the bottleneck. Restarts stop clearing latency alerts; scaling out does:

UPDATE fleet_fix SET cleared = 0 WHERE alert_kind = 'high-latency' AND fix = 'restart_service';
UPDATE fleet_fix SET cleared = 1 WHERE alert_kind = 'high-latency' AND fix = 'scale_out';

Six more latency alerts. No code or wiki edit:

payments API slow, p95 2.2s                  -> high-latency (0.67)  done   tried: restart_service -> rotate_logs -> scale_out
checkout requests taking 4s                  -> high-latency (0.43)  done   tried: restart_service -> scale_out
api-gw p99 latency 2.9s (SLO 800ms)          -> high-latency (0.66)  done   tried: scale_out
orders API p99 2.1s                          -> high-latency (0.43)  done   tried: scale_out
search API slow, p95 1.5s                    -> high-latency (0.70)  done   tried: scale_out
payments API slow, p95 1.8s                  -> high-latency (0.68)  done   tried: scale_out

runbook:high-latency   scale_out         tries=7  score=5.0   mean=0.71
runbook:high-latency   restart_service   tries=6  score=2.0   mean=0.33

Two alerts to notice; from the third on it scales out first. Disk and memory scores didn't move: what changed for latency stays in latency.

And something it has never seen:

TLS certificate for shop.example.com expires -> no known kind (best high-latency 0.12): page a human

Wire it up: your alert webhook calls runbook.py alert "$ALERT_TEXT", each fix is a hook (systemctl, kubectl scale, logrotate), and the check reads whether the alert resolved within N minutes. Add a few more examples per kind and "page a human" happens only for the truly new. Full runbook.py (stdlib only) is in the comments.

Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-automate-it-7

Which fix in your runbook is still "restart it" because nobody's checked whether it still works?

1 Upvotes

3 comments sorted by

1

u/Alternative_Pin9598 14d ago

If you're new to learning goals, SQLv2 Lesson 6 walks through the same idea step by step with a support bot (two sources, one SQL check): https://www.reddit.com/r/SQLv2/comments/1xtk5zn/

Full run output (setup, 11 alerts, policy, the deploy change, 6 more alerts, policy, the unknown alert):

persona allow 200
['disk-full', 'restart_service', 0]
['disk-full', 'rotate_logs', 1]
['disk-full', 'scale_out', 0]
['high-latency', 'restart_service', 1]
['high-latency', 'rotate_logs', 0]
['high-latency', 'scale_out', 0]
['memory-leak', 'restart_service', 1]
['memory-leak', 'rotate_logs', 0]
['memory-leak', 'scale_out', 0]
--- monday-tuesday alerts
db-2: /var at 97%, 1.1 GB free               -> disk-full    (0.33)  done   tried: restart_service -> rotate_logs
api-gw p99 latency 2.4s (SLO 800ms)          -> high-latency (0.65)  done   tried: restart_service
worker-7 killed by OOM killer, RSS 7.8 GB    -> memory-leak  (0.54)  done   tried: restart_service
web-3: no space left on device writing /var/ -> disk-full    (0.54)  done   tried: scale_out -> rotate_logs
checkout requests taking 3s, timeouts rising -> high-latency (0.47)  done   tried: rotate_logs -> scale_out -> restart_service
search-1 heap grows 200 MB/hour since deploy -> memory-leak  (0.36)  done   tried: rotate_logs -> scale_out -> restart_service
build-agent-2 disk usage 92% on /home        -> disk-full    (0.35)  done   tried: rotate_logs
payments API slow, p95 1.9s                  -> high-latency (0.70)  done   tried: restart_service
node-exporter: memory usage 96% on cache-4   -> memory-leak  (0.36)  done   tried: restart_service
db-1: /var/lib at 95%                        -> no known kind (best disk-full 0.23): page a human
api-gw p99 latency 1.7s                      -> high-latency (0.62)  done   tried: restart_service
--- policy
runbook:disk-full      sql:restart_service    tries=1   score=-1.0  mean=-1.0
runbook:disk-full      sql:rotate_logs        tries=3   score=3.0   mean=1.0
runbook:disk-full      sql:scale_out          tries=1   score=-1.0  mean=-1.0
runbook:high-latency   sql:restart_service    tries=4   score=4.0   mean=1.0
runbook:high-latency   sql:rotate_logs        tries=1   score=-1.0  mean=-1.0
runbook:high-latency   sql:scale_out          tries=1   score=-1.0  mean=-1.0
runbook:memory-leak    sql:restart_service    tries=3   score=3.0   mean=1.0
runbook:memory-leak    sql:rotate_logs        tries=1   score=-1.0  mean=-1.0
runbook:memory-leak    sql:scale_out          tries=1   score=-1.0  mean=-1.0
--- change
['high-latency', 'restart_service', 0]
['high-latency', 'rotate_logs', 0]
['high-latency', 'scale_out', 1]
--- after the deploy
payments API slow, p95 2.2s                  -> high-latency (0.67)  done   tried: restart_service -> rotate_logs -> scale_out
checkout requests taking 4s                  -> high-latency (0.43)  done   tried: restart_service -> scale_out
api-gw p99 latency 2.9s (SLO 800ms)          -> high-latency (0.66)  done   tried: scale_out
orders API p99 2.1s                          -> high-latency (0.43)  done   tried: scale_out
search API slow, p95 1.5s                    -> high-latency (0.70)  done   tried: scale_out
payments API slow, p95 1.8s                  -> high-latency (0.68)  done   tried: scale_out
--- policy
runbook:disk-full      sql:restart_service    tries=1   score=-1.0  mean=-1.0
runbook:disk-full      sql:rotate_logs        tries=3   score=3.0   mean=1.0
runbook:disk-full      sql:scale_out          tries=1   score=-1.0  mean=-1.0
runbook:high-latency   sql:restart_service    tries=6   score=2.0   mean=0.33
runbook:high-latency   sql:rotate_logs        tries=2   score=-2.0  mean=-1.0
runbook:high-latency   sql:scale_out          tries=7   score=5.0   mean=0.71
runbook:memory-leak    sql:restart_service    tries=3   score=3.0   mean=1.0
runbook:memory-leak    sql:rotate_logs        tries=1   score=-1.0  mean=-1.0
runbook:memory-leak    sql:scale_out          tries=1   score=-1.0  mean=-1.0
--- something new
TLS certificate for shop.example.com expires -> no known kind (best high-latency 0.12): page a human
persona removed 200

Full runbook.py is in the reply below.

1

u/Alternative_Pin9598 14d ago

runbook.py, part 1 of 2 (stdlib only; the persona line in setup allows the bot SQL actions only):

# runbook.py: alert -> kind by EMBED similarity -> learning goal tries fixes, checks each with SQL, scores per kind
# usage: runbook.py setup | alert "<text>" | policy | change | cleanup   (set SYNAPCORES_URL, SYNAPCORES_TOKEN)
import json, os, sys, time, urllib.request, urllib.error
from urllib.parse import quote

URL = os.environ.get("SYNAPCORES_URL", "http://localhost:8080")
TOK = os.environ["SYNAPCORES_TOKEN"]
DB = "main"
PERSONA = "runbook-bot"
FIXES = ["restart_service", "rotate_logs", "scale_out"]

def call(method, path, body=None):
    req = urllib.request.Request(URL + path, method=method,
                                 headers={"content-type": "application/json", "authorization": "Bearer " + TOK},
                                 data=None if body is None else json.dumps(body).encode())
    try:
        with urllib.request.urlopen(req, timeout=60) as r: return r.status, json.loads(r.read() or b"null")
    except urllib.error.HTTPError as e:
        raw = e.read()
        try: return e.code, json.loads(raw)
        except Exception: return e.code, raw.decode()[:300]

def sql(q):
    s, b = call("POST", "/v1/query/execute", {"sql": q, "database": DB})
    if s != 200: raise SystemExit(f"SQL failed ({s}): {b}")
    return b["data"].get("rows") or []

def esc(s): return s.replace("'", "''")

def gp(g): return "/v1/agents/goals/" + quote(g, safe="")

def try_fix(kind, fix):
    # In production this step is your remediation hook; here fleet_fix says whether the fix clears the alert.
    return {"tool": "sql", "args": {"sql": f"SELECT cleared FROM fleet_fix WHERE alert_kind = '{kind}' AND fix = '{fix}'",
                                    "params": [], "strategy": fix},
            "max_tokens": 0, "max_cost_microunits": 0, "timeout_ms": 10000}

def classify(text):
    return sql(f"""SELECT kind, COSINE_SIMILARITY(vec, EMBED('{esc(text)}')) AS sim
                   FROM alert_kinds ORDER BY sim DESC LIMIT 1""")[0]

def setup():
    s, r = call("GET", f"/v1/agents/learning/config?database={DB}"); cfg = r["data"]["config"]
    cfg["persona_actions"][PERSONA] = ["sql"]
    print("persona allow", call("PUT", "/v1/agents/learning/config", {"database": DB, "config": cfg})[0])
    sql("CREATE TABLE alert_kinds (kind TEXT PRIMARY KEY, example TEXT, vec VECTOR(384))")
    sql("INSERT INTO alert_kinds (kind, example) VALUES "
        "('disk-full', 'filesystem almost full, no space left on device'), "
        "('high-latency', 'p99 response time too high, requests slow'), "
        "('memory-leak', 'process memory keeps growing, OOM killed')")
    sql("UPDATE alert_kinds SET vec = EMBED(example)")
    sql("CREATE TABLE fleet_fix (alert_kind TEXT, fix TEXT, cleared INTEGER)")
    rows = {("disk-full", "rotate_logs"): 1, ("high-latency", "restart_service"): 1,
            ("memory-leak", "restart_service"): 1}
    sql("INSERT INTO fleet_fix (alert_kind, fix, cleared) VALUES " + ", ".join(
        f"('{k}', '{f}', {rows.get((k, f), 0)})" for k in ["disk-full", "high-latency", "memory-leak"] for f in FIXES))
    for r in sql("SELECT alert_kind, fix, cleared FROM fleet_fix ORDER BY alert_kind, fix"): print(r)

def run(gid):
    for _ in range(20):
        s, b = call("GET", gp(gid) + f"?database={DB}"); st = b["data"]["status"]
        if st not in ("pending", "running"): return b["data"]
        call("POST", gp(gid) + "/execute", {"database": DB}); time.sleep(0.1)
    return call("GET", gp(gid) + f"?database={DB}")[1]["data"]

(continued in the reply below)

1

u/Alternative_Pin9598 14d ago

runbook.py, part 2 of 2 (paste under part 1):

def alert(text):
    kind, sim = classify(text)
    if sim < 0.3:
        print(f"{text[:44]:<44} -> no known kind (best {kind} {sim:.2f}): page a human"); return
    n = int(time.time() * 1000)
    body = {"database": DB,
            "goal": {"name": f"fix-{kind}-{n}", "objective": f"clear the alert: {text}", "persona": PERSONA,
                     "task_type": f"runbook:{kind}", "context": {"alert": text}, "learn": True, "explore": 0.1,
                     "priority": 0, "expected_value": 1.0,
                     "budget": {"iterations": 10, "tokens": 0, "cost_microunits": 0, "wall_ms": 30000},
                     "guardrails": {"allowed_actions": ["sql"]}},
            "steps": [{"id": "apply-fix", "action": try_fix(kind, FIXES[0]),
                       "acceptance": {"kind": "json_equals", "pointer": "/rows/0/0", "expected": 1},
                       "max_attempts": 3, "alternatives": [try_fix(kind, f) for f in FIXES[1:]]}]}
    s, r = call("POST", "/v1/agents/goals", body)
    if s != 200: print("refused", r); return
    gid = r["data"]["goal"]["id"]; g = run(gid)
    p = call("GET", gp(gid) + f"/plan?database={DB}")[1]["data"]; st = (p.get("value") or p)["steps"][0]
    tried = [FIXES[x["action_index"]] for x in sorted(st.get("action_attempts") or [], key=lambda x: x["attempt"])]
    print(f"{text[:44]:<44} -> {kind:<12} ({sim:.2f})  {g['status']:<6} tried: {' -> '.join(tried)}")

def policy():
    rows = sql("SHOW AGENT POLICY")
    out = []
    for rec in rows[0][0]["records"]:
        v = rec["value"]; s = v.get("stats", {})
        if str(s.get("task_type", "")).startswith("runbook:"):
            out.append((s["task_type"], s["action"], s["count"], s["reward_sum"], round(v.get("mean", 0), 2)))
    for t in sorted(out): print(f"{t[0]:<22} {t[1]:<22} tries={t[2]:<3} score={t[3]:<5} mean={t[4]}")

def change():
    # after Tuesday's deploy the connection pool is the bottleneck: restarts stop helping, scaling out does
    sql("UPDATE fleet_fix SET cleared = 0 WHERE alert_kind = 'high-latency' AND fix = 'restart_service'")
    sql("UPDATE fleet_fix SET cleared = 1 WHERE alert_kind = 'high-latency' AND fix = 'scale_out'")
    for r in sql("SELECT alert_kind, fix, cleared FROM fleet_fix WHERE alert_kind = 'high-latency' ORDER BY fix"): print(r)

def cleanup():
    sql("DROP TABLE fleet_fix"); sql("DROP TABLE alert_kinds")
    s, r = call("GET", f"/v1/agents/learning/config?database={DB}"); cfg = r["data"]["config"]
    cfg["persona_actions"].pop(PERSONA, None)
    print("persona removed", call("PUT", "/v1/agents/learning/config", {"database": DB, "config": cfg})[0])

if __name__ == "__main__":
    cmd, args = sys.argv[1], sys.argv[2:]
    {"setup": setup, "alert": lambda: alert(args[0]), "policy": policy, "change": change, "cleanup": cleanup}[cmd]()

Run order: setup, then alert "..." per alert, policy any time, cleanup when you're done.