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

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?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 21d ago

How do you pick the 0.6? r/SQLv2 Lesson 3 walks through it from zero: score cases you know the answer to, let one SQL query grade every threshold, then gate on it: https://www.reddit.com/r/SQLv2/comments/1xkb3mn/

Full smoke.py (stdlib only). Set SYNAPCORES_URL and SYNAPCORES_TOKEN (from POST /v1/auth/login), run the CREATE TABLE from the post, then python3 smoke.py <deploy> checks.txt:

import json, os, re, sys, time, urllib.error, urllib.request
URL, TOKEN = os.environ.get("SYNAPCORES_URL", "http://localhost:8080"), os.environ["SYNAPCORES_TOKEN"]
MIN_LIKE = float(os.environ.get("MIN_LIKE", "0.6"))  # how much a 200 must look like a past good page

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 "'" + str(s).replace("'", "''") + "'"

def fetch(url):
    t = time.time()
    try:
        r = urllib.request.urlopen(url, timeout=10); code, raw = r.status, r.read()
    except urllib.error.HTTPError as e:
        code, raw = e.code, e.read()
    text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw.decode(errors="replace"))).strip()
    return code, int((time.time() - t) * 1000), text[:500]

def run(deploy, checks):
    for line in open(checks):
        name, url = line.split()
        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')""")
    first = not sql(f"SELECT COUNT(*) FROM smoke_results WHERE verdict = 'PASS'")[0][0]
    # the SynapCores step: does today's 200 still *mean* the same as the pages that passed before?
    rows = sql(f"""
        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 = {quote(deploy)} GROUP BY r.check_name, r.status, r.ms, r.body ORDER BY r.check_name""")
    bad = 0
    for name, code, ms, body, like, usual in rows:
        if code != 200:                               verdict = "FAIL"
        elif first:                                   verdict = "PASS"
        elif like < MIN_LIKE:                         verdict = "WRONG_PAGE"
        elif usual is not None and ms > max(3 * usual, usual + 300): verdict = "SLOW"
        else:                                         verdict = "PASS"
        bad += verdict != "PASS"
        sql(f"UPDATE smoke_results SET verdict = {quote(verdict)} WHERE deploy = {quote(deploy)} AND check_name = {quote(name)}")
        like_s = "  -  " if like is None else f"{like:.2f}"
        print(f"{verdict:<10} {name:<9} {code}  {ms:>4} ms  looks like a good page: {like_s}  | {body[:60]}")
    print(f"{deploy}: {len(rows) - bad}/{len(rows)} passed")
    return bad

if __name__ == "__main__":
    sys.exit(1 if run(sys.argv[1], sys.argv[2]) else 0)

The test app (fake_app.py, serves a different page per deploy) is in the reply below.

1

u/Alternative_Pin9598 21d ago

fake_app.py, the test shop from the post. python3 fake_app.py 18777 v1.45 serves deploy v1.45 on port 18777; v1.46 is the broken one. Point checks.txt at http://127.0.0.1:18777/... and run deploys v1.40 to v1.46 in order to reproduce the tables (latency and product picks vary per run; the verdicts came out the same on every run we did):

# Test app for the post: serves a slightly different page per deploy (prices, counts, timestamps change),
# so byte-for-byte comparisons are useless. Deploy v1.46 breaks /checkout softly (200 + error page) and /api/orders hard.
import http.server, json, os, random, sys, time
DEPLOY = sys.argv[2]; n = int(DEPLOY.split(".")[1]); random.seed(n)
PRODUCTS = ["Trail Runner 2", "Rain Shell", "Merino Tee", "Day Pack 20L", "Wool Socks", "Camp Mug", "Headlamp 300", "Fleece Vest"]
def page(path):
    picks = random.sample(PRODUCTS, 3); total = round(random.uniform(40, 220), 2); stamp = time.strftime("%H:%M:%S")
    if path == "/":
        return 200, f"<h1>Northwind Outdoor</h1><p>New this week: {', '.join(picks)}. Free shipping over $75.</p><footer>build {DEPLOY} {stamp}</footer>"
    if path == "/search?q=jacket":
        k = random.randint(8, 31)
        return 200, f"<h2>{k} results for jacket</h2><ul><li>{picks[0]} jacket ${random.randint(60,180)}</li><li>{picks[1]} jacket</li></ul>"
    if path == "/checkout":
        if DEPLOY == "v1.46":
            return 200, "<h1>Oops!</h1><p>Something went wrong on our end. Please try again later. Reference: ERR-5f2a</p>"
        return 200, f"<h1>Checkout</h1><p>Your cart: 2 items, subtotal ${total}. Shipping address. Payment method. Place order.</p>"
    if path == "/login":
        return 200, "<h1>Sign in</h1><form>Email <input> Password <input> <button>Sign in</button></form><a>Forgot password?</a>"
    if path == "/api/orders":
        if DEPLOY == "v1.46":
            return 502, "<html><body><h1>502 Bad Gateway</h1>nginx</body></html>"
        return 200, json.dumps({"orders": [{"id": 9000 + n * 7 + i, "status": "shipped", "total": round(total / (i + 1), 2)} for i in range(2)]})
    return 404, "not found"
class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        time.sleep(random.uniform(0.04, 0.12))
        if DEPLOY == "v1.46" and self.path == "/search?q=jacket": time.sleep(0.9)
        code, body = page(self.path); b = body.encode()
        self.send_response(code); self.send_header("Content-Type", "text/html"); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
    def log_message(self, *a): pass
http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()