219 lines
11 KiB
Python
219 lines
11 KiB
Python
"""Explicit grade4 failure checks; changes only this local lab stand.
|
|
|
|
Run after public smoke; services are restored in finally blocks:
|
|
docker compose --profile tools run --rm tester python3 student-tests/lab5_recovery.py
|
|
|
|
Modes can be run separately: --mode persistence|outbox|objects|ack|replay|retry.
|
|
Faults are one-shot DB records; API tokens are never printed.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import time
|
|
from uuid import UUID
|
|
|
|
from PIL import Image
|
|
|
|
from lab5_helpers import Client, Failure, Stand, check, encoded, metadata, upload, wait_until
|
|
|
|
|
|
def wait_status(client, actor, attachment_id, target, timeout=180):
|
|
def poll():
|
|
value = metadata(client, actor, attachment_id)
|
|
if target != "failed":
|
|
check(value["status"] != "failed", "attachment unexpectedly failed")
|
|
return value if value["status"] == target else None
|
|
return wait_until(poll, f"attachment did not reach {target}", timeout=timeout, interval=0.6)
|
|
|
|
|
|
def assert_original(client, actor, att, content):
|
|
result = client.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=actor)
|
|
check(result["bytes"] == content, "accepted original bytes were lost")
|
|
check(hashlib.sha256(content).hexdigest() == att["sha256"], "original checksum changed")
|
|
|
|
|
|
def fault_hits(stand, point):
|
|
result = stand.sql(f"SELECT hits FROM fault_injections WHERE point='{point}';")
|
|
return int(result or 0)
|
|
|
|
|
|
def persistence(stand, client, alice, bob, chat, content):
|
|
stand.stop("worker")
|
|
try:
|
|
att = upload(client, alice, chat, content)
|
|
linked = client.message(alice, chat, "", attachments=[att["id"]])["json"]
|
|
check(linked["attachment_ids"] == [att["id"]], "queued attachment not linkable")
|
|
client.call("GET", f"/api/v1/attachments/{att['id']}/content", 409, actor=bob)
|
|
client.message(bob, chat, "Messages work while worker is stopped")
|
|
# Ensure there really is a durable broker message before its restart.
|
|
aid = str(UUID(att["id"]))
|
|
wait_until(lambda: stand.sql(
|
|
f"SELECT count(*) FROM outbox WHERE attachment_id='{aid}' AND published_at IS NOT NULL;"
|
|
) != "0", "outbox did not publish before broker restart", timeout=30)
|
|
before = {service: {cid: stand.docker("inspect", "-f", "{{.State.StartedAt}}", cid)
|
|
for cid in stand.ids(service)} for service in ("api", "broker")}
|
|
stand.restart("api", "broker")
|
|
stand.wait_ready()
|
|
for service, containers in before.items():
|
|
for cid, started in containers.items():
|
|
check(stand.docker("inspect", "-f", "{{.State.StartedAt}}", cid) != started,
|
|
f"{service} did not actually restart")
|
|
check(metadata(client, bob, att["id"])["status"] == "queued", "worker ran while stopped")
|
|
stand.start("worker")
|
|
ready = wait_status(client, bob, att["id"], "ready")
|
|
assert_original(client, bob, ready, content)
|
|
print(f"PASS persistence: attachment={att['id']} same session/ID after API+broker restart; "
|
|
"volumes preserved; queued content409; messages201; ready", flush=True)
|
|
finally:
|
|
stand.start("worker", "broker", "api")
|
|
|
|
|
|
def injected(stand, client, alice, bob, chat, content, point):
|
|
service = "publisher" if point == "crash_after_commit_before_publish" else "worker"
|
|
stand.stop(service)
|
|
try:
|
|
before = fault_hits(stand, point)
|
|
stand.operator("fault", point)
|
|
att = upload(client, alice, chat, content)
|
|
aid = str(UUID(att["id"]))
|
|
if service == "publisher":
|
|
check(stand.sql(f"SELECT count(*) FROM outbox WHERE attachment_id='{aid}' "
|
|
"AND published_at IS NULL;") != "0", "no durable unpublished outbox")
|
|
check(metadata(client, bob, aid)["status"] == "queued", "outbox gap not established")
|
|
stand.start(service)
|
|
wait_until(lambda: fault_hits(stand, point) > before,
|
|
f"fault {point} was not reached", timeout=60)
|
|
if point == "crash_after_objects_before_commit":
|
|
row = stand.row(aid)
|
|
check(row["status"] == "processing", "objects crash did not leave processing")
|
|
check(stand.objects_exist([row["object_key"]]) == [True],
|
|
"no durable original exists at the injected crash boundary")
|
|
check(row["lease_until"] is not None, "processing has no lease")
|
|
# Restart policy normally does this; explicit start also works without one.
|
|
stand.start(service)
|
|
started = time.monotonic()
|
|
ready = wait_status(client, bob, aid, "ready", timeout=200)
|
|
assert_original(client, bob, ready, content)
|
|
check(len(ready["variants"]) == 3, "recovery duplicated/lost variants")
|
|
row = stand.row(aid)
|
|
if point == "crash_after_objects_before_commit":
|
|
check(row["attempts_run"] >= 2, "expired processing was not retried")
|
|
print(f"PASS {point}: attachment={aid} hits={fault_hits(stand, point)-before} "
|
|
f"recovered_seconds={time.monotonic()-started:.1f}; same original; three variants", flush=True)
|
|
# No staging removal is allowed before ready, but it must eventually be cleaned.
|
|
wait_until(lambda: stand.row(aid)["staging_deleted"],
|
|
"ready staging was not cleaned", timeout=90)
|
|
check(stand.objects_exist([row["staging_key"]]) == [False], "ready staging object remains")
|
|
finally:
|
|
stand.sql(f"UPDATE fault_injections SET remaining=0 WHERE point='{point}';")
|
|
stand.start(service)
|
|
|
|
|
|
def replay(stand, client, alice, bob, chat, content):
|
|
stand.stop("worker")
|
|
try:
|
|
att = upload(client, alice, chat, content)
|
|
aid = att["id"]
|
|
row = stand.row(aid)
|
|
original_job = row["job_id"]
|
|
# Damage only this test's staged object. The checksum mismatch is permanent.
|
|
stand.replace_object(row["staging_key"], b"deliberately damaged staged source")
|
|
stand.start("worker")
|
|
failed = wait_status(client, bob, aid, "failed", timeout=120)
|
|
check(failed["error_code"] is not None, "failed has no safe error code")
|
|
check(stand.row(aid)["attempts_run"] == 1, "permanent error was repeatedly retried")
|
|
client.call("GET", f"/api/v1/attachments/{aid}/content", 409, actor=bob)
|
|
import uuid
|
|
client.call("POST", f"/api/v1/chats/{chat['id']}/messages", 409,
|
|
actor=alice, body={"text": "", "attachment_ids": [aid]},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex})
|
|
registry = stand.operator("failed")
|
|
check(aid in registry, "failed attachment not visible to operator")
|
|
stand.replace_object(row["staging_key"], content)
|
|
stand.operator("replay", aid, "--reason", "test source restored after simulated corruption")
|
|
ready = wait_status(client, bob, aid, "ready")
|
|
check(stand.row(aid)["job_id"] == original_job, "replay changed logical job ID")
|
|
assert_original(client, bob, ready, content)
|
|
check(stand.sql(f"SELECT count(*) FROM job_events WHERE attachment_id='{aid}' AND event='operator_replay';") != "0",
|
|
"explicit replay was not audited")
|
|
check(stand.sql(f"SELECT attempt FROM job_events WHERE attachment_id='{aid}' "
|
|
"AND event='operator_replay' ORDER BY id DESC LIMIT 1;") ==
|
|
str(stand.row(aid)["attempt"]), "replay audit refers to the previous attempt")
|
|
snapshot = metadata(client, bob, aid)
|
|
stand.operator("redeliver", aid)
|
|
wait_until(lambda: stand.sql(f"SELECT count(*) FROM outbox WHERE attachment_id='{aid}' "
|
|
"AND published_at IS NULL;") == "0",
|
|
"ready duplicate was not published", timeout=30)
|
|
time.sleep(2)
|
|
check(metadata(client, bob, aid) == snapshot, "ready redelivery modified completed result")
|
|
check(len(snapshot["variants"]) == 3, "ready redelivery duplicated variants")
|
|
print(f"PASS failed/replay: attachment={aid}; permanent error fails once; failed registry; "
|
|
"content/link409; audited replay preserves job_id; ready duplicate no-op", flush=True)
|
|
finally:
|
|
stand.start("worker")
|
|
|
|
|
|
def retry(stand, client, alice, bob, chat, content):
|
|
"""Temporary S3 failure must persist retries and eventually exhaust the budget."""
|
|
stand.stop("worker")
|
|
try:
|
|
att = upload(client, alice, chat, content)
|
|
aid = att["id"]
|
|
stand.stop("s3")
|
|
stand.start("worker")
|
|
failed = wait_status(client, bob, aid, "failed", timeout=240)
|
|
check(failed["error_code"] == "retry_exhausted", "transient errors did not exhaust retry budget")
|
|
row = stand.row(aid)
|
|
check(row["attempts_run"] > 1, "temporary outage was not retried")
|
|
attempts = stand.sql(f"SELECT count(DISTINCT attempt) FROM outbox WHERE attachment_id='{aid}';")
|
|
check(int(attempts) == row["attempts_run"], "retry attempt was not saved in outbox")
|
|
stand.start("s3")
|
|
# Wait storage health separately; Stand.ready covers API/broker/db.
|
|
wait_until(lambda: stand.docker("inspect", "-f", "{{.State.Health.Status}}",
|
|
stand.one("s3")) == "healthy", "S3 did not recover", timeout=90)
|
|
stand.operator("replay", aid, "--reason", "S3 recovered after bounded retry exhaustion")
|
|
ready = wait_status(client, bob, aid, "ready")
|
|
assert_original(client, bob, ready, content)
|
|
print(f"PASS transient S3 outage: attachment={aid}; attempts={row['attempts_run']}; "
|
|
"durable retries, retry_exhausted, explicit replay after recovery", flush=True)
|
|
finally:
|
|
stand.start("s3", "worker")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default=None)
|
|
parser.add_argument("--mode", default="all", choices=("all", "persistence", "outbox", "objects",
|
|
"ack", "replay", "retry"))
|
|
args = parser.parse_args()
|
|
stand = Stand()
|
|
stand.wait_ready()
|
|
client = Client(args.base_url, timeout=40)
|
|
alice, bob, _eve, chat = client.bootstrap()
|
|
content = encoded(Image.new("RGB", (320, 200), (40, 100, 190)))
|
|
scenarios = (
|
|
("persistence", lambda: persistence(stand, client, alice, bob, chat, content)),
|
|
("outbox", lambda: injected(stand, client, alice, bob, chat, content,
|
|
"crash_after_commit_before_publish")),
|
|
("objects", lambda: injected(stand, client, alice, bob, chat, content,
|
|
"crash_after_objects_before_commit")),
|
|
("ack", lambda: injected(stand, client, alice, bob, chat, content,
|
|
"crash_after_commit_before_ack")),
|
|
("replay", lambda: replay(stand, client, alice, bob, chat, content)),
|
|
("retry", lambda: retry(stand, client, alice, bob, chat, content)),
|
|
)
|
|
for name, action in scenarios:
|
|
if args.mode in ("all", name):
|
|
action()
|
|
print(f"PASS: lab5 grade4 recovery checks ({args.mode})", flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (Failure, ValueError, OSError) as exc:
|
|
print("FAIL:", str(exc), flush=True)
|
|
raise SystemExit(1)
|