r/devops7 • • 6d ago

One script, one chore: 6 of 12 runbook lines contradict the inventory. Similarity can't tell which (a stale line scores highest, 0.95); one SQL query with an NLI check finds them (real output)

Short one this week: one script, one chore, real output. (This sub is run by the SynapCores team.)

The chore

Runbooks rot. The failover runbook says the orders primary is db-1 in us-east-1. Terraform has said db-3 in us-east-2 since the migration. You find out at 3 a.m., halfway through the failover.

Every runbook line gets a verdict: STALE (the inventory contradicts it), OK (it backs it up) or REVIEW.

Step 1: two files, two tables

facts.txt holds 8 facts rendered from what you trust (Terraform outputs, the CMDB); runbook.txt holds 12 claims from 4 runbooks. Both samples are in the first comment:

The orders database primary is db-3 in us-east-2.
db-failover.md: The orders primary is db-1 in us-east-1.

Both go into tables, embedded on the way in:

INSERT INTO rb_facts VALUES (1, 'The orders database primary is db-3 in us-east-2.',
  EMBED('The orders database primary is db-3 in us-east-2.')), ...

Step 2, the payoff: one query

Similarity pairs each line with its closest fact; then NLI_CLASSIFY (a natural language inference model inside the engine) reads the pair and scores entailment (e: the fact backs the line up) and contradiction (c).

SELECT fid, fact, doc, line, ROUND(sim, 2) AS sim, ROUND(e, 2) AS e, ROUND(c, 2) AS c,
  CASE WHEN sim < 0.5 THEN 'REVIEW' WHEN c > 0.5 THEN 'STALE'
       WHEN e > 0.5 THEN 'OK' ELSE 'REVIEW' END AS verdict
FROM (SELECT fid, fact, doc, line, sim,
  JSON_EXTRACT(NLI_CLASSIFY('nli-default', fact, line), '$.scores.entailment') AS e,
  JSON_EXTRACT(NLI_CLASSIFY('nli-default', fact, line), '$.scores.contradiction') AS c
  FROM (SELECT f.id AS fid, f.fact, r.doc, r.line, COSINE_SIMILARITY(r.emb, f.emb) AS sim,
    ROW_NUMBER() OVER (PARTITION BY r.id ORDER BY COSINE_SIMILARITY(r.emb, f.emb) DESC) AS rn
    FROM rb_runbook r CROSS JOIN rb_facts f) best
  WHERE rn = 1) checked
ORDER BY fid, sim DESC

Output of rotcheck.py (sim = similarity to the fact):

fact: The orders database primary is db-3 in us-east-2.
0.90 STALE e 0.00 c 0.99  db-failover.md  The orders primary is db-1 in us-east-1.
0.73 OK e 1.00 c 0.00  db-restore.md  Primary: db-3 (us-east-2).
0.37 REVIEW e 0.00 c 0.01  db-failover.md  Escalate to the DBA team in #dba-help.
fact: orders-db backups run every 6 hours.
0.88 STALE e 0.00 c 1.00  db-failover.md  orders-db is backed up every 24 hours.
0.86 REVIEW e 0.02 c 0.01  db-restore.md  Backups run every 6 hours, so you can lose up to 6 hours of orders.
0.25 REVIEW e 0.00 c 1.00  checkout.md  Keep the incident doc updated every 30 minutes.
fact: The edge nginx listens on port 8443.
0.80 STALE e 0.00 c 1.00  edge-tls.md  Edge nginx listens on port 443.
fact: The session Redis runs version 7.2.
0.95 STALE e 0.00 c 1.00  checkout.md  Session Redis is version 6.2.
fact: The checkout on-call channel is #checkout-oncall.
0.84 OK e 0.99 c 0.00  checkout.md  Reach the checkout on-call in #checkout-oncall.
fact: TLS certificates are issued by cert-manager with Let's Encrypt.
0.88 OK e 1.00 c 0.00  edge-tls.md  Certificates come from cert-manager with Let's Encrypt.
0.62 STALE e 0.00 c 0.98  edge-tls.md  TLS certificates are renewed by hand with certbot on the edge box.
fact: Deploys go through Argo CD.
0.65 STALE e 0.00 c 1.00  checkout.md  Deploys go out through Jenkins.

6 of 12 runbook lines contradict the inventory, 3 OK, 3 to review

Look at the sim column. The stale db-1 line scores 0.90 against the primary fact, the current "Primary: db-3" line 0.73, and the most similar line of all (Redis 6.2, 0.95) is stale. Similarity finds the fact a line is about; whether the line agrees with it is the question NLI models are trained for.

REVIEW means a human looks: one line adds a claim the inventory can't confirm, two aren't about any fact. The 0.5 similarity floor comes first, so only pairs about the same thing reach NLI.

Why one database? Embeddings, pairing and the NLI check all run where the tables are: no embedding API, no NLI model server, no glue code.

Run it after each Terraform apply and send each STALE line to the runbook's owner. rotcheck.py (stdlib only) is in the first comment.

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

How do you catch stale runbooks today: a "last reviewed" date, game days, or the 3 a.m. page?

1 Upvotes

1 comment sorted by

1

u/Alternative_Pin9598 6d ago

rotcheck.py (standard library only; set SC_URL and SC_TOKEN). Run: python3 rotcheck.py facts.txt runbook.txt

NLI is a one-time opt-in: synapcores pull nli-default (about 577 MB), then synapcores models enable-nli nli-default, both with the --config your service uses, then restart the server.

"""rotcheck.py: which runbook lines does the current inventory contradict?
usage: python3 rotcheck.py facts.txt runbook.txt
  facts.txt    one sentence per inventory fact (render it from Terraform outputs, the CMDB, ...)
  runbook.txt  one statement per line, "file.md: text"
"""
import json, os, sys, urllib.request

BASE = os.environ["SC_URL"]      # e.g. http://localhost:<port> of your SynapCores
TOKEN = os.environ["SC_TOKEN"]   # from POST /v1/auth/login


def run(q):
    req = urllib.request.Request(BASE + "/v1/query/execute", method="POST",
                                 data=json.dumps({"sql": q, "database": "main"}).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=120) as r:
        return json.load(r)["data"].get("rows", [])


def lit(text):  # SQL string literal
    return "'" + text.replace("'", "''") + "'"


def load(facts_path, runbook_path):
    facts = [l.strip() for l in open(facts_path) if l.strip()]
    lines = [l.strip().split(": ", 1) for l in open(runbook_path) if l.strip()]
    run("DROP TABLE IF EXISTS rb_facts")
    run("DROP TABLE IF EXISTS rb_runbook")
    run("CREATE TABLE rb_facts (id INTEGER PRIMARY KEY, fact TEXT, emb VECTOR(384))")
    run("CREATE TABLE rb_runbook (id INTEGER PRIMARY KEY, doc TEXT, line TEXT, emb VECTOR(384))")
    # EMBED() runs inside SynapCores: no embedding API to call, no vector store on the side
    run("INSERT INTO rb_facts VALUES " + ",".join(
        f"({i}, {lit(f)}, EMBED({lit(f)}))" for i, f in enumerate(facts, 1)))
    run("INSERT INTO rb_runbook VALUES " + ",".join(
        f"({i}, {lit(doc)}, {lit(text)}, EMBED({lit(text)}))" for i, (doc, text) in enumerate(lines, 1)))
    print(f"loaded {len(facts)} facts, {len(lines)} runbook lines")


# The check is one query. Similarity pairs each runbook line with the fact it talks about
# (closest fact, ROW_NUMBER = 1). NLI reads the pair: the fact entails the line -> OK,
# contradicts it -> STALE, neither -> REVIEW. Closest fact under 0.5: no fact covers it -> REVIEW.
CHECK = """
SELECT fid, fact, doc, line, ROUND(sim, 2) AS sim, ROUND(e, 2) AS e, ROUND(c, 2) AS c,
       CASE WHEN sim < 0.5 THEN 'REVIEW' WHEN c > 0.5 THEN 'STALE'
            WHEN e > 0.5 THEN 'OK' ELSE 'REVIEW' END AS verdict
FROM (SELECT fid, fact, doc, line, sim,
             JSON_EXTRACT(NLI_CLASSIFY('nli-default', fact, line), '$.scores.entailment') AS e,
             JSON_EXTRACT(NLI_CLASSIFY('nli-default', fact, line), '$.scores.contradiction') AS c
      FROM (SELECT f.id AS fid, f.fact, r.doc, r.line, COSINE_SIMILARITY(r.emb, f.emb) AS sim,
                   ROW_NUMBER() OVER (PARTITION BY r.id ORDER BY COSINE_SIMILARITY(r.emb, f.emb) DESC) AS rn
            FROM rb_runbook r CROSS JOIN rb_facts f) best
      WHERE rn = 1) checked
ORDER BY fid, sim DESC"""


def check():
    rows, last = run(CHECK), None
    for fid, fact, doc, line, sim, e, c, verdict in rows:
        if fact != last:
            print(f"\nfact: {fact}")
            last = fact
        print(f"  {sim:.2f}  {verdict:<6}  e {e:.2f}  c {c:.2f}  {doc:<15} {line}")
    n = {v: sum(r[-1] == v for r in rows) for v in ("STALE", "OK", "REVIEW")}
    print(f"\n{n['STALE']} of {len(rows)} runbook lines contradict the inventory, {n['OK']} OK, {n['REVIEW']} to review")


if __name__ == "__main__":
    load(sys.argv[1], sys.argv[2])
    check()

facts.txt (one sentence per inventory fact):

The orders database primary is db-3 in us-east-2.
orders-db backups run every 6 hours.
The payments service runs on Kubernetes in the prod-eu cluster.
The edge nginx listens on port 8443.
The session Redis runs version 7.2.
The checkout on-call channel is #checkout-oncall.
TLS certificates are issued by cert-manager with Let's Encrypt.
Deploys go through Argo CD.

runbook.txt (file.md: text, one statement per line):

db-failover.md: The orders primary is db-1 in us-east-1.
db-failover.md: orders-db is backed up every 24 hours.
db-failover.md: Escalate to the DBA team in #dba-help.
db-restore.md: Primary: db-3 (us-east-2).
db-restore.md: Backups run every 6 hours, so you can lose up to 6 hours of orders.
edge-tls.md: Edge nginx listens on port 443.
edge-tls.md: Certificates come from cert-manager with Let's Encrypt.
edge-tls.md: TLS certificates are renewed by hand with certbot on the edge box.
checkout.md: Reach the checkout on-call in #checkout-oncall.
checkout.md: Session Redis is version 6.2.
checkout.md: Deploys go out through Jenkins.
checkout.md: Keep the incident doc updated every 30 minutes.

Want the idea behind the NLI step? Recipe of the week #2 on r/synapcores checks new agent memories against old ones the same way: https://www.reddit.com/r/synapcores/comments/1xru0wg/

The pairing step (CROSS JOIN + ROW_NUMBER by similarity, then a floor) is today's SQLv2 Lesson 8, step by step: https://www.reddit.com/r/SQLv2/comments/1xzhmki/