#!/usr/bin/env python3 """Grade 4 fault-injection suite (needs FAULT_INJECTION=1 on the stand, see REPORT.md). Each scenario uploads a file whose display name selects an injected fault (app/faults.py) and checks the recovery through the public API plus DB/S3/broker state: A api_crash_after_commit crash between COMMIT(job+outbox) and publish -> another replica's relay publishes B worker_crash_after_put crash after S3 writes, before result COMMIT -> lease expiry -> same keys, one result C worker_crash_after_commit crash after COMMIT, before ack -> redelivery is a no-op D transient3 3 transient errors -> retries with growing jittered backoff -> ready E permanent permanent error -> failed at attempt 1, no retry, content/attach 409 F transient6 attempts exhausted -> failed/retry_exhausted -> registry -> explicit replay -> ready; replay of a ready job is refused G worker_hang hung worker (no heartbeats) -> other worker takes over, hung one is fenced H poison message invalid broker message -> DLQ, not retried forever I broker down RabbitMQ stopped: upload still 202 (job waits in outbox) -> broker back -> ready usage: python3 student-tests/test_failure_windows.py [A B C ...] """ import sys import time from stand import (Client, Failure, check, compose, get, jobs_cli, log, objects_of, queue_depth, run, sql, upload, unique_name, wait_http_ready, wait_status) def audit(att_id): return sql("SELECT action, actor, attempt, coalesce(detail->>'error_code',''), coalesce(detail->>'delay_seconds','')" " FROM job_audit WHERE attachment_id='%s' ORDER BY id" % att_id) def show_audit(att_id): for action, actor, attempt, code, delay in audit(att_id): log(" audit attempt=%s %-16s %-28s %s %s" % (attempt, action, actor[:28], code, ("delay=%ss" % delay) if delay else "")) def one_result(att_id): variants = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att_id)[0][0] succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att_id)[0][0] keys = objects_of(att_id) check(variants == "3", "exactly one set of 3 variant rows, got %s" % variants) check(succeeded == "1", "exactly one committed success, got %s" % succeeded) check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys), "original + 3 variants, staging cleaned: %s" % keys) def ready_and_single(c, actor, att_id, seconds=120): att, seen = wait_status(c, actor, att_id, ("ready", "failed"), seconds) check(att["status"] == "ready", "expected ready, got %s/%s" % (att["status"], att["error_code"])) log(" statuses:", " -> ".join(seen)) show_audit(att_id) one_result(att_id) return att def scenario_a(c, alice, bob, chat): name = unique_name("api_crash_after_commit") try: upload(c, alice, chat, filename=name, expected=[202, 500, 502, 503]) except Failure as exc: log(" client saw:", exc) wait_http_ready(c) rows = sql("SELECT id FROM attachments WHERE filename='%s'" % name) check(len(rows) == 1, "committed attachment must exist after API crash") att_id = rows[0][0] log(" committed attachment %s survived the API crash" % att_id) ready_and_single(c, bob, att_id) pub = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id" " WHERE j.attachment_id='%s' AND o.published_at IS NOT NULL" % att_id)[0][0] check(pub == "1", "outbox row published exactly once by the relay") def scenario_b(c, alice, bob, chat): att = upload(c, alice, chat, filename=unique_name("worker_crash_after_put")) ready_and_single(c, bob, att["id"]) actions = [r[0] for r in audit(att["id"])] check("retry_scheduled" in actions, "lease expiry must schedule a new attempt") def scenario_c(c, alice, bob, chat): att = upload(c, alice, chat, filename=unique_name("worker_crash_after_commit")) ready_and_single(c, bob, att["id"]) time.sleep(8) logs = compose("logs", "--since", "60s", "worker") check("decision=done" in logs, "redelivered message after crash must be a no-op") one_result(att["id"]) def scenario_d(c, alice, bob, chat): att = upload(c, alice, chat, filename=unique_name("transient3")) ready_and_single(c, bob, att["id"]) delays = [float(r[4]) for r in audit(att["id"]) if r[0] == "retry_scheduled"] check(len(delays) == 3, "three retries expected, got %s" % delays) bounds = [(1, 2), (2, 4), (4, 8)] check(all(lo <= d <= hi for d, (lo, hi) in zip(delays, bounds)), "equal-jitter backoff bounds %s" % delays) log(" backoff delays:", delays) def scenario_e(c, alice, bob, chat): att = upload(c, alice, chat, filename=unique_name("permanent")) failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 60) check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "permanent -> failed/invalid_image") check(failed["variants"] == [], "failed attachment has no variants") show_audit(att["id"]) check([r[0] for r in audit(att["id"])].count("claimed") == 1, "permanent errors are not retried") c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob) c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice, body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "k-" + att["id"]}) def scenario_f(c, alice, bob, chat): att = upload(c, alice, chat, filename=unique_name("transient6")) failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 120) check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "exhausted -> retry_exhausted") attempts = sql("SELECT attempt, max_attempts FROM attachment_jobs WHERE attachment_id='%s'" % att["id"])[0] check(attempts == ["5", "5"], "bounded: stopped at attempt 5 of 5, got %s" % attempts) rc, registry = jobs_cli("failed") check(any(r["attachment_id"] == att["id"] for r in registry), "failed job listed in operator registry") log(" failed registry contains the job; replay") rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite") check(rc == 0 and result["result"] == "queued", "replay must queue: %s" % result) ready_and_single(c, bob, att["id"], 120) rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite") check(rc == 3 and result["result"] == "refused", "replay of a ready job must be refused: %s" % result) log(" second replay refused:", result["reason"]) one_result(att["id"]) def scenario_g(c, alice, bob, chat): att = upload(c, alice, chat, filename=unique_name("worker_hang")) ready_and_single(c, bob, att["id"], 150) rows = audit(att["id"]) check(any(r[0] == "retry_scheduled" and r[3] == "lease_expired" for r in rows), "lease expiry detected") time.sleep(30) # the hung worker wakes up and must be fenced logs = compose("logs", "--since", "180s", "worker") check("lease_lost" in logs or "job_result_not_committed" in logs, "hung worker must be fenced by the lease") one_result(att["id"]) POISON = ("import asyncio, aio_pika\n" "from app import config, broker\n" "async def m():\n" " conn = await broker.connect(); ch = await conn.channel(publisher_confirms=True)\n" " ex = await broker.get_exchange(ch)\n" " await ex.publish(aio_pika.Message(b'{not json', delivery_mode=2), routing_key=broker.ROUTING_KEY)\n" " await conn.close()\n" "asyncio.run(m())\n") def scenario_h(c, alice, bob, chat): before = (queue_depth("attachments.dlq") or {}).get("messages", 0) compose("exec", "-T", "api-1", "python", "-c", POISON) deadline = time.monotonic() + 30 after = before while time.monotonic() < deadline and after <= before: time.sleep(1) after = (queue_depth("attachments.dlq") or {}).get("messages", 0) check(after == before + 1, "poison message must land in attachments.dlq (%s -> %s)" % (before, after)) log(" DLQ depth %s -> %s" % (before, after)) def scenario_i(c, alice, bob, chat): compose("stop", "-t", "10", "rabbitmq") try: att = upload(c, alice, chat, filename=unique_name()) check(att["status"] == "queued", "upload accepted while broker is down") c.message(alice, chat, "", attachments=[att["id"]]) time.sleep(3) pending = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id" " WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0] check(pending == "1", "job must wait in the outbox, got %s" % pending) check(get(c, bob, att["id"])["status"] == "queued", "still queued while broker is down") log(" broker down: upload 202, outbox holds 1 unpublished job") finally: compose("start", "rabbitmq") ready_and_single(c, bob, att["id"], 120) SCENARIOS = {"A": scenario_a, "B": scenario_b, "C": scenario_c, "D": scenario_d, "E": scenario_e, "F": scenario_f, "G": scenario_g, "H": scenario_h, "I": scenario_i} def main(): c = Client(timeout=30) alice, bob, eve, chat = c.bootstrap() picked = sys.argv[1:] or list(SCENARIOS) for key in picked: log("scenario %s: %s" % (key, SCENARIOS[key].__name__)) started = time.monotonic() SCENARIOS[key](c, alice, bob, chat) log("scenario %s PASS (%.1fs)" % (key, time.monotonic() - started)) print("PASS: failure windows %s" % " ".join(picked)) if __name__ == "__main__": run(main)