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)

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?

1 Upvotes

1 comment sorted by

1

u/Alternative_Pin9598 13d ago

jobwatch.py (standard library only; set SC_URL and SC_TOKEN; create the job_runs table from Step 2 first):

"""jobwatch.py: nightly cron results -> SynapCores, then ask which job 'succeeded' in a way it never does.
usage: jobwatch.py ingest runs.txt | jobwatch.py check 2026-11-10
"""
import json, os, sys, urllib.request

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


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


def human(n):
    for unit in ["B", "KB", "MB", "GB"]:
        if n < 1000 or unit == "GB": return f"{n:.1f} {unit}"
        n /= 1000


def ingest(path):
    rows = [l.split() for l in open(path) if l.strip()]
    sql("INSERT INTO job_runs (day, job, exit_code, duration_s, bytes_out) VALUES " +
        ",".join(f"('{d}', '{j}', {e}, {s}, {b})" for d, j, e, s, b in rows))
    print(f"ingested {len(rows)} runs")


def check(night):
    # 1. the check most of us have: did anything exit non-zero?
    failed = sql(f"SELECT job, exit_code FROM job_runs WHERE day = '{night}' AND exit_code <> 0")
    print(f"exit_code <> 0 last night: {len(failed)} jobs")
    # 2. each job vs its own usual (all earlier nights), as two ratios: 1.0 = a normal night
    for job, dur, out in sql(f"SELECT job, AVG(duration_s), AVG(bytes_out) FROM job_runs WHERE day < '{night}' GROUP BY job"):
        sql(f"UPDATE job_runs SET dur_ratio = duration_s / {dur}, bytes_ratio = bytes_out / {out} WHERE job = '{job}'")
    # 3. SynapCores: train an anomaly model on all 30 nights, score last night inside the SELECT
    for q in ["DROP MODEL cron_model", "DROP EXPERIMENT cron_exp"]:
        try: sql(q)
        except Exception: pass
    sql(f"""CREATE EXPERIMENT cron_exp AS SELECT dur_ratio, bytes_ratio FROM job_runs WHERE day <= '{night}'
            WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'], max_trials = 5, random_seed = 42)""")
    sql("DEPLOY MODEL cron_model FROM EXPERIMENT cron_exp")
    for job, code, dur, out, dr, br, score in sql(f"""
        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 = '{night}' ORDER BY score DESC"""):
        flag = "ODD " if score > 0.8 else "ok  "
        print(f"{flag} {job:<14} exit {code}  {dur:>6.0f}s ({dr:4.2f}x usual)  {human(out):>9} ({br:5.2f}x usual)  anomaly {score:.2f}")


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

gen_runs.py (the seeded sample: python3 gen_runs.py > runs.txt && python3 jobwatch.py ingest runs.txt && python3 jobwatch.py check 2026-11-10):

# 30 nights of cron job results for 6 jobs (generated, seeded): "date job exit_code duration_s bytes_out" per line.
# Last night (2026-11-10) has two quiet failures: backup-db exits 0 after 4 s with almost no output,
# and logrotate exits 0 on time but ships ~40x its usual bytes.
import random, datetime
random.seed(7)
JOBS = {"backup-db": (2400, 18e9), "backup-files": (1500, 6e9), "logrotate": (40, 2e8),
        "cert-renew": (12, 4e4), "db-vacuum": (900, 1e6), "report-export": (300, 5e8)}
start = datetime.date(2026, 10, 12)
for d in range(30):
    day = start + datetime.timedelta(days=d)
    for job, (dur, out) in JOBS.items():
        dur_s = dur * random.uniform(0.85, 1.2)
        bytes_out = out * random.uniform(0.9, 1.15) * (1 + d * 0.003)
        if day == datetime.date(2026, 11, 10) and job == "backup-db":
            dur_s, bytes_out = 4, 1200
        if day == datetime.date(2026, 11, 10) and job == "logrotate":
            bytes_out = out * 41
        print(day.isoformat(), job, 0, round(dur_s), int(bytes_out))

Picking the cut-off: SQLv2 Lesson 3 shows how to choose a score threshold from data instead of guessing, which is the same question as "is 0.8 right for my jobs": https://www.reddit.com/r/SQLv2/comments/1xkb3mn/

New to ANOMALY_SCORE()? Recipe of the week #1 on r/synapcores walks through it from zero on a fraud example: https://www.reddit.com/r/synapcores/comments/1xlzo4t/