r/devops7 • • 18h ago

Automate it #10: a stolen-key SSH login at 03:41 succeeded like any other. 3 rules flagged it plus 5 harmless logins; an anomaly score flagged only that one (real output)

1 Upvotes

03:41, Accepted publickey for erin on the bastion. A valid key, so it's a success line like the other 950 in auth.log. The key was stolen.

The chore: score every successful SSH login against what's normal for that account, and look only at the ones the history has never seen.

(This sub is run by the SynapCores team; the table, the rules and the model all run in SynapCores. Sample auth.log, real output from 2.5.1 this morning.)

Step 1: auth.log into a table, three numbers per login

Nov 24 03:40:15 bastion sshd[51845]: Connection closed by authenticating user deploy 203.0.113.77 port 43424 [preauth]
Nov 24 03:41:07 bastion sshd[51846]: Accepted publickey for erin from 203.0.113.77 port 59705 ssh2: ED25519 SHA256:fLzLDEyq35/NtR7kV6gozHKkWHmDG1uXiuLizvxElwU

sshwatch.py parses six weeks of lines. For each login it looks at the 14 days before:

  • hour_seen: how many of the account's logins were within an hour of this time of day (capped at 10; 0 = never at this time)
  • net_seen: how many of the account's logins came from this /24 (capped at 10; 0 = never from this network)
  • ip_accounts: how many other accounts this IP tried, or got into, in the 15 minutes before

One row per login:

CREATE TABLE logins (ts TEXT, account TEXT, ip TEXT, hour_seen FLOAT, net_seen FLOAT, ip_accounts FLOAT)

951 logins and 1443 refused tries; 640 logins scored (after the first 14 days)

Step 2: the rules you'd write first

SELECT ts, account FROM logins WHERE ts >= '2026-11-23 08:00' AND net_seen = 0 ORDER BY ts

Same with hour_seen = 0 and ip_accounts >= 2, over the last 24 h:

new network                 3: alice 09:20, carol 19:40, erin 03:41
never at this hour          2: erin 03:41, frank 06:50
IP tried 2+ other accounts  3: alice 09:04, bob 09:11, erin 03:41

All three catch erin. All three also fire on ordinary logins: alice at a conference hotel, carol on call from a phone hotspot, frank up early, the office NAT at standup. Six logins flagged, one real. By Thursday somebody mutes them.

Step 3, the payoff: learn normal from 4 weeks of logins, score inside the SELECT

CREATE EXPERIMENT ssh_exp AS SELECT hour_seen, net_seen, ip_accounts FROM logins WHERE ts < '2026-11-23 08:00'
WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'], max_trials = 5, random_seed = 42);
DEPLOY MODEL ssh_model FROM EXPERIMENT ssh_exp;

SELECT ts, account, ip, hour_seen, net_seen, ip_accounts, ANOMALY_SCORE('ssh_model', hour_seen, net_seen, ip_accounts) AS score
FROM logins WHERE ts >= '2026-11-23 08:00' ORDER BY score DESC LIMIT 6;

odd = above the highest score in the history (0.70)
  11-24 03:41  erin   203.0.113.77   hour_seen  0  net_seen  0  ip_accounts 3  score 0.77  ODD
  11-23 09:20  alice  198.19.88.140  hour_seen 10  net_seen  0  ip_accounts 0  score 0.66
  11-23 19:40  carol  198.19.55.2    hour_seen  6  net_seen  0  ip_accounts 0  score 0.66
  11-23 14:05  alice  198.19.88.140  hour_seen 10  net_seen  1  ip_accounts 0  score 0.64
  ...

One login over the line. In the 607 logins of history, a new network showed up 6 times, a never-before hour 8 times, a busy IP 21 times, and two of them at once never. Nobody wrote a rule for "all three at once". The model only learned what past logins look like, and erin's 03:41 sits where none of them do. You could AND the rules now that you know this pattern; the score will flag the next odd mix of these three numbers without anyone writing a rule for it.

Why one database? Logins, model and scores sit behind one endpoint: no ML service, no export step. The whole check, training included, took about 0.1 s on a Mac mini (Apple M4).

Wire it up: from cron every 15 minutes, join the rotated auth.log files into one, oldest first (zcat -f reads the .gz ones), load it, check the last 15 minutes, and post ODD lines to the on-call channel. sshwatch.py (stdlib only) and the sample log generator are in the comments.

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

Does anything alert on your successful SSH logins, or only on the failed ones?


r/devops7 • • 1d ago

One script, one chore: where did the incident channel contradict itself? 54 NLI calls, not 870 (real output)

1 Upvotes

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

The chore

Before the postmortem, someone combs the incident channel for where it contradicted itself. 14:05: "Failed over orders-db to db-2." 14:30: "We never failed over." Pick wrong and the timeline is fiction.

Step 1: load the channel

channel.txt (in the comments): 30 messages of a made-up #inc-2291 (checkout 500s), chatter included, loaded into a table with EMBED() in the INSERT.

Step 2: every pair through NLI

NLI_CLASSIFY (natural language inference) scores whether one text contradicts another. Gate at -1: every pair, both ways.

30 messages, 435 pairs; 435 at similarity >= -1 went to NLI (870 NLI calls)
...
14:04 sam: joining the bridge in 2, grabbing coffee
14:28 kim: burrito for me please
  sim 0.29 c1 1.00 c2 1.00
...
159 pairs contradict each other both ways (9.3 s)

159 hits, 4 of them corrections: NLI reads two texts as one scene, so unrelated lines clash. Hence the gate.

Step 3, the payoff: one query, with a gate

Only pairs that look alike (similarity >= 0.45) reach NLI, read both ways (c1 earlier vs later, c2 the reverse):

SELECT * FROM (
  SELECT a.id AS i1, b.id AS i2, a.ts AS t1, a.name AS who1, a.msg AS said1,
    b.ts AS t2, b.name AS who2, b.msg AS said2, COSINE_SIMILARITY(a.emb, b.emb) AS sim,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', a.msg, b.msg), '$.scores.contradiction') AS c1,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', b.msg, a.msg), '$.scores.contradiction') AS c2
  FROM inc8_msgs a JOIN inc8_msgs b ON a.id < b.id
  WHERE COSINE_SIMILARITY(a.emb, b.emb) >= 0.45) checked
WHERE c1 > 0.5 AND c2 > 0.5
ORDER BY i1, i2

contracheck.py channel.txt on SynapCores 2.5.1:

30 messages, 435 pairs; 27 at similarity >= 0.45 went to NLI (54 NLI calls)

14:03 priya: here, looking at orders-db
14:05 priya: Failed over orders-db to db-2 at 14:05.
  sim 0.57 c1 0.99 c2 0.96

14:04 sam: joining the bridge in 2, grabbing coffee
14:12 sam: on the bridge now, what did I miss?
  sim 0.46 c1 0.75 c2 0.89

14:05 priya: Failed over orders-db to db-2 at 14:05.
14:30 priya: We never failed over; db-1 recovered on its own.
  sim 0.50 c1 1.00 c2 0.56

14:08 marco: Rolled back checkout to v1.42.
14:25 ravi: The rollback never went out, we hotfixed forward in v1.44.
  sim 0.60 c1 1.00 c2 1.00

14:10 dana: Status page updated: investigating checkout errors.
14:13 lee: Checkout pods are all waiting on db connections.
  sim 0.45 c1 0.98 c2 0.99

14:10 dana: Status page updated: investigating checkout errors.
14:14 marco: Confirmed, every checkout pod is blocked waiting for a connection.
  sim 0.49 c1 1.00 c2 0.91

14:11 lee: The orders-db pool limit was changed 50 -> 5 in this morning's config push.
14:23 priya: Pool config wasn't touched, prod is still at 50.
  sim 0.50 c1 1.00 c2 0.99

14:20 kim: Status page is up, support is linking it in replies.
14:44 dana: Status page set to resolved.
  sim 0.74 c1 0.80 c2 0.98

14:35 kim: No orders were lost.
14:41 jo: Finance says 212 orders were charged but never written to orders-db.
  sim 0.55 c1 0.98 c2 1.00

9 pairs contradict each other both ways (0.6 s)

Four of the nine are for the postmortem to settle: did we fail over, roll back, change the pool limit, lose orders? The other five are the incident moving on (joining the bridge, then on it; investigating, then a cause): a glance each.

Why 0.45 and both ways? These four have sim 0.50 to 0.60: a 0.50 gate loses the pool pair (0.496), a 0.30 gate returns 18. With c1 alone, 13 come back, including two people agreeing ("Checkout pods are all waiting on db connections." / "Confirmed, every checkout pod is blocked..."): c1 0.98, c2 0.00. Both ways: 9 (as in SQLv2 Lesson 9).

Why one database? Embeddings, pairing and NLI run where the table is: no embedding API, no NLI model server. 54 NLI calls instead of 870: 0.6 s instead of 9.3 s on a Mac mini (Apple M4).

contracheck.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-8

Who untangles the incident channel before your postmortem: the IC, a scribe, or whoever writes it up?


r/devops7 • • 4d ago

What broke this week? #3: drop a one-liner. (Plus: was the fix already in your postmortem backlog? One SQL query matched 4 of 5 sample breaks to old action items by meaning, real output)

1 Upvotes

Friday thread. What broke for you this week? One line is plenty: what failed, and what fixed it (or "still don't know").

This week's angle: was the fix already sitting in your backlog? Postmortems end with action items. Some get done, many sit "open" for months, and then the same thing breaks again and someone finds the ticket from August.

Keyword search is hit and miss here: a one-liner written mid-incident rarely uses the words of an action item written months earlier. So we put both lists in tables and matched them by meaning.

(Disclosure: this sub is run by the SynapCores team, and the matching step uses SynapCores. Sample data, real output, run today on 2.5.1.)

Sample data: old action items and this week's one-liners

CREATE TABLE pm_actions (id INTEGER PRIMARY KEY, postmortem TEXT, opened TEXT, item TEXT, status TEXT, embedding VECTOR(384));
INSERT INTO pm_actions (id, postmortem, opened, item, status) VALUES
 (1, 'PM-031', '2026-08-21', 'Cap the payments DB connection pool and add a query timeout, so a slow database cannot hang checkout', 'open'),
 (2, 'PM-033', '2026-09-04', 'Page the platform on-call when a build agent disk goes above 85%', 'done'),
 (3, 'PM-033', '2026-09-04', 'Prune old docker images and build caches on the build agents nightly, so the disks stop filling up', 'open'),
 -- + 7 more in the first comment (cert-manager, empty backup dump, webhook retries, ...)
UPDATE pm_actions SET embedding = EMBED(item);

CREATE TABLE week_breaks (id INTEGER PRIMARY KEY, what_broke TEXT, embedding VECTOR(384));
INSERT INTO week_breaks (id, what_broke) VALUES
 (1, 'checkout hung for 20 minutes, the payments DB got slow and every request sat waiting for a connection'),
 (2, 'CI was red all Tuesday morning, the build agents ran out of disk again'),
 (3, 'nightly backup said success but the dump was 0 bytes, we found out when we needed it'),
 (4, 'partner API was flaky for an hour and we lost about 300 webhook events for good'),
 (5, 'the status page domain expired because it was on an ex-employee personal credit card');
UPDATE week_breaks SET embedding = EMBED(what_broke);

EMBED() runs a small model inside the database. No API key.

Was it already on the backlog?

SELECT b.id, a.postmortem, a.status, DATEDIFF(CURRENT_DATE, a.opened) AS days_old,
       ROUND(COSINE_SIMILARITY(b.embedding, a.embedding), 2) AS match, SUBSTR(a.item, 1, 36) AS item
FROM week_breaks b CROSS JOIN pm_actions a
WHERE COSINE_SIMILARITY(b.embedding, a.embedding) > 0.35
ORDER BY b.id, match DESC;

id  postmortem  status  days_old  match  item
1   PM-031      open    91        0.72   Cap the payments DB connection pool
2   PM-033      done    77        0.44   Page the platform on-call when a bui
2   PM-033      open    77        0.36   Prune old docker images and build ca
3   PM-036      open    51        0.56   Make the nightly database backup fai
4   PM-039      open    36        0.53   Retry failed webhook deliveries with

On no list at all? That one gets the postmortem

SELECT b.what_broke, ROUND(MAX(COSINE_SIMILARITY(b.embedding, a.embedding)), 2) AS best
FROM week_breaks b CROSS JOIN pm_actions a
GROUP BY b.what_broke
HAVING MAX(COSINE_SIMILARITY(b.embedding, a.embedding)) < 0.35;

the status page domain expired because it was on an ex-employee personal credit card   0.25

So in this sample week, 4 of 5 breaks already had an action item, written 36 to 91 days ago. The CI one is the classic: the alert item is marked done, the disks filled anyway, and the prune item next to it is still open. Those four open items are the retro agenda.

Why 0.35: the closest wrong pairing scored 0.3 (the CI break vs the Redis failover-steps item) and the weakest right one 0.36 (CI vs the prune item). That gap is thin, so check borderline rows by eye. The near-misses and how to pick the cut-off are in the first comment.

Free Community Edition, to run it on your own backlog: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-whatbroke-1120

Your turn: what broke this week, and was the fix already sitting in a ticket somewhere?


r/devops7 • • 5d ago

Automate it #9: 5 pages at 02:14, and the service that broke never paged. Anomaly scores + a dependency-graph walk ranked it first (real output)

1 Upvotes

02:14, five pages in three minutes: web, mobile-bff, checkout-api, payments-api, notifications. Which one do you open first?

The chore: rank the suspects. Score every service against its own normal (not just the ones that paged), then walk the dependency graph down from the pages.

(This sub is run by the SynapCores team; each step runs in SynapCores. Sample data, real output from 2.3.2 this morning.)

Step 1: metrics in a table, dependencies in a graph

metrics.csv: p99 latency and error rate for 15 services, every 5 minutes for 24 h. deps.txt: "caller callee" lines. Metrics go into svc_metrics with SQL; each dependency becomes a graph edge with Cypher, same endpoint:

MERGE (a:Svc {name: "payments-api"}) MERGE (b:Svc {name: "payments-db"})
MERGE (a)-[:DEPENDS_ON]->(b)

loaded 18 dependencies, 4335 metric rows

Step 2: score every service

Each row gets two ratios vs its service's 24 h average, lat_x and err_x (1.0 = normal). One anomaly model learns normal, then scores inside the SELECT:

CREATE EXPERIMENT rca_exp AS SELECT lat_x, err_x FROM svc_metrics WHERE ts < '2026-11-19 02:10'
WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'], max_trials = 5, random_seed = 42);
DEPLOY MODEL rca_model FROM EXPERIMENT rca_exp;

SELECT service, p99_ms, err_pct, ANOMALY_SCORE('rca_model', lat_x, err_x) AS score
FROM svc_metrics WHERE ts = '2026-11-19 02:10' ORDER BY score DESC, lat_x DESC;

every service at 2026-11-19 02:10 (odd = above the last 24 h's highest score, 0.76):
  payments-api   p99  1900 ms (13.4x usual)  errors 3.1% (12.2x)  anomaly 0.82  ODD  PAGED
  payments-db    p99    41 ms (10.0x usual)  errors 0.8% ( 9.0x)  anomaly 0.82  ODD
  checkout-api   p99  2300 ms ( 7.3x usual)  errors 4.1% (13.4x)  anomaly 0.82  ODD  PAGED
  web            p99  2650 ms ( 6.9x usual)  errors 3.4% ( 8.6x)  anomaly 0.82  ODD  PAGED
  mobile-bff     p99  2480 ms ( 5.7x usual)  errors 3.0% ( 6.8x)  anomaly 0.82  ODD  PAGED
  ... (9 more ok, 0.36 to 0.49)
  notifications  p99   270 ms ( 1.0x usual)  errors 4.3% ( 1.0x)  anomaly 0.37  ok   PAGED

payments-db never paged: 41 ms is under its 100 ms alert, but it's 10x its usual 4 ms, with errors at 0.8% (usually 0). notifications paged at 4.3% errors: normal for it (over 2% in 287 of the last 288 windows).

But five services tie at 0.82. The score says "odd", not "open this one first".

Step 3, the payoff: graph walk + anomaly score in one query

Cypher lists everything each page depends on, 1 to 6 hops down (41 rows, saved as reach):

MATCH p = (a:Svc)-[:DEPENDS_ON*1..6]->(b:Svc) WHERE a.name IN ['web', 'mobile-bff', ...]
RETURN a.name AS page, b.name AS service, min(length(p)) AS hops

The walk alone can't decide either: auth-svc, payments-db, redis-session, smtp-relay and users-db each sit under 4 of the 5 pages. One SQL query keeps the odd ones, ranked by how many pages depend on them:

SELECT r.service, MAX(ANOMALY_SCORE('rca_model', m.lat_x, m.err_x)) AS score,
  COUNT(DISTINCT r.page) AS explains, GROUP_CONCAT(DISTINCT r.page) AS pages
FROM reach r JOIN svc_metrics m ON m.service = r.service
WHERE m.ts = '2026-11-19 02:10' AND ANOMALY_SCORE('rca_model', m.lat_x, m.err_x) > 0.76
GROUP BY r.service
ORDER BY explains DESC, score DESC;

suspects: odd services, ranked by how many of the 5 pages depend on them
  payments-db    anomaly 0.82  4 of 5 pages: checkout-api, mobile-bff, payments-api, web
  payments-api   anomaly 0.82  3 of 5 pages: checkout-api, mobile-bff, web
  checkout-api   anomaly 0.82  2 of 5 pages: mobile-bff, web

paged, but not odd and nothing odd behind it: notifications

Open payments-db first. It's the only odd service that never paged.

Why one database? Model, scores, metrics and graph sit behind one endpoint: no ML service, no graph store to sync. The whole check, training included, took 0.5 s on a Mac mini (Apple M4).

Wire it to your pager: on 3+ pages in 5 minutes, run rootcause.py check with them and post the suspects in the incident channel. rootcause.py (stdlib only), the data generator and deps.txt are in the comments.

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

In your last alert storm, did the service that actually broke page at all?


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)

1 Upvotes

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?


r/devops7 • • 7d ago

Automate it #8: ask your ops tables in plain English. A read-only key that sees 4 tables, the SQL it ran next to every answer, and a flat "cannot answer" for the phone list and the DELETE (real output)

1 Upvotes

Seven posts of this series put deploys, alerts, cert expiry and disk numbers into tables. Then the questions start coming from people who don't write SQL: "is anything still firing?", "which certs run out this month?", "who shipped the last payments release?". Each one costs you a context switch and a query.

The chore: let them ask in plain English, without giving a chat model the keys to the database. Three rules:

  1. It can read only the ops tables. The on-call table (names, phone numbers) sits in the same database and stays out of reach.
  2. It can't write. Not "the prompt says please don't": the credential can't.
  3. Every answer shows the SQL it ran, so you can check it in five seconds.

(Disclosure: this sub is run by the SynapCores team, and step 2 is a SynapCores endpoint. Run this morning on SynapCores 2.5.0 on a Mac mini (Apple M4), real output.)

Step 1: the tables

CREATE TABLE deploys (id INTEGER PRIMARY KEY, service TEXT, version TEXT, author TEXT, deployed_at TEXT);
CREATE TABLE alerts  (id INTEGER PRIMARY KEY, service TEXT, severity TEXT, title TEXT, fired_at TEXT, resolved_at TEXT);
CREATE TABLE certs   (id INTEGER PRIMARY KEY, host TEXT, expires_on TEXT);
CREATE TABLE disk    (id INTEGER PRIMARY KEY, host TEXT, mount TEXT, used_pct REAL, measured_at TEXT);
CREATE TABLE oncall  (id INTEGER PRIMARY KEY, name TEXT, phone TEXT, team TEXT);

Sample data: 6 deploys, 7 alerts, 4 certs, 5 disk readings, 2 on-call rows (INSERTs in the first comment).

Step 2, the payoff: a key that can see 4 tables, and one endpoint

Mint a ReadOnly key whose grants list exactly the tables it may read:

POST /v1/api-keys
{"name": "ops-ask-readonly", "permission": "ReadOnly", "expires_in_days": 1,
 "table_grants": {"grants": [{"database": "ops", "table": "deploys"}, {"database": "ops", "table": "alerts"},
                             {"database": "ops", "table": "certs"},   {"database": "ops", "table": "disk"}]}}

Then ask with that key:

POST /v1/ask   (Authorization: Bearer <that key>)
{"question": "Which hosts are above 85% disk usage?", "database": "ops", "include_rows": true}

The database writes the SQL from your schema with a local model (qwen2.5-coder:7b, running inside the engine, no API key), runs it under that key's grants, and answers from the rows it got back. The response carries the SQL, the rows and a citation.

Step 3: five questions

$ python3 ask_ops.py "Which hosts are above 85% disk usage?"
  status: answered
  answer: The hosts with disk usage above 85% are db-1 and logs-1 [SQL 1].
  sql:    SELECT host FROM disk WHERE used_pct > 85

$ ask "Which certificates expire before December 1, 2026?"
  answer: The certificates that expire before December 1, 2026, are:
          - Certificate ID: 1, Host: api.example.com, Expires On: 2026-11-29
          - Certificate ID: 3, Host: status.example.com, Expires On: 2026-11-21
  sql:    SELECT * FROM certs WHERE expires_on < '2026-12-01'

$ ask "Which alerts are still unresolved?"
  answer: 1. Alert ID: 6, Service: search-api, Severity: critical, Title: index lag 20 min, Fired At: 2026-11-17 08:55
          2. Alert ID: 7, Service: db-1, Severity: warning, Title: disk /var/lib at 91%, Fired At: 2026-11-17 06:10
  sql:    SELECT id, service, severity, title, fired_at FROM alerts WHERE resolved_at IS NULL

$ ask "Which service had the most critical alerts?"
  answer: The service with the most critical alerts is payments [SQL 1].
  sql:    SELECT service FROM alerts WHERE severity = 'critical' GROUP BY service ORDER BY COUNT(*) DESC LIMIT 1

$ ask "Who deployed the latest payments release?"
  answer: Dana deployed the latest payments release [SQL 1].
  sql:    SELECT author FROM deploys WHERE service = 'payments' ORDER BY deployed_at DESC LIMIT 1

All five match the data, and the SQL is what you'd have written. 6 to 13 seconds each on a Mac mini (Apple M4). Same SQL and answers on three runs.

Step 4: the two it should refuse

$ ask "What is Dana's phone number?"
  status: insufficient_data
  answer: Cannot answer from the permitted data.

$ ask "Delete all resolved alerts."
  HTTP 403: data_scope_denied: Cannot answer from the permitted data.

The phone number is in the oncall table of the same database; the key isn't granted that table, so there is nothing to answer from. The DELETE is refused before anything runs. Afterwards: SELECT COUNT(*) FROM alerts is still 7.

Why not a chatbot with a DB connection? You can wire an LLM to a Postgres role, then build the schema prompt, the SQL check, the answer step and the "show your work" part yourself. Here that is one endpoint: the scope is in a credential the database enforces, the model runs inside the engine, and the answer comes back with its SQL and rows instead of a paragraph you have to trust.

Wire it up: a Slack slash command or a /ask bot in the incident channel calls ask_ops.py "$TEXT" and posts the answer with its SQL. Setup is one model pull (synapcores --config gateway.toml pull qwen2.5-coder:7b) and model = "qwen2.5-coder:7b" under [query.ai_service] in gateway.toml. Full ask_ops.py (stdlib only) and the sample data are in the first comment.

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

Which question do you get asked in Slack most often that you'd hand to a bot like this?


r/devops7 • • 8d ago

One script, one chore: before Saturday's orders-db maintenance, who do you tell? grep finds 3 services that call it; a graph walk joined with the owners table finds 9 across 9 teams (real output)

1 Upvotes

Short one this week: one script, one chore, real output. (This sub is run by the SynapCores team; the script uses our database for the one step that matters.)

The chore

orders-db gets a major-version upgrade Saturday at 02:00, about 20 minutes of downtime. Before you post the maintenance notice: which services break, and which on-call channels need to hear about it?

The usual move is grepping configs for the connection string:

$ grep -l orders-db */config.yaml
fulfillment-worker/config.yaml
invoice-cron/config.yaml
orders-api/config.yaml

Three. But checkout calls orders-api, and web and mobile call checkout. They break too, and their teams don't know they depend on orders-db. That is the email you get Saturday at 02:05.

Step 1: the call graph, one line per dependency

deps.txt is "caller callee" (from your catalog or tracing), 18 lines:

web checkout-api
checkout-api orders-api
orders-api orders-db
...

The script loads it as a graph in SynapCores with Cypher, same endpoint as SQL:

MERGE (a:Svc {name: "checkout-api"}) MERGE (b:Svc {name: "orders-api"})
MERGE (a)-[:DEPENDS_ON]->(b)

Owners go in a plain SQL table next to it:

CREATE TABLE services (name TEXT PRIMARY KEY, team TEXT, tier INTEGER, channel TEXT);
-- ('checkout-api', 'checkout', 1, '#checkout-oncall'), ...

Step 2: walk the graph

Everything that reaches orders-db in 1 to 6 hops:

MATCH p = (s:Svc)-[:DEPENDS_ON*1..6]->(t:Svc {name: 'orders-db'})
RETURN s.name AS service, length(p) AS hops, [n IN nodes(p) | n.name] AS via
ORDER BY hops, service

1 hop   fulfillment-worker  fulfillment-worker > orders-db
1 hop   invoice-cron        invoice-cron > orders-db
1 hop   orders-api          orders-api > orders-db
2 hops  admin-portal        admin-portal > orders-api > orders-db
2 hops  checkout-api        checkout-api > orders-api > orders-db
2 hops  notifications       notifications > orders-api > orders-db
2 hops  partner-webhooks    partner-webhooks > orders-api > orders-db
3 hops  mobile-bff          mobile-bff > checkout-api > orders-api > orders-db
3 hops  web                 web > checkout-api > orders-api > orders-db

Step 3, the payoff: join the walk with the owners table

The script saves those rows to a blast table; one SQL query turns them into "who to tell":

SELECT s.team, s.channel, MIN(s.tier) AS tier, COUNT(DISTINCT b.service) AS n,
       GROUP_CONCAT(DISTINCT b.service) AS services
FROM blast b JOIN services s ON s.name = b.service
WHERE b.target = 'orders-db'
GROUP BY s.team, s.channel
ORDER BY tier, n DESC, s.team;

Output of python3 blast.py radius orders-db:

orders-db: 3 direct callers (fulfillment-worker, invoice-cron, orders-api), 9 services affected

  tier 1  checkout      #checkout-oncall       checkout-api
  tier 1  mobile        #mobile-oncall         mobile-bff
  tier 1  orders        #orders-oncall         orders-api
  tier 1  storefront    #storefront-oncall     web
  tier 2  integrations  #integrations-oncall   partner-webhooks
  tier 2  messaging     #messaging             notifications
  tier 2  warehouse     #warehouse-oncall      fulfillment-worker
  tier 3  backoffice    #backoffice            admin-portal
  tier 3  finance-eng   #finance-eng           invoice-cron

grep found 3 services; the real blast radius is 9 services and 9 channels, and 4 of them are tier 1. Two of those tier-1 teams (storefront, mobile) are 3 hops away and would never have found orders-db in their own configs.

Why one database? Variable-length paths with the path attached are a painful recursive CTE in plain SQL. A separate graph store walks them easily, but then owners and tiers live elsewhere and you sync two systems. Here the walk and the join hit the same database and endpoint.

Wire blast.py radius <node> into your change-request template and every maintenance ticket lists its blast radius. blast.py (stdlib only) and both sample files are in the first comment.

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

Where does your dependency map live today: a service catalog, tracing, or "ask in Slack and hope"?


r/devops7 • • 11d ago

One script, one chore: route alerts with one HTTP call. Team, "wake someone up?" and urgency for 6 alerts, 0 generated tokens, ~0.5 s each on a laptop CPU (SynapCores 2.5.0, real output)

1 Upvotes

Every alert pipeline ends in the same three questions: whose is it, does it wake someone up, and how soon does it need a human. Most of us answer them with a pile of regex routing rules, or by pasting the alert into a chat model and parsing whatever paragraph comes back.

SynapCores 2.5.0 (out this week) adds an endpoint built for exactly this: POST /v1/systemone. You send the alert text and your questions; you get back typed answers you can branch on: a choice with a probability for every option, a yes/no probability, and a score on a scale you define. It's backed by d1, a small decision model that weighs the options instead of writing text, so every call reports output_tokens: 0. (This sub is run by the SynapCores team.)

Setup (one-time, ~2.7 GiB):

synapcores --config gateway.toml pull d1:latest

One call per alert, three questions:

curl -s -X POST localhost:8080/v1/systemone -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' -d '{
  "model": "d1:latest",
  "state": "PagerDuty: api-gateway p99 latency 4.8 s (threshold 800 ms) for 12 min, 5xx rate 9% and rising, checkout failing for customers.",
  "questions": {
    "team":    {"type": "choice", "instructions": "Which team owns this alert?",
                "criteria": {"database": "databases, backups, replication, storage",
                             "network": "DNS, BGP, load balancers, firewalls, TLS certificates",
                             "app": "application services, APIs, frontend"}},
    "page":    {"type": "noul", "instructions": "Should this wake up the on-call engineer right now?"},
    "urgency": {"type": "score", "instructions": "How urgent is this?",
                "criteria": ["can wait", "this week", "today", "right now"]}}}'

Response (trimmed):

"team":    {"choice": "app", "probabilities": {"app": 0.962, "network": 0.029, "database": 0.009}},
"page":    {"noul": 0.861},
"urgency": {"score": 2.64, "probabilities": {"0": 0.020, "1": 0.015, "2": 0.275, "3": 0.691}},
"usage":   {"input_tokens": 269, "output_tokens": 0}

Six alerts, same three questions (2.5.0-ce on a Mac mini, Apple M4, warm):

alert                                              team            page   urgency           time
api-gateway p99 4.8 s, 5xx 9%, checkout failing    app (0.96)      0.86   right now (2.64)  714 ms
cert for staging.internal expires in 21 days       network (0.93)  0.42   this week (1.22)  503 ms
/var/lib/postgresql at 91%, +3%/hour               database (0.99) 0.75   today (2.42)      550 ms
frontend bundle size +4% after deploy              app (0.99)      0.14   this week (1.10)  502 ms
BGP session flapping, 30% loss us-east -> eu-west  network (0.99)  0.81   today (2.44)      545 ms
orders-db backup failed 2 nights, pg_dump exit 1   database (0.99) 0.90   today (2.37)      551 ms

The cert warning and the bundle-size note route to the right team but stay out of the pager (0.42, 0.14). The checkout outage, the BGP flap, the filling disk and the missing backups all clear 0.75. urgency is fractional on purpose: 2.64 reads as "right now, with some weight on today", and the per-level probabilities are there if you want your own thresholds.

Wiring it into an alert handler is a few lines:

a = r["answers"]
if a["page"]["noul"] > 0.7:
    page(a["team"]["choice"])
elif a["team"]["confidence"] > 0.8:
    open_ticket(a["team"]["choice"], due=a["urgency"]["score"])
else:
    send_to_triage_channel()

The whole Python script (standard library only) is in the first comment.

Why this matters beyond alerts: 2.5.0 rounds out one engine that does ML (AutoML in SQL), NLI (checking answers against your own data), LLM generation and agents, and now typed decisions. Pick the one whose output you need: https://synapcores.com/learn/llm-vs-nli-vs-vectors/llm-vs-nli-vs-ml-vs-decision-model?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-15

Which alert source would you route through this first: Prometheus/Alertmanager, PagerDuty, or cron/backup reports?


r/devops7 • • 12d 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)

1 Upvotes

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?


r/devops7 • • 13d ago

One script, one chore: every cron job exited 0 last night, and two still failed. Catch the backup that "finished" in 4 seconds with one anomaly score per job (real output)

1 Upvotes

Short one this week: one script, one chore, real output. (This sub is run by the SynapCores team; the script uses our database for the one step that matters.)

The chore

Every cron job exited 0 last night. Monitoring is green. Two of them still failed:

  • backup-db "finished" in 4 seconds and wrote 1.2 KB. It usually takes 40 minutes and writes about 18 GB. (Classic causes: the dump pointed at an empty replica, or a wrapper script swallowed the real error.)
  • logrotate ran on time but shipped 8.2 GB, 38x its usual. Something upstream started logging in a loop.

exit_code <> 0 catches neither. You only find out when you need the backup.

Step 1: log three numbers per job

Wrap each job so it appends one line: date, job, exit code, seconds, bytes written.

start=$(date +%s); pg_dump mydb > /backups/db.sql; code=$?
echo "$(date +%F) backup-db $code $(( $(date +%s) - start )) $(wc -c < /backups/db.sql | tr -d ' ')" >> /var/log/runs.txt

Real line from that wrapper (with a stand-in command):

2026-11-11 backup-db 0 1 6

For this post I generated 30 nights x 6 jobs (gen_runs.py, seeded, in the first comment) with the two failures above on the last night.

Step 2: one table, plus "how far from usual" for each job

CREATE TABLE job_runs (day TEXT, job TEXT, exit_code INTEGER, duration_s FLOAT, bytes_out FLOAT,
                       dur_ratio FLOAT, bytes_ratio FLOAT);

The script loads the lines, then for each job divides tonight's numbers by that job's average, so 1.0 means a normal night for that job. A 4-second cert renewal is normal; a 4-second database backup is not.

SELECT job, AVG(duration_s), AVG(bytes_out) FROM job_runs WHERE day < '2026-11-10' GROUP BY job;
-- then per job:
UPDATE job_runs SET dur_ratio = duration_s / <avg>, bytes_ratio = bytes_out / <avg> WHERE job = '<job>';

Step 3, the payoff: an anomaly model in the database, scored inside the SELECT

CREATE EXPERIMENT cron_exp AS SELECT dur_ratio, bytes_ratio FROM job_runs WHERE day <= '2026-11-10'
WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'], max_trials = 5, random_seed = 42);
DEPLOY MODEL cron_model FROM EXPERIMENT cron_exp;

SELECT job, exit_code, duration_s, bytes_out, dur_ratio, bytes_ratio,
       ANOMALY_SCORE('cron_model', dur_ratio, bytes_ratio) AS score
FROM job_runs WHERE day = '2026-11-10' ORDER BY score DESC;

Output of python3 jobwatch.py check 2026-11-10:

exit_code <> 0 last night: 0 jobs
ODD  backup-db      exit 0       4s (0.00x usual)     1.2 KB ( 0.00x usual)  anomaly 0.87
ODD  logrotate      exit 0      35s (0.87x usual)     8.2 GB (37.75x usual)  anomaly 0.86
ok   cert-renew     exit 0      10s (0.81x usual)    48.5 KB ( 1.13x usual)  anomaly 0.58
ok   report-export  exit 0     313s (1.03x usual)   615.1 MB ( 1.16x usual)  anomaly 0.53
ok   backup-files   exit 0    1608s (1.05x usual)     7.2 GB ( 1.10x usual)  anomaly 0.42
ok   db-vacuum      exit 0     908s (1.02x usual)     1.1 MB ( 1.00x usual)  anomaly 0.41

Both quiet failures on top, and a clear gap down to the rest. Is 0.8 going to page you every night? The top 5 scores over all 180 runs:

2026-11-10 backup-db     0.87
2026-11-10 logrotate     0.86
2026-10-13 db-vacuum     0.63
2026-11-10 cert-renew    0.58
2026-11-06 report-export 0.56

In 30 nights, nothing else got past 0.63.

Why a model and not thresholds? You can write duration < 10% of usual. Then you need "bytes too low", "bytes too high", "too slow", for every job: 6 jobs x 2 numbers x 2 directions = 24 thresholds to tune and keep tuned. The model learns what normal looks like for both numbers at once, and you get one score per job, inside the same SELECT, with no extra service.

Run it from cron after the last job: python3 jobwatch.py check $(date -d yesterday +%F), and send the ODD lines wherever your alerts go.

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

What's the worst "exit 0 but it didn't actually work" job you've found, and how long had it been broken?


r/devops7 • • 14d ago

Automate it #6: one incident timeline from deploys, app logs and alerts, then ask it which change caused the page (it skipped the newest deploy, real output)

1 Upvotes

13:58, PagerDuty: "Checkout: customers can't pay." You open three tabs: the deploy log, the app logs, the alert history. Five deploys went out in the last 80 minutes. The newest one (auth, 11 minutes ago) gets blamed first because it's the newest.

Put all three in one table and the timeline is one ORDER BY. Then rank every event in the hour before the page by how close it is to the alert's meaning, not its keywords.

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

Sample incident: 5 deploys, 15 log lines, 3 alerts.

Step 1: one table for everything

CREATE TABLE events (id INTEGER PRIMARY KEY, at TEXT, kind TEXT, service TEXT, level TEXT, text TEXT, vec VECTOR(384));

timeline.py load inserts the parsed lines, then embeds them all in one statement. EMBED() runs a small model inside the database, no API key:

UPDATE events SET vec = EMBED(service || ' ' || text);

Step 2: the plain timeline

SELECT at, kind, service, level, text FROM events
WHERE at BETWEEN '2026-11-09T12:58' AND '2026-11-09T13:58' ORDER BY at;

13:22 deploy payments   INFO     deployed v5.12.0: upgrade card processor SDK, connection poo
13:30 deploy inventory  INFO     deployed v1.9.4: add warehouse_code column
13:36 log    payments   WARN     waited 1840ms to acquire a connection from the pool
13:41 log    inventory  WARN     stock sync lag 45s for warehouse EU-2
13:47 deploy auth       INFO     deployed v4.2.2: rotate session signing key
13:50 log    auth       WARN     41 users forced to log in again
...21 rows

Still 21 rows of noise. grep -i checkout finds 2 lines (the 504, a slow render): not the payment timeouts, the pool waits, or the deploy.

Step 3: "what is this alert about?"

Rank the hour before the page against the alert:

SELECT e.at, e.kind, e.service, e.text, COSINE_SIMILARITY(e.vec, a.vec) AS related
FROM events e JOIN events a ON a.kind = 'alert' AND a.at = '2026-11-09T13:58'
WHERE e.at <= a.at AND e.at >= '2026-11-09T12:58' AND e.id <> a.id
ORDER BY related DESC LIMIT 8;

$ python3 timeline.py why 2026-11-09T13:58
0.38  13:57  log    web        504 from upstream on POST /checkout/pay
0.37  13:56  log    payments   card authorisation timed out after 5000ms (order 88231)
0.36  13:52  log    payments   card authorisation timed out after 5000ms (order 88213)
0.35  13:53  log    web        checkout page render 4.1s
0.31  13:22  deploy payments   deployed v5.12.0: upgrade card processor SDK, connection pool size 50
0.30  13:44  log    payments   waited 2950ms to acquire a connection from the pool
0.25  13:36  log    payments   waited 1840ms to acquire a connection from the pool
0.21  13:50  log    auth       41 users forced to log in again

The top 7 are the whole story: pool cut from 50 to 5 at 13:22, connection waits from 13:36, card auths timing out, 504s at checkout. No payments line contains "checkout", and the auth deploy is not in the top 8.

Step 4: just the deploys

SELECT d.at, d.service, d.text, COSINE_SIMILARITY(d.vec, a.vec) AS related
FROM events d JOIN events a ON a.kind = 'alert' AND a.at = '2026-11-09T13:58'
WHERE d.kind = 'deploy' ORDER BY related DESC;

0.31  13:22  payments   deployed v5.12.0: upgrade card processor SDK, connection pool size 50
0.16  13:05  web        deployed v2.41.0: new footer, cookie banner copy
0.05  13:47  auth       deployed v4.2.2: rotate session signing key
0.04  12:40  search-api deployed v3.8.1: reindex nightly job moved to 02:00
0.03  13:30  inventory  deployed v1.9.4: add warehouse_code column

The newest deploy, the one everyone blames first, scores 0.05. The payments deploy 36 minutes earlier leads by a wide margin. It's a ranking, not a verdict: it tells you which diff to read first.

Wire it up: deploy job, log shipper and alert webhook all append to events; the PagerDuty webhook runs timeline.py why <alert time> and posts the list to the incident channel. Full timeline.py (40 lines, stdlib only) and the three sample files are in the first comment.

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

When a page fires, what's the first thing you open: the deploy log, the dashboards, or the logs?


r/devops7 • • 15d ago

One script, one chore: 26 alerts at 3 a.m., 24 different texts, 4 monitoring tools. Group the alert storm by meaning in one SQL query and read 7 lines instead (real output)

1 Upvotes

3 a.m. Your phone buzzes 26 times in 45 minutes. Prometheus, Datadog, syslog and Kubernetes all have an opinion, and every one of them words it differently:

Disk usage above 90% on /var (web-03)
web-05: no space left on device while writing /var/log/nginx/access.log
Low disk space: /var on web-06 has 6% free
kernel: Out of memory: Killed process 4121 (java) on app-02
Pod checkout-7f9c restarted: OOMKilled (exit 137)
app-01: getaddrinfo ENOTFOUND payments.internal
...

Dedupe by exact text barely helps: 26 alerts, 24 different strings. What you actually want at 3 a.m. is "how many real problems is this, and which one started first".

The chore: dump the storm into a table, let the database group alerts that mean the same thing, and print one line per group.

(Disclosure: this sub is run by the SynapCores team, and the grouping step is a SynapCores feature. Run this morning on 2.3.2, real output.)

The input: one alert per line, time|source|message (export from your pager or grep your alert channel). The 26-line file is in the first comment.

The script: storm.py (38 lines, stdlib only). It loads the file and embeds every message inside the database:

sql("CREATE TABLE alerts (id INTEGER PRIMARY KEY, at TEXT, source TEXT, message TEXT, embedding VECTOR(384))")
sql("INSERT INTO alerts (id, at, source, message) VALUES " + rows)
sql("UPDATE alerts SET embedding = EMBED(message)")

EMBED runs a local model in the engine. No API key, no calls out.

The one query that does the work

Each alert joins the group of the earliest alert that means the same thing (similarity above 0.4), then we count per group:

SELECT l.id AS grp, COUNT(*) AS alerts, COUNT(DISTINCT a.source) AS tools,
       MIN(a.at) AS first_seen, MAX(a.at) AS last_seen, l.message AS first_alert
FROM (
  SELECT a.id, MIN(b.id) AS leader
  FROM alerts a CROSS JOIN alerts b
  WHERE COSINE_SIMILARITY(a.embedding, b.embedding) > 0.4
  GROUP BY a.id
) g
JOIN alerts a ON a.id = g.id
JOIN alerts l ON l.id = g.leader
GROUP BY l.id, l.message
ORDER BY alerts DESC, grp;

Run it

$ python3 storm.py alerts.txt
26 alerts, 24 different texts, 7 groups by meaning (> 0.4)

alerts  tools  window       first alert
    10      4  03:02-03:41  Disk usage above 90% on /var (web-03)
     6      3  03:11-03:44  Pod checkout-7f9c restarted: OOMKilled (exit 137)
     4      3  03:30-03:33  app-01: getaddrinfo ENOTFOUND payments.internal
     3      2  03:21-03:22  TLS certificate for api.example.com expires in 3 days
     1      1  03:13-03:13  Container memory at 100% of limit for checkout
     1      1  03:31-03:31  app-03: DNS lookup failed for payments.internal (SERVFAIL)
     1      1  03:47-03:47  Replication lag on orders-db-replica is 412 seconds

26 pages became 7 lines. The disk group pulled together "Disk usage above 90%", "no space left on device", "Low disk space ... 6% free" and "[FIRING] filesystem /var almost full" from four different tools, with no regex rules to maintain. The kernel's "Out of memory: Killed process" landed with Kubernetes' "OOMKilled". And the one alert you might have scrolled past (replication lag, 03:47) is its own line instead of being buried under disk spam.

Two of the 7 lines belong with a bigger group: "Container memory at 100%" is the OOM problem, and the 03:31 line (Datadog's "Resolver errors spiking") is the DNS problem. That's the safe direction: a split group costs you one extra line, a wrong merge hides a problem.

Why 0.4 and not lower? I tried 0.3 too. It gives a tidier 5 groups, but it quietly moves checkout-7f9c: dial tcp: lookup payments.internal: no such host into the OOM group, because the pod name matches. That's the wrong merge, so 0.4 stays. Pick yours the same way: run last week's storm at a few values and keep the lowest one that never mixes two problems.

Try it on your own alerts: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-storm (free Community Edition).

Question for you: in your worst alert storm, how many pages was it, and how many actual problems? A rough guess like "~80 pages, 2 problems" is perfect.


r/devops7 • • 19d ago

Automate it #5: a post-deploy smoke test that catches the "200 OK, Oops! Something went wrong" page, keeps every result, and gives you a one-query dashboard (real output)

1 Upvotes

Most post-deploy smoke tests are curl -f in a loop: every URL returns 200, ship it. Then checkout serves a friendly "Oops! Something went wrong" page with a 200, and the test is green while customers can't pay.

Diffing the body against last time doesn't help: prices, products and timestamps change on every request.

So after each deploy this smoke test checks status and latency, asks whether each 200 still looks like the pages that passed before (by meaning, not byte for byte), and stores every result so "which deploy broke checkout?" is one query.

(Disclosure: this sub is run by the SynapCores team, and step 2 uses SynapCores. Run this morning on 2.3.2, real output.)

Setup, once

CREATE TABLE smoke_results (deploy TEXT, check_name TEXT, status INTEGER, ms INTEGER,
                            body TEXT, body_vec VECTOR(384), verdict TEXT);

checks.txt is one name url per line:

home      https://shop.example.com/
search    https://shop.example.com/search?q=jacket
checkout  https://shop.example.com/checkout
login     https://shop.example.com/login
orders    https://shop.example.com/api/orders

Step 1: hit every URL, store what came back

smoke.py strips the tags and keeps the first 500 characters. EMBED() runs a small model inside the database and stores what that text means, in the same INSERT:

code, ms, text = fetch(url)
sql(f"""INSERT INTO smoke_results (deploy, check_name, status, ms, body, body_vec, verdict)
        VALUES ({quote(deploy)}, {quote(name)}, {code}, {ms}, {quote(text)}, EMBED({quote(text)}), 'NEW')""")

Step 2: does today's page mean the same thing as the pages that passed?

Each check's best similarity to every earlier passing response of that check, plus its usual latency:

SELECT r.check_name, r.status, r.ms, r.body,
       MAX(COSINE_SIMILARITY(r.body_vec, b.body_vec)) AS like_good, AVG(b.ms) AS usual_ms
FROM smoke_results r LEFT JOIN smoke_results b ON b.check_name = r.check_name AND b.verdict = 'PASS'
WHERE r.deploy = 'v1.46'
GROUP BY r.check_name, r.status, r.ms, r.body;

Verdict in Python: not 200 is FAIL, a 200 under 0.6 is WRONG_PAGE, over 3x usual latency (and +300 ms) is SLOW. Anything but PASS exits 1.

Run it

Test shop for this post: a tiny app with different products, prices and result counts on every deploy, so no two responses are equal. Six normal deploys, then v1.46 breaks three things three ways. A normal deploy:

$ python3 smoke.py v1.45 checks.txt
PASS       checkout  200   115 ms  looks like a good page: 0.93  | Checkout Your cart: 2 items, subtotal $64.3. Shipping addres
PASS       home      200    73 ms  looks like a good page: 0.96  | Northwind Outdoor New this week: Fleece Vest, Merino Tee, Tr
PASS       login     200   111 ms  looks like a good page: 1.00  | Sign in Email Password Sign in Forgot password?
PASS       orders    200    97 ms  looks like a good page: 0.99  | {"orders": [{"id": 9315, "status": "shipped", "total": 206.1
PASS       search    200    48 ms  looks like a good page: 0.82  | 11 results for jacket Fleece Vest jacket $99 Trail Runner 2
v1.45: 5/5 passed

Different subtotal, different products, different result count, and still 0.82 to 0.96: same kind of page. The broken deploy:

$ python3 smoke.py v1.46 checks.txt
WRONG_PAGE checkout  200    53 ms  looks like a good page: 0.13  | Oops! Something went wrong on our end. Please try again late
PASS       home      200   124 ms  looks like a good page: 0.76  | Northwind Outdoor New this week: Headlamp 300, Trail Runner
PASS       login     200    58 ms  looks like a good page: 1.00  | Sign in Email Password Sign in Forgot password?
FAIL       orders    502   121 ms  looks like a good page: 0.16  | 502 Bad Gateway nginx
SLOW       search    200  1021 ms  looks like a good page: 0.81  | 9 results for jacket Merino Tee jacket $63 Wool Socks jacket
v1.46: 2/5 passed

Exit code 1. curl -f would have caught the 502 and nothing else. Checkout returned 200 and scores 0.13 against its own good pages; search returned the right page, just more than 10x slower than usual.

Is 0.6 a safe cut? Across all 7 deploys, the lowest score a passing response got was 0.76 (home, whose product list changes every time). The broken pages scored 0.13 and 0.16. Check yours over a week of real deploys before you trust it.

Step 3: the dashboard query

SELECT deploy, COUNT(*) AS checks,
       SUM(CASE WHEN verdict = 'PASS' THEN 1 ELSE 0 END) AS passed,
       SUM(CASE WHEN verdict = 'WRONG_PAGE' THEN 1 ELSE 0 END) AS wrong_page,
       SUM(CASE WHEN verdict = 'FAIL' THEN 1 ELSE 0 END) AS failed,
       SUM(CASE WHEN verdict = 'SLOW' THEN 1 ELSE 0 END) AS slow,
       MAX(ms) AS slowest_ms
FROM smoke_results GROUP BY deploy ORDER BY deploy;

deploy  checks passed wrong_page failed slow slowest_ms
v1.40        5      5          0      0    0        107
v1.41        5      5          0      0    0        125
v1.42        5      5          0      0    0        102
v1.43        5      5          0      0    0        110
v1.44        5      5          0      0    0        126
v1.45        5      5          0      0    0        115
v1.46        5      2          1      1    1       1021

Wire it up: last step of your deploy job, python3 smoke.py $VERSION checks.txt || ./rollback.sh. Only PASS rows become the baseline, so a broken page never teaches the test that "Oops!" is normal. Full smoke.py (49 lines, stdlib only) is in the first comment, the test app right under it.

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

What's the sneakiest "it returned 200 but was broken" you've shipped?


r/devops7 • • 20d ago

One script, one chore: the on-call handoff nobody reads at 9 a.m. Write notes all night, get "where things stand + what changed" in one command (real output)

1 Upvotes

The night shift leaves 40 lines in the incident channel. The morning person skims, sees "suspect deploy 4182", and rolls it back again. Nobody wrote down that the rollback was tried at 02:05 and didn't help, or they did, but it's line 23.

The chore: make every handoff note a fact with a name (status, suspect, tried, next_step), so the next person gets the latest value of each one plus what changed overnight, instead of scrolling.

(Disclosure: this sub is run by the SynapCores team, and the memory step below is a SynapCores feature. Run this morning on 2.3.2, real output.)

Setup, once

CREATE MEMORY handoff IDENTITY service WITH (llm_extraction = false);

A MEMORY keeps facts per identity (here: per service). When a new note sets an attribute that already has a value, the new value becomes current and the old one becomes history.

The script: handoff.py (28 lines, stdlib only)

The two commands that matter:

# note: one fact per line
sql(f"""REMEMBER handoff FOR service = {quote(svc)} {quote(text)}
        WITH (source_type = 'verified_user_statement', attribute = {quote(attr)}, value = {quote(value)})""")

# brief: current value of every fact, what changed, and the notes closest to your question
d = sql(f"RECALL handoff FOR service = {quote(svc)} ABOUT {quote(ask or 'current state')}")["data"]
for attr, s in d["current_state"].items():
    print(f"  {attr:<10} {s['value']}")
for t in d["temporal"]:
    print(f"  changed: {t['attribute']} {t['previous_value']} -> {t['current_value']}")

(Full file in the first comment.)

The night shift, as it happened

python3 handoff.py note payments-api status investigating "01:10 p99 latency on payments-api jumped to 2.4s, right after deploy 4182"
python3 handoff.py note payments-api suspect deploy-4182 "Suspect deploy 4182, it added retry logic around the card provider"
python3 handoff.py note payments-api tried rollback "02:05 rolled back 4182. p99 still 2.1s, so it is not the deploy"
python3 handoff.py note payments-api suspect db-pool "payments-db connections at 198/200, pool exhausted"
python3 handoff.py note payments-api status mitigated "03:40 raised the pool to 300, p99 back to 180ms. Not root-caused"
python3 handoff.py note payments-api next_step "check the nightly reconciliation job" "Next: find what holds the connections, start with the nightly reconciliation job"

9 a.m., the morning person runs one command

$ python3 handoff.py brief payments-api
== payments-api: where things stand
  next_step  check the nightly reconciliation job
  status     mitigated
  suspect    db-pool
  tried      rollback
  changed: status investigating -> mitigated
  changed: suspect deploy-4182 -> db-pool

The deploy theory is still in the history, but it's marked as replaced: suspect deploy-4182 -> db-pool. Nobody rolls back twice.

And when they have a specific question

$ python3 handoff.py brief payments-api "did anyone already try a rollback"
...
== closest notes to: did anyone already try a rollback
  0.26  02:05 rolled back 4182. p99 still 2.1s, so it is not the deploy
  0.24  Suspect deploy 4182, it added retry logic around the card provider

The question shares almost no words with the note ("try a rollback" vs "rolled back 4182"), and it still comes back first, because RECALL matches the original notes by meaning.

Wire it up: a Slack slash command that calls handoff.py note ..., and the on-call bot posts handoff.py brief <service> into the channel at shift change. One memory serves every service; FOR service = 'checkout-web' keeps its facts separate.

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

What's the one thing you wish the previous on-call had written down?


r/devops7 • • 21d ago

Automate it #4: "disk full in N days" from one SQL query, plus the check that catches a box that started filling 16x faster today (real output)

1 Upvotes

A 90% disk alert fires too late to do anything calm about it. A trend line ("full in 27 days") is better, but it is slow: the morning someone leaves DEBUG logging on, a 14-day trend still says you have two months.

So this daily job does two things with one table of df samples:

  1. Trend: least-squares slope over the last 14 days, so you get "full in N days" per server.
  2. Odd day: scores today's growth against what each server usually does, and flags the box that is suddenly filling much faster than normal, before the trend notices.

(Disclosure: this sub is run by the SynapCores team, and step 2 uses SynapCores. Run this morning on 2.3.2, real output.)

Collect: one line per server per day

for h in web-01 db-01 app-02 cache-01 logs-01; do
  ssh $h "df -P /" | awk -v h=$h -v d=$(date +%F) 'NR==2{print d, h, $6, $5+0}'
done | python3 disk_trend.py ingest

That prints 2026-11-03 web-01 / 62 lines. The script stores each one with today's growth, the server's usual growth (its 14-day average) and the difference:

CREATE TABLE disk_samples (day TEXT, host TEXT, mount TEXT, used_pct REAL, growth REAL, usual REAL, excess REAL);

For this post: 30 days of samples for 5 test servers (seeded generator in the first comment, so you can reproduce every number). On the last day, logs-01 gets a DEBUG-logging spike.

Step 1, the trend: plain SQL, nothing special

SELECT s.host, s.mount, MAX(t.used_pct) AS used,
       (COUNT(*)*SUM(s.n*s.used_pct) - SUM(s.n)*SUM(s.used_pct)) / (COUNT(*)*SUM(s.n*s.n) - SUM(s.n)*SUM(s.n)) AS slope
FROM (SELECT host, mount, used_pct, DATEDIFF(day, '2026-11-03') AS n FROM disk_samples
      WHERE DATEDIFF(day, '2026-11-03') > -14) s
JOIN disk_samples t ON t.host = s.host AND t.mount = s.mount AND t.day = '2026-11-03'
GROUP BY s.host, s.mount;

Then (100 - used) / slope in Python is the days left. Here is every server:

TREND cache-01  /  33.3% used, +0.10/day -> full in 643 days
TREND db-01     /  78.1% used, +0.80/day -> full in 27 days
TREND logs-01   /  64.6% used, +0.54/day -> full in 66 days
TREND web-01    /  62.2% used, +0.24/day -> full in 159 days

db-01 is the one to plan for. logs-01 looks fine: 66 days.

Step 2, the odd day: an anomaly model in the database, scored inside the SELECT

Every morning, retrain on the last 30 days (the whole report runs in under 0.1 s for 150 rows), then score today:

CREATE EXPERIMENT disk_growth_exp AS
  SELECT excess FROM disk_samples WHERE DATEDIFF('2026-11-03', day) <= 30
WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'], max_trials = 5, random_seed = 42);
DEPLOY MODEL disk_growth_model FROM EXPERIMENT disk_growth_exp;

SELECT host, mount, used_pct, growth, usual, ANOMALY_SCORE('disk_growth_model', excess) AS score
FROM disk_samples WHERE day = '2026-11-03' AND ANOMALY_SCORE('disk_growth_model', excess) > 0.8;

No labels and no per-server thresholds. "Weird" is learned from 30 days of what your fleet normally does, and excess (today minus usual) keeps a fast-growing DB from looking weird just for being busy.

Run it

Yesterday's run, before the spike:

$ python3 disk_trend.py report 2026-11-02
TREND db-01     /  77.2% used, +0.79/day -> full in 29 days

This morning:

$ python3 disk_trend.py report 2026-11-03
TREND db-01     /  78.1% used, +0.80/day -> full in 27 days
ODD   logs-01   /  +6.1 pts today, usually +0.37 (anomaly 0.91) -> at today's rate full in 6 days

The trend still says logs-01 has 66 days. The anomaly score says something changed today, and at today's rate it has 6. The top 5 scores over all 150 server-days:

logs-01   2026-11-03   +6.1   usual 0.37   0.91
db-01     2026-10-06   +1.0   usual 0.00   0.79
cache-01  2026-10-09   -0.3   usual 0.23   0.75
cache-01  2026-10-12   -0.3   usual 0.11   0.67
logs-01   2026-10-06   +0.5   usual 0.00   0.66

The spike is alone above 0.8. db-01 grew +0.9 today, like most days, and scores 0.37: busy, not odd.

Wire it up: 30 7 * * * collect.sh && python3 disk_trend.py report $(date +%F) | grep -E 'TREND|ODD', then send that to Slack. TREND lines are for the weekly capacity chat, ODD lines are for today. Full disk_trend.py (about 50 lines, stdlib only) and the sample generator are in the first comment.

Update: inodes. A reader pointed out that inodes can run out long before the disk percentage looks scary. No second table needed: collect df -Pi as its own "mount", and both checks run unchanged, because everything groups by host + mount:

ssh $h "df -Pi /" | awk -v h=$h -v d=$(date +%F) 'NR==2{print d, h, $6":inodes", $5+0}'

Same seeded fleet on 2.3.2, plus an app-02 that sits at ~41% disk but uses ~1.1% of its inodes a day (lots of tiny cache files). Generator for that, so you can reproduce it:

import random, datetime
random.seed(11)
start, u = datetime.date(2026, 10, 5), 52.0
for d in range(30):
    if d: u += max(0.0, random.gauss(1.1, 0.15))
    print((start + datetime.timedelta(days=d)).isoformat(), "app-02", "/:inodes", round(u, 1))

Output:

$ WARN_DAYS=60 python3 disk_trend.py report 2026-11-03
TREND app-02    /:inodes  84.1% used, +1.10/day -> full in 14 days
TREND db-01     /  78.1% used, +0.80/day -> full in 27 days
ODD   logs-01   /  +6.1 pts today, usually +0.37 (anomaly 0.91) -> at today's rate full in 6 days

app-02's disk line never shows up (it has years left), but its inodes run out in two weeks.

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

What filled up a disk on you the fastest: logs, core dumps, Docker images, or something stranger?


r/devops7 • • 22d ago

One script, one chore: send each alert to the team that owns it, matched by meaning (no regex routing rules, ~25 lines of Python)

1 Upvotes

Alert routing usually starts as a few regex rules (/postgres|pg-/ -> #db-oncall) and ends as 200 of them that nobody dares to touch. Every new tool phrases things its own way, so the rules never cover the alert that actually wakes you up, and it lands in the wrong channel.

The chore: write one sentence per team saying what they own, and send each alert to the team whose sentence is closest in meaning. If nothing is close, send it to a triage channel instead of guessing.

(Disclosure: this sub is run by the SynapCores team, and the matching step below uses SynapCores. Tested on 2.3.2 this morning.)

Setup, once: one row per team

CREATE TABLE team_owners (team TEXT PRIMARY KEY, channel TEXT, owns TEXT, embedding VECTOR(384));
INSERT INTO team_owners (team, channel, owns) VALUES
 ('database', '#db-oncall', 'Postgres primary and replicas, replication lag, slow queries, connection pool exhaustion, vacuum'),
 ('platform', '#platform-oncall', 'Kubernetes nodes and pods, container restarts, memory limits, disk space on hosts, autoscaling'),
 ('network', '#net-oncall', 'load balancers, DNS resolution, TLS certificates, ingress, packet loss, VPN'),
 ('payments', '#payments-oncall', 'checkout API, card authorization failures, payment provider webhooks, refunds');
UPDATE team_owners SET embedding = EMBED(owns);

CREATE TABLE incoming_alerts (id INTEGER PRIMARY KEY, alert TEXT, embedding VECTOR(384));

EMBED() runs a small embedding model inside the database and stores what each sentence means as 384 numbers. No API key, nothing leaves the box.

The script: route_alerts.py

alerts = [line.strip() for line in open(sys.argv[1]) if line.strip()]
sql("DELETE FROM incoming_alerts")
sql("INSERT INTO incoming_alerts (id, alert) VALUES " + ", ".join(f"({i}, {quote(a)})" for i, a in enumerate(alerts, 1)))
sql("UPDATE incoming_alerts SET embedding = EMBED(alert)")
rows = sql("""SELECT a.id, a.alert, t.channel, COSINE_SIMILARITY(a.embedding, t.embedding) AS score
              FROM incoming_alerts a, team_owners t ORDER BY a.id, score DESC""")
best = {}
for i, alert, channel, score in rows:
    best.setdefault(i, (alert, channel, score))
for alert, channel, score in best.values():
    if score < 0.3:
        channel = "#ops-triage"
    print(f"{channel:<17} {score:.2f}  {alert}")

(The sql() and quote() helpers are 8 lines; they're in the first comment.)

Run it on this morning's 7 alerts

$ python3 route_alerts.py alerts.txt
#db-oncall        0.67  pg-replica-2 is 340s behind primary
#platform-oncall  0.51  pod api-7f9c restarted 6 times in 10 min (CrashLoopBackOff)
#ops-triage       0.21  NXDOMAIN for internal.api.svc from 3 resolvers
#payments-oncall  0.58  stripe webhook deliveries failing with 401 since 09:12
#platform-oncall  0.59  node ip-10-0-3-17 disk 94% full on /var/lib/kubelet
#db-oncall        0.39  too many clients already: pool at 200/200 on db-primary
#ops-triage       0.12  marketing site hero image returns 404

Look at too many clients already: pool at 200/200. It never says "Postgres" or "connection", and CrashLoopBackOff never says "container restarts", yet both land with the right team. The marketing 404 matches nobody (0.12), so it goes to triage instead of waking the payments on-call.

When triage gets one that has an owner, teach the owner's sentence

The NXDOMAIN alert was closest to network (0.21) but under the 0.3 cut, so it went to triage. That's the safe default. Once a human says "that's network", add the words:

UPDATE team_owners SET owns = owns || ', NXDOMAIN and resolver errors' WHERE team = 'network';
UPDATE team_owners SET embedding = EMBED(owns) WHERE team = 'network';

Re-run:

#net-oncall       0.40  NXDOMAIN for internal.api.svc from 3 resolvers
#ops-triage       0.12  marketing site hero image returns 404

One edit to a sentence instead of a new regex, and the other six routes stay the same. Pick your cut-off from a week of real alerts: the scores of correct routes here run 0.39–0.67 and the non-matches 0.12–0.21.

Free Community Edition if you want to try it: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-route-alerts

What's the alert that most often ends up in the wrong channel on your team?


r/devops7 • • 25d ago

What broke this week? Drop a one-liner. (Plus how we check each new incident against old ones by meaning, so repeats come with their old fix)

1 Upvotes

Friday thread. What broke for you this week? One line is plenty: what failed, and what fixed it (or "still don't know").

A lot of "new" incidents are repeats of something someone already fixed, just described differently. "Build servers ran out of disk space" and "docker host filled up with old images" are the same problem, but grep won't connect them. So we keep a small incident notebook and match each new one against it by meaning.

(Disclosure: this sub is run by the SynapCores team, and the matching step uses SynapCores. Run this morning on 2.3.2, real output.)

The notebook: past incidents and what fixed them

CREATE TABLE incidents (id INTEGER PRIMARY KEY, happened TEXT, what_broke TEXT, fix TEXT, embedding VECTOR(384));
INSERT INTO incidents (id, happened, what_broke, fix) VALUES
 (1, '2026-08-14', 'cron job silently stopped after the server moved to UTC', 'pin TZ in the crontab and alert on missed runs'),
 (2, '2026-09-02', 'postgres ran out of connections during a traffic spike, app got connection errors', 'put pgbouncer in front, cap the app pool at 20'),
 (3, '2026-09-19', 'docker host ran out of disk space, old images filled it up', 'weekly docker image prune -a --filter until=168h'),
 (4, '2026-10-03', 'expired TLS cert on the internal API', 'certbot renew + daily expiry check'),
 (5, '2026-10-11', 'deploy went out with a missing env var and the app crash-looped', 'validate required env vars in CI before deploy');
UPDATE incidents SET embedding = EMBED(what_broke);

This week's one-liners, in whatever words people used

CREATE TABLE this_week (id INTEGER PRIMARY KEY, reply TEXT, embedding VECTOR(384));
INSERT INTO this_week (id, reply) VALUES
 (1, 'our build servers ran out of disk space again'),
 (2, 'the database hit max connections when traffic jumped after the newsletter'),
 (3, 'the nightly report job never ran after the clocks changed'),
 (4, 'someone rotated the S3 keys and forgot the backup script');
UPDATE this_week SET embedding = EMBED(reply);

Seen it before? Show the old fix

SELECT w.reply, i.happened, i.fix,
       ROUND(COSINE_SIMILARITY(w.embedding, i.embedding), 2) AS match
FROM this_week w CROSS JOIN incidents i
WHERE COSINE_SIMILARITY(w.embedding, i.embedding) > 0.4
ORDER BY w.id;

our build servers ran out of disk space again
    2026-09-19  weekly docker image prune -a --filter until=168h  0.51
the database hit max connections when traffic jumped after the newsletter
    2026-09-02  put pgbouncer in front, cap the app pool at 20    0.51
the nightly report job never ran after the clocks changed
    2026-08-14  pin TZ in the crontab and alert on missed runs    0.49

The wording differs from the old write-ups ("clocks changed" vs "moved to UTC", "build servers" vs "docker host"), and each one still lands on the right fix. Every wrong pairing scored 0.27 or lower.

Genuinely new? That's the one worth a postmortem

SELECT w.reply, ROUND(MAX(COSINE_SIMILARITY(w.embedding, i.embedding)), 2) AS best
FROM this_week w CROSS JOIN incidents i
GROUP BY w.reply
HAVING MAX(COSINE_SIMILARITY(w.embedding, i.embedding)) < 0.4;

someone rotated the S3 keys and forgot the backup script   0.2

So the Friday routine is: three repeats get their old fix pasted into the ticket, and one new incident gets written up and added to the notebook. Next time it'll match too.

If you want to try it: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-whatbroke-1030 (free Community Edition).

Your turn: what broke this week, and was it a repeat of something you'd fixed before?


r/devops7 • • 26d ago

Automate it #3: a daily SSL check that warns 14 days before expiry, keeps history, and prints the fix when a cert is already broken

1 Upvotes

Expiry checks are easy. The hard part is the 6 a.m. page that says unable to get local issuer certificate while whoever is on call tries to remember what that means.

So this checker, every morning:

  1. Checks every host, the same way a client would.
  2. Stores every result, so you have history instead of a one-off grep.
  3. Warns 14 days ahead. When a cert is already broken, it prints the fix from your runbook next to the error.

(Disclosure: this sub is run by the SynapCores team, and step 3 uses SynapCores. Run this morning on 2.3.2, real output.)

Setup, once: a results table and a 4-line runbook

CREATE TABLE cert_checks (host TEXT, checked_at TEXT, expires TEXT, days_left INTEGER, issuer TEXT, error TEXT, embedding VECTOR(384));
CREATE TABLE cert_fixes (id INTEGER PRIMARY KEY, problem TEXT, fix TEXT, embedding VECTOR(384));
INSERT INTO cert_fixes (id, problem, fix) VALUES
 (1, 'the certificate is out of date: its end date has passed and nobody renewed it', 'renew it: certbot renew --cert-name HOST, then reload nginx'),
 (2, 'the certificate is for a different domain name than the one the client asked for', 'add the name to the certificate (certbot -d HOST) or fix server_name / DNS'),
 (3, 'the server certificate is signed by itself, not by any certificate authority', 'replace it with a Let''s Encrypt certificate'),
 (4, 'chain incomplete: the issuer''s certificate is not available to the client', 'serve fullchain.pem instead of cert.pem');
UPDATE cert_fixes SET embedding = EMBED(problem);

The runbook is in human words, not error strings. EMBED() runs a small model inside the database and stores what each line means.

The script: cert_check.py (stdlib only; the sql()/quote() helpers are in the first comment)

def check(host):
    try:
        with socket.create_connection((host, 443), timeout=10) as s:
            with ssl.create_default_context().wrap_socket(s, server_hostname=host) as t:
                cert = t.getpeercert()
        expires = datetime.datetime.fromtimestamp(ssl.cert_time_to_seconds(cert["notAfter"]), datetime.UTC)
        issuer = dict(x[0] for x in cert["issuer"]).get("organizationName")
        return expires.date().isoformat(), (expires - datetime.datetime.now(datetime.UTC)).days, issuer, None
    except ssl.SSLCertVerificationError as e:
        return None, None, None, e.verify_message
    except OSError as e:
        return None, None, None, str(e)

now = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S")
for host in open(sys.argv[1]).read().split():
    expires, days, issuer, error = check(host)
    sql(f"""INSERT INTO cert_checks (host, checked_at, expires, days_left, issuer, error, embedding)
            VALUES ({quote(host)}, {quote(now)}, {quote(expires)}, {days if days is not None else 'NULL'},
                    {quote(issuer)}, {quote(error)}, {'EMBED(' + quote(error) + ')' if error else 'NULL'})""")

# 1. expiring soon: plain SQL over this run
for host, days, issuer in sql(f"""SELECT host, days_left, issuer FROM cert_checks WHERE checked_at = {quote(now)}
                                  AND days_left <= {WARN_DAYS} ORDER BY days_left"""):
    print(f"WARN  {host:<28} expires in {days} days ({issuer})")

# 2. broken right now: match the error by meaning to the runbook and print the fix with it
for host, error in sql(f"SELECT host, error FROM cert_checks WHERE checked_at = {quote(now)} AND error IS NOT NULL ORDER BY host"):
    fix, score = sql(f"""SELECT f.fix, COSINE_SIMILARITY(c.embedding, f.embedding) AS score FROM cert_checks c, cert_fixes f
                         WHERE c.host = {quote(host)} AND c.checked_at = {quote(now)} ORDER BY score DESC LIMIT 1""")[0]
    print(f"FAIL  {host:<28} {error}\n      fix ({score:.2f}): {fix.replace('HOST', host)}")

Run it

hosts.txt: 3 healthy sites plus 4 deliberately broken badssl.com hosts:

$ python3 cert_check.py hosts.txt
FAIL  expired.badssl.com           certificate has expired
      fix (0.85): renew it: certbot renew --cert-name expired.badssl.com, then reload nginx
FAIL  incomplete-chain.badssl.com  unable to get local issuer certificate
      fix (0.63): serve fullchain.pem instead of cert.pem
FAIL  self-signed.badssl.com       self-signed certificate
      fix (0.65): replace it with a Let's Encrypt certificate
FAIL  wrong.host.badssl.com        Hostname mismatch, certificate is not valid for 'wrong.host.badssl.com'.
      fix (0.60): add the name to the certificate (certbot -d wrong.host.badssl.com) or fix server_name / DNS
2026-10-29 14:04:15 UTC: 3 ok

Four failures, four right fixes. unable to get local issuer certificate never says what's wrong; by meaning it lands on "chain incomplete": the classic "works in Chrome, fails in curl" missing intermediate. The page says to serve fullchain.pem.

Nothing is inside 14 days today, so here's a wider window to show a warning:

$ WARN_DAYS=35 python3 cert_check.py hosts.txt
WARN  github.com                   expires in 31 days (Sectigo Limited)
(then the same 4 FAIL lines)

Wire it up: 0 7 * * * python3 cert_check.py hosts.txt | grep -A1 -E 'WARN|FAIL', then send that to Slack. Every run stays in cert_checks, so "when did this last renew?" is one query. New kind of failure? Add a line to cert_fixes. More wording (curl, Go) in the first comment.

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

What's the TLS error that cost you the longest debugging session?


r/devops7 • • 28d ago

New in v2.4.0: 3 Ollama tutorials (rag with one option, plain-English SQL that keeps PII private, a support bot that's just a model name)

Thumbnail
reddit.com
1 Upvotes

r/devops7 • • 28d ago

Automate it #2: check your access logs every hour, but page only for a new kind of attack (not every new IP)

1 Upvotes

Part 1 found the scanner and the scraper in an access log by hand. Next step is cron: run it hourly, send the result to Slack. Within a week you'll mute the channel: scanners rotate IPs constantly, so "alert on every new bad IP" pages you for the same attack over and over.

The real question each hour: new kind of attack, or the same one from a new address? Same one: block quietly. New kind: page a human.

(Disclosure: this sub is run by the SynapCores team, and the matching step uses SynapCores. Run this morning on 2.3.2, real output.)

Setup, once

CREATE TABLE hour_log (ip TEXT, method TEXT, path TEXT, status INTEGER);
CREATE TABLE suspects (ip TEXT, signature TEXT, embedding VECTOR(384));
CREATE TABLE offenders (ip TEXT, first_seen TEXT, signature TEXT, embedding VECTOR(384));

The script: hourly.py

import json, os, re, sys, urllib.request
URL, TOKEN = os.environ.get("SYNAPCORES_URL", "http://localhost:8080"), os.environ["SYNAPCORES_TOKEN"]
LINE = re.compile(r'(\S+) \S+ \S+ \[([^:]+:\d\d)[^\]]*\] "(\S+) (\S+) [^"]*" (\d{3})')

def sql(q):
    req = urllib.request.Request(URL + "/v1/query/execute", data=json.dumps({"sql": q, "database": "main"}).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(req))["data"]["rows"]

def quote(s):
    return "'" + s.replace("'", "''") + "'"

rows = [m.groups() for m in map(LINE.match, open(sys.argv[1])) if m]
hour = rows[0][1]
sql("DELETE FROM hour_log")
for i in range(0, len(rows), 200):
    sql("INSERT INTO hour_log (ip, method, path, status) VALUES " + ", ".join(
        f"({quote(ip)}, {quote(m)}, {quote(re.sub(r'[0-9]+', 'N', p.split('?')[0]))}, {s})"
        for ip, h, m, p, s in rows[i:i + 200]))

# 1. the checks from part 1, per hour: secret probing, scraping, password guessing
suspects = sql("""SELECT ip FROM hour_log WHERE ip NOT IN (SELECT ip FROM offenders) GROUP BY ip
                  HAVING SUM(CASE WHEN status = 404 THEN 1 ELSE 0 END) >= 10 OR COUNT(*) >= 200
                      OR SUM(CASE WHEN status = 401 THEN 1 ELSE 0 END) >= 20 ORDER BY ip""")

# 2. describe what each suspect did, in words, and compare by meaning with every attack already paged
sql("DELETE FROM suspects")
for (ip,) in suspects:
    top = sql(f"""SELECT method, path, status, COUNT(*) AS n FROM hour_log WHERE ip = {quote(ip)}
                  GROUP BY method, path, status ORDER BY n DESC, path LIMIT 6""")
    sig = "; ".join(f"{m} {p} {s}" for m, p, s, n in top)
    sql(f"INSERT INTO suspects (ip, signature, embedding) VALUES ({quote(ip)}, {quote(sig)}, EMBED({quote(sig)}))")

# 3. page only for a new kind of attack; a known attack from a new IP just joins the blocklist
for (ip,) in suspects:
    best = sql(f"""SELECT o.ip, COSINE_SIMILARITY(s.embedding, o.embedding) AS sim FROM suspects s, offenders o
                   WHERE s.ip = {quote(ip)} ORDER BY sim DESC LIMIT 1""")
    if best and best[0][1] >= 0.6:
        print(f"quiet  {ip:<15} same attack as {best[0][0]} ({best[0][1]:.2f}), added to blocklist")
    else:
        print(f"PAGE   {ip:<15} new kind of attack")
    sql(f"""INSERT INTO offenders (ip, first_seen, signature, embedding)
            SELECT ip, {quote(hour)}, signature, embedding FROM suspects WHERE ip = {quote(ip)}""")
print(f"{hour}h: {len(rows)} requests, {len(suspects)} new suspect(s)")

Each suspect gets a short signature (its 6 most common METHOD path status lines). EMBED() turns it into a vector inside the database, and COSINE_SIMILARITY compares it with every attack on file. 0.6 or higher = same attack: blocklist, no page.

Run it on two hours of traffic

$ python3 hourly.py access-09.log
PAGE   192.0.2.77      new kind of attack
PAGE   198.51.100.23   new kind of attack
27/Oct/2026:09h: 434 requests, 2 new suspect(s)
$ python3 hourly.py access-10.log
quiet  104.28.40.17    same attack as 198.51.100.23 (0.90), added to blocklist
PAGE   198.51.100.140  new kind of attack
27/Oct/2026:10h: 387 requests, 2 new suspect(s)
$ python3 hourly.py access-10.log
27/Oct/2026:10h: 387 requests, 0 new suspect(s)

Hour 10 is the interesting one. 198.51.100.23 came back but is already known. 104.28.40.17 is a new IP probing completely different paths (/.env.production, /.git/HEAD, /backup.sql, /.ssh/id_rsa vs /.env, /.git/config, /.aws/credentials). Not one path in common, so exact matching would page you again. By meaning it's the same "hunting for secret files" attack (0.90), so it's blocked quietly. The password guesser (POST /login 401 x90) scores 0.24 at most against anything on file, so it's the only page. Rerun: silence.

Wire it up: cron it at 5 * * * * on last hour's log, send grep PAGE to Slack, and feed SELECT ip FROM offenders to fail2ban. Same attack scored 0.90, different ones 0.24 or less, so 0.6 sits in the gap; check yours on a week of real logs.

Sample logs: first comment. Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-automate-it-2

What attack fills your logs most: .env hunters, wp-login guessers, or something weirder?


r/devops7 • • 29d ago

One script, one chore: which errors in last night's log are actually new? (20 lines of Python, match by meaning instead of grep)

1 Upvotes

Every morning someone scrolls last night's errors and asks the same thing: is any of this new, or is it the usual noise?

grep -v and exact-match dedup don't help, because the usual noise never repeats exactly. attempt 3/5 becomes attempt 5/5, after 30s becomes after 30000ms, 93% becomes 95%. So every line looks new and you stop reading.

The chore: keep a list of errors you've already triaged, and print only the lines that don't mean the same thing as anything on it.

(Disclosure: this sub is run by the SynapCores team, and the matching step below uses SynapCores. Tested on 2.3.2 this morning.)

Setup, once

CREATE TABLE known_errors (id INTEGER PRIMARY KEY, msg TEXT, embedding VECTOR(384));
CREATE TABLE todays_errors (id INTEGER PRIMARY KEY, msg TEXT, embedding VECTOR(384));

INSERT INTO known_errors (id, msg) VALUES
 (1, 'connection refused to db-primary:5432'),
 (2, 'timeout waiting for upstream payments-api after 30s'),
 (3, 'disk usage above 90% on /var/lib/docker'),
 (4, 'OOMKilled: container worker exceeded memory limit 512Mi'),
 (5, 'TLS handshake failed: certificate expired for api.internal');

UPDATE known_errors SET embedding = EMBED(msg);

EMBED() runs a small embedding model inside the database and stores what each message means as 384 numbers. No API key.

The script: new_errors.py

import json, os, sys, urllib.request
URL, TOKEN = os.environ.get("SYNAPCORES_URL", "http://localhost:8080"), os.environ["SYNAPCORES_TOKEN"]

def sql(q):
    req = urllib.request.Request(URL + "/v1/query/execute", data=json.dumps({"sql": q, "database": "main"}).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(req))["data"]["rows"]

def quote(s):
    return "'" + s.replace("'", "''") + "'"

errors = sorted({line.split(" ERROR ", 1)[1].strip() for line in open(sys.argv[1]) if " ERROR " in line})
sql("DELETE FROM todays_errors")
sql("INSERT INTO todays_errors (id, msg) VALUES " +
    ", ".join(f"({i}, {quote(e)})" for i, e in enumerate(errors, 1)))
sql("UPDATE todays_errors SET embedding = EMBED(msg)")
for msg, closest in sql("""SELECT t.msg, MAX(COSINE_SIMILARITY(t.embedding, k.embedding)) AS closest
                           FROM todays_errors t, known_errors k GROUP BY t.msg
                           HAVING MAX(COSINE_SIMILARITY(t.embedding, k.embedding)) < 0.6 ORDER BY closest"""):
    print(f"NEW  {closest:.2f}  {msg}")

Run it on last night's log (9 lines, 7 of them ERROR)

$ python3 new_errors.py app.log
NEW  0.16  redis: READONLY You can't write against a read only replica
NEW  0.19  permission denied writing to /var/log/app/audit.log

Two out of seven. The other five were dropped because each is close in meaning to a known error (1.0 = same meaning):

disk usage 93% on /var/lib/docker                         0.97
container worker OOMKilled, memory limit 512Mi reached    0.97
connection refused to db-primary:5432 (attempt 3/5)       0.96
connection refused to db-primary:5432 (attempt 5/5)       0.95
upstream payments-api timed out after 30000ms             0.89

Look at timed out after 30000ms vs timeout waiting for upstream payments-api after 30s: different words, different units, still 0.89. That's the line exact-match dedup can never catch. The gap between 0.89 and 0.19 is wide, so 0.6 is a safe cut here; check yours on a week of real logs before trusting it.

Once you've triaged a new one, teach it

INSERT INTO known_errors (id, msg, embedding)
  SELECT 100 + id, msg, embedding FROM todays_errors WHERE id IN (5, 6);

Tomorrow those two stay quiet too. Put the script in cron at 08:00, pipe the output to Slack, and an empty message means a boring night.

Free Community Edition if you want to try it: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-new-errors

What's one error message your team has learned to ignore?


r/devops7 • • Oct 23 '26

Find the bots hammering your server: load your nginx access log into SQL and ask 5 questions (beginner, ~15 min)

1 Upvotes

Grepping access logs works until the question gets interesting: who is probing for .env files? Who sent 240 requests in one minute? Is that "Googlebot" really Google? Those are GROUP BY questions, and SQL answers them in one line each.

This walkthrough loads a standard nginx/Apache access log (combined format) into a database table with a ~30-line Python script, then runs five queries. I use SynapCores, the self-hosted database our team builds (full disclosure: this sub is run by the same people), but the SQL is plain and works almost anywhere.

What you need

  • A running SynapCores Community Edition (free; one-line installer or Docker at synapcores.com/download). Any SQL database works if you adapt the loader.
  • Python 3, standard library only.
  • An access token: log in once with POST /v1/auth/login and export it as SYNAPCORES_TOKEN.

No logs handy? The generator script in the first comment writes a realistic sample access.log (706 requests: normal visitors, a real crawler, a vulnerability scanner, a scraper, and a fake Googlebot).

Step 1: load the log

load_log.py parses each line with a regex and inserts rows 200 at a time:

import json, os, re, sys, urllib.request
URL, TOKEN = os.environ.get("SYNAPCORES_URL", "http://localhost:8080"), os.environ["SYNAPCORES_TOKEN"]
LINE = re.compile(r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) [^"]*" (\d{3}) (\d+|-) "[^"]*" "([^"]*)"')

def sql(statement):
    req = urllib.request.Request(URL + "/v1/query/execute",
                                 data=json.dumps({"sql": statement, "database": "main"}).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(req))["data"]

def quote(s):
    return "'" + s.replace("'", "''") + "'"

sql("""CREATE TABLE IF NOT EXISTS access_log (
         ip TEXT, ts TEXT, minute TEXT, method TEXT, path TEXT, status INTEGER, bytes INTEGER, user_agent TEXT)""")
rows = []
for raw in open(sys.argv[1]):
    m = LINE.match(raw)
    if not m:
        continue
    ip, ts, method, path, status, size, ua = m.groups()
    rows.append(f"({quote(ip)}, {quote(ts)}, {quote(ts[:17])}, {quote(method)}, {quote(path)}, "
                f"{status}, {0 if size == '-' else size}, {quote(ua)})")
for i in range(0, len(rows), 200):
    sql("INSERT INTO access_log (ip, ts, minute, method, path, status, bytes, user_agent) VALUES "
        + ", ".join(rows[i:i + 200]))
print(f"loaded {len(rows)} requests into access_log")

$ python3 load_log.py access.log
loaded 706 requests into access_log

(minute is the timestamp cut to the minute, 22/Oct/2026:09:41, so we can count bursts.)

Step 2: who sends the most requests?

SELECT ip, COUNT(*) AS requests FROM access_log
GROUP BY ip ORDER BY requests DESC LIMIT 5;

192.0.2.77      240
66.249.66.12     30
198.51.100.23    24
203.0.113.18     13
203.0.113.35     13

One IP is 34% of all traffic. Suspicious, but volume alone doesn't prove anything.

Step 3: who is hunting for secrets?

SELECT ip, COUNT(*) AS probes FROM access_log
WHERE status = 404 AND (path LIKE '%.env%' OR path LIKE '%.git%' OR path LIKE '%wp-login%'
      OR path LIKE '%phpmyadmin%' OR path LIKE '%.aws%' OR path LIKE '%config.json%')
GROUP BY ip ORDER BY probes DESC;

198.51.100.23   24
198.51.100.99   12

Nobody legitimate asks your server for /.aws/credentials. These two are scanners.

Step 4: who is bursting?

SELECT ip, minute, COUNT(*) AS hits FROM access_log
GROUP BY ip, minute HAVING COUNT(*) > 60 ORDER BY hits DESC;

192.0.2.77   22/Oct/2026:09:41   240

240 requests in one minute (4 per second) is a scraper, not a person.

Step 5: is that Googlebot real?

SELECT ip, COUNT(*) AS requests,
       SUM(CASE WHEN status = 404 THEN 1 ELSE 0 END) AS not_found
FROM access_log WHERE user_agent LIKE '%Googlebot%' GROUP BY ip;

198.51.100.99   12   12
66.249.66.12    30    0

Same user agent, two very different behaviors. The real crawler (66.249.x is in Google's published ranges) fetched real pages. The impostor only requested secret files. Anyone can type "Googlebot" into a User-Agent header, so verify against the published IP ranges (or a reverse DNS lookup) before you trust it.

Step 6: what's actually talking to you?

SELECT user_agent, COUNT(*) AS requests FROM access_log
GROUP BY user_agent ORDER BY requests DESC LIMIT 5;

python-requests/2.31.0 with 240 requests is your scraper again.

What to do with this

  • Feed the scanner IPs from step 3 to fail2ban or your firewall.
  • Rate-limit by IP when step 4 shows more than N hits per minute.
  • Keep the table and load new logs daily. Tomorrow you'll ask "is this IP new?" and that's one more query.

We did exactly this on our own servers last week and found a scanner farm using Cloudflare Worker IPs to dodge blocklists. Next post: run these checks automatically every hour and get alerted only when something new shows up.

What do you look for first when you open an access log?


r/devops7 • • Oct 20 '26

Your ML Model Called This Fraud Ring NORMAL

Thumbnail
youtube.com
1 Upvotes