forked from mtusi2026/mtusi2026lab6
387 lines
20 KiB
Python
387 lines
20 KiB
Python
"""Lab 5 grade 3+4: HTTP outputs and deterministic operator-injected faults."""
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import os
|
|
import struct
|
|
import tempfile
|
|
import time
|
|
import uuid
|
|
import zlib
|
|
|
|
from checks import ROOT, Failure, Pending, check, post, key, assert_history, wait
|
|
from image_probe import jpeg_size
|
|
|
|
STAGING = ("queued", "processing")
|
|
VARIANTS = {
|
|
"thumbnail": ("image/jpeg", 256, 160),
|
|
"crop": ("image/jpeg", 128, 128),
|
|
"optimized": ("image/webp", 320, 200),
|
|
}
|
|
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
|
|
|
|
|
def attachment_path(att):
|
|
return f"/api/v1/attachments/{att['id']}"
|
|
|
|
|
|
def metadata(c, actor, att):
|
|
return c.call("GET", attachment_path(att), actor=actor, schema="Attachment")["json"]
|
|
|
|
|
|
def until_status(c, actor, att, desired, timeout):
|
|
started = time.monotonic()
|
|
while time.monotonic()-started < timeout:
|
|
current = metadata(c, actor, att)
|
|
state = current["status"]
|
|
if state == desired:
|
|
check(time.monotonic()-started <= timeout, f"{desired} observed after deadline")
|
|
c.evidence.event("attachment_state", attachment=att["id"], status=state,
|
|
seconds=time.monotonic()-started)
|
|
return current
|
|
check(state in STAGING, f"wanted {desired}, reached terminal state {state}")
|
|
time.sleep(0.25)
|
|
raise Failure(f"attachment never reached {desired} within {timeout} seconds")
|
|
|
|
|
|
def png_chunk(kind, data):
|
|
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
|
|
|
|
|
|
def oversized_pixels():
|
|
# 40,010,000 pixels, but a small valid PNG; never allocate the decoded image.
|
|
width, height = 10000, 4001
|
|
enc = zlib.compressobj()
|
|
row = bytes(width+1)
|
|
compressed = b"".join(enc.compress(row) for _ in range(height)) + enc.flush()
|
|
return (SAMPLE[:8] + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0))
|
|
+ png_chunk(b"IDAT", compressed) + png_chunk(b"IEND", b""))
|
|
|
|
|
|
def upload_rejects(c):
|
|
alice, _, _, chat = c.bootstrap()
|
|
path = f"/api/v1/chats/{chat['id']}/attachments?filename=limits.png"
|
|
n = 10 * 1024 * 1024
|
|
padded = SAMPLE[:-12] + png_chunk(b"npAD", bytes(n + 1 - len(SAMPLE) - 12)) + SAMPLE[-12:]
|
|
check(len(padded) == n + 1, "invalid bytes-boundary fixture")
|
|
for data, status, code in (
|
|
(padded, 413, "payload_too_large"),
|
|
(oversized_pixels(), 413, "payload_too_large"),
|
|
(b"not a PNG", 415, "unsupported_media_type"),
|
|
(SAMPLE[:30], 415, "unsupported_media_type"),
|
|
):
|
|
r = c.call("POST", path, status, actor=alice, raw=data, headers={"Content-Type": "image/png"})
|
|
check(r["json"]["error"]["code"] == code, f"upload must return {code}")
|
|
|
|
|
|
def decoded_webp_size(data):
|
|
# Read actual bitstream dimensions. Check the complete RIFF framing, not
|
|
# metadata or filename alone; full pixel decode can also run via ImageMagick.
|
|
check(len(data) >= 20 and data[:4] == b"RIFF" and data[8:12] == b"WEBP"
|
|
and int.from_bytes(data[4:8], "little") + 8 == len(data), "invalid WebP RIFF")
|
|
i, canvas, image = 12, None, None
|
|
while i < len(data):
|
|
check(i + 8 <= len(data), "truncated WebP chunk")
|
|
size = int.from_bytes(data[i+4:i+8], "little")
|
|
name, start = data[i:i+4], i+8
|
|
i = start+size+(size % 2)
|
|
check(i <= len(data), "truncated WebP chunk body")
|
|
if name == b"VP8X":
|
|
check(size == 10, "invalid WebP canvas")
|
|
canvas = tuple(1 + int.from_bytes(data[start+x:start+x+3], "little") for x in (4, 7))
|
|
elif name == b"VP8 ":
|
|
check(size >= 10 and data[start+3:start+6] == b"\x9d\x01\x2a", "invalid VP8 bitstream")
|
|
image = tuple(int.from_bytes(data[start+x:start+x+2], "little") & 0x3fff for x in (6, 8))
|
|
elif name == b"VP8L":
|
|
check(size >= 5 and data[start] == 0x2f, "invalid VP8L bitstream")
|
|
bits = int.from_bytes(data[start+1:start+5], "little")
|
|
image = (1+(bits & 0x3fff), 1+((bits >> 14) & 0x3fff))
|
|
check(image and (canvas is None or canvas == image), "WebP missing image or inconsistent canvas")
|
|
return image
|
|
|
|
|
|
def verify_ready(c, reader, queued, ready, *, decoder=None):
|
|
stable = ("id", "chat_id", "owner_id", "filename", "content_type", "sha256", "size_bytes", "created_at")
|
|
check(all(ready[k] == queued[k] for k in stable), "original metadata changed from queued to ready")
|
|
check(ready["status"] == "ready" and ready["error_code"] is None, "invalid ready state")
|
|
entries = {v["name"]: v for v in ready["variants"]}
|
|
check(len(ready["variants"]) == len(entries) and set(entries) >= set(VARIANTS),
|
|
"ready requires exactly one thumbnail, crop and optimized variant each")
|
|
path = attachment_path(ready) + "/content"
|
|
original = c.call("GET", path, actor=reader)
|
|
check(original["bytes"] == SAMPLE and original["headers"].get_content_type() == "image/png",
|
|
"published original changed")
|
|
for name, (mime, w, h) in VARIANTS.items():
|
|
v = entries[name]
|
|
r = c.call("GET", f"{path}?variant={name}", actor=reader)
|
|
data = r["bytes"]
|
|
check((v["content_type"], v["width"], v["height"]) == (mime, w, h), f"{name}: metadata differs")
|
|
check(r["headers"].get_content_type() == mime and len(data) == v["size_bytes"]
|
|
and hashlib.sha256(data).hexdigest() == v["sha256"], f"{name}: MIME/size/hash mismatch")
|
|
size = jpeg_size(data) if mime == "image/jpeg" else decoded_webp_size(data)
|
|
check(size == (w, h), f"{name}: wrong dimensions in image bytes")
|
|
if decoder:
|
|
decoder(data, mime, w, h)
|
|
c.evidence.event("variant", name=name, width=w, height=h, bytes=len(data), sha256=v["sha256"])
|
|
return ready
|
|
|
|
|
|
def variants(c, timeout, decoder):
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
que, _ = c.attachment(alice, chat)
|
|
check(que["variants"] == [] and que["error_code"] is None, "queued upload disclosed a result or error")
|
|
ready = until_status(c, bob, que, "ready", timeout)
|
|
verify_ready(c, bob, que, ready, decoder=decoder)
|
|
c.call("GET", attachment_path(que), 404, actor=eve)
|
|
c.call("GET", attachment_path(que) + "/content?variant=crop", 404, actor=eve)
|
|
|
|
|
|
class Pipeline:
|
|
def __init__(self, stand, decoder):
|
|
self.stand, self.c, self.a = stand, stand.c, stand.a
|
|
self.decoder = decoder
|
|
|
|
def action(self, command, *args):
|
|
if not self.a.pipeline_hook:
|
|
raise Pending("awaiting worker, broker, relay and app-specific fault adapter")
|
|
path = Path(self.a.pipeline_hook).resolve()
|
|
check(path.is_file() and os.access(path, os.X_OK), "pipeline hook is not executable")
|
|
env = dict(os.environ, BASE_URL=self.c.base)
|
|
if self.a.project:
|
|
env["COMPOSE_PROJECT_NAME"] = self.a.project
|
|
result = self.stand.command("pipeline " + command + (" " + args[0] if command in
|
|
("arm", "await", "clear", "crash") else ""),
|
|
[str(path), command, *args], env=env, timeout=self.a.pipeline_timeout,
|
|
allow_failure=True)
|
|
if result.returncode == 78:
|
|
raise Pending(f"pipeline adapter prerequisite unavailable for {command}")
|
|
if result.returncode and path == Path(__file__).with_name("pipeline_action.py"):
|
|
# The bundled adapter emits bounded, whitelisted action labels.
|
|
self.c.evidence.event("adapter_diagnostic", action=command, note=result.stderr.decode()[:300].strip())
|
|
check(result.returncode == 0, f"pipeline adapter rejected {command} (exit {result.returncode})")
|
|
if command in ("inspect", "await", "crash", "broker-restart", "restart-apis",
|
|
"replay", "invalid-job", "worker-limits", "drain"):
|
|
data = json.loads(result.stdout)
|
|
check(isinstance(data, dict), "pipeline hook did not return an object")
|
|
if command in ("broker-restart", "restart-apis", "invalid-job", "replay", "worker-limits", "drain"):
|
|
self.c.evidence.event(command, evidence=data)
|
|
return data
|
|
return None
|
|
|
|
def snapshot(self, att):
|
|
o = self.action("inspect", att["id"])
|
|
fields = ("job_id", "jobs", "outbox", "staging_exists", "variant_objects", "failed_registered",
|
|
"attempts", "max_attempts", "lease_seconds", "prefetch", "concurrency",
|
|
"job_timeout_seconds", "worker_memory_bytes", "retry_base_seconds",
|
|
"published", "generation", "result_count", "original_exists", "audit_replays", "envelope_valid",
|
|
"scheduled_delays_ms")
|
|
check(set(fields) <= o.keys(), "incomplete durable pipeline observation")
|
|
check(isinstance(o["job_id"], str), "observation has no job ID")
|
|
uuid.UUID(o["job_id"])
|
|
attempts = [{k: row[k] for k in ("attempt", "kind", "delay_seconds", "error_code")} for row in o["attempts"]
|
|
if isinstance(row, dict) and {"attempt", "kind", "delay_seconds", "error_code"} <= row.keys()]
|
|
check(len(attempts) == len(o["attempts"]), "malformed attempt history")
|
|
rows = {k: o[k] for k in fields}
|
|
rows["attempts"] = attempts
|
|
self.c.evidence.event("pipeline_state", attachment=att["id"], **rows)
|
|
check(o["jobs"] == 1 and o["outbox"] >= 1 and o["envelope_valid"] is True,
|
|
"lost, duplicated or invalid durable processing intent")
|
|
check(all(isinstance(o[k], (int, float)) and o[k] > 0 for k in
|
|
("max_attempts", "lease_seconds", "prefetch", "concurrency",
|
|
"job_timeout_seconds", "worker_memory_bytes", "retry_base_seconds")),
|
|
"unbounded worker/process configuration")
|
|
check(o["job_timeout_seconds"] < o["lease_seconds"] and o["prefetch"] >= o["concurrency"],
|
|
"worker lease/prefetch do not cover work admitted by worker")
|
|
return o
|
|
|
|
def accepted(self, uploader, reader, chat):
|
|
att, _ = self.c.attachment(uploader, chat)
|
|
check(metadata(self.c, reader, att)["status"] in STAGING, "processed while worker must be held")
|
|
fail = self.c.call("GET", attachment_path(att) + "/content", 409, actor=reader)
|
|
check(fail["json"]["error"]["code"] == "conflict", "non-ready content must be a conflict")
|
|
before = self.snapshot(att)
|
|
check(before["staging_exists"] is True, "202 returned without durable staging")
|
|
return att, before
|
|
|
|
def finished(self, reader, att, previous):
|
|
ready = until_status(self.c, reader, att, "ready", self.a.pipeline_timeout)
|
|
verify_ready(self.c, reader, att, ready, decoder=self.decoder)
|
|
|
|
def cleaned():
|
|
row = self.snapshot(att)
|
|
check(row["job_id"] == previous["job_id"], "job identity changed during recovery")
|
|
if row["staging_exists"] or row["result_count"] != len(VARIANTS) + 1:
|
|
return None
|
|
check(row["original_exists"] is True and sorted(row["variant_objects"]) == sorted(VARIANTS),
|
|
"S3 must contain the original and one published object per required variant")
|
|
return row
|
|
|
|
current = wait(cleaned, self.a.pipeline_timeout, "staging or orphan results were not cleaned")
|
|
return ready, current
|
|
|
|
def durable(self):
|
|
self.action("reset")
|
|
alice, bob, _, chat = self.c.bootstrap()
|
|
try:
|
|
self.action("worker-stop")
|
|
att, previous = self.accepted(alice, bob, chat)
|
|
msg = post(self.c, alice, chat, key(), "", body={"text": "", "attachment_ids": [att["id"]]})["json"]
|
|
wait(lambda: self.snapshot(att)["published"] > 0, 30, "original job was not published")
|
|
self.action("restart-apis")
|
|
self.action("broker-restart")
|
|
wait(lambda: self.c.call("GET", "/health/ready", schema="Health"), 60, "API not ready after restart")
|
|
check(metadata(self.c, bob, att)["status"] == "queued", "job did not stay queued without worker")
|
|
assert_history(self.c, bob, chat, [msg])
|
|
self.action("worker-start")
|
|
ready, prior = self.finished(bob, att, previous)
|
|
self.action("relay-start")
|
|
self.action("redeliver", att["id"])
|
|
after, row = self.finished(bob, att, previous)
|
|
check(after == ready and row["attempts"] == prior["attempts"],
|
|
"duplicate broker event changed published effect or executed again")
|
|
finally:
|
|
self.action("reset")
|
|
|
|
def crash(self, point):
|
|
self.action("reset")
|
|
alice, bob, _, chat = self.c.bootstrap()
|
|
try:
|
|
if point == "publish-before-mark":
|
|
self.action("worker-stop")
|
|
self.action("arm", point)
|
|
att, _ = self.c.attachment(alice, chat)
|
|
mark = self.action("crash", point, att["id"])
|
|
check(mark.get("point") == point and mark.get("attachment_id") == att["id"]
|
|
and mark.get("signal") == "SIGKILL", "fault did not identify and kill the expected process")
|
|
self.c.evidence.event("fault_reached", evidence=mark)
|
|
if point == "publish-before-mark":
|
|
self.action("worker-start")
|
|
_, current = self.finished(bob, att, mark)
|
|
self.action("drain")
|
|
if point == "object-before-ack":
|
|
check([row["kind"] for row in current["attempts"]] == ["lease_expired", "success"]
|
|
and current["generation"] > mark["generation"], "lost processing lease was not recovered")
|
|
if point == "ready-before-ack":
|
|
check(current["generation"] == mark["generation"] and current["attempts"] == mark["attempts"],
|
|
"redelivery started a new attempt after durable completion")
|
|
finally:
|
|
self.action("reset")
|
|
|
|
def bounded_processing(self):
|
|
self.action("reset")
|
|
alice, bob, _, chat = self.c.bootstrap()
|
|
settings = wait(lambda: settings_with_consumer(self), 20, "no active worker consumer observed")
|
|
limits = settings["image_limits"]
|
|
check(all(value and value not in ("0", "unlimited", "0 seconds") for value in limits.values())
|
|
and settings["worker_memory_bytes"] > 0, "worker or ImageMagick has unbounded resources")
|
|
consumers = settings["consumers"]
|
|
check(len(consumers) == settings["concurrency"] and all(
|
|
row["active"] and row["ack_required"] and row["prefetch"] == settings["prefetch"] > 0
|
|
for row in consumers), "broker consumer count, ack or prefetch differs from worker configuration")
|
|
try:
|
|
self.action("arm", "object-before-ack")
|
|
att, _ = self.c.attachment(alice, chat)
|
|
marker = self.action("await", "object-before-ack", att["id"])
|
|
# Leave the worker paused. Its own work deadline must end the
|
|
# attempt, record a temporary failure and permit automatic retry.
|
|
_, recovered = self.finished(bob, att, {"job_id": marker["job_id"]})
|
|
observed = [(x["kind"], x["error_code"]) for x in recovered["attempts"]]
|
|
check(observed == [("temporary", "processing_timeout"), ("success", None)],
|
|
"worker did not time out and finish the same job on retry")
|
|
finally:
|
|
self.action("reset")
|
|
|
|
def malformed_job(self):
|
|
self.action("reset")
|
|
alice, bob, _, chat = self.c.bootstrap()
|
|
try:
|
|
att, _ = self.c.attachment(alice, chat)
|
|
ready = until_status(self.c, bob, att, "ready", self.a.pipeline_timeout)
|
|
original, prior = self.finished(bob, att, self.snapshot(att))
|
|
self.action("invalid-job", att["id"])
|
|
later, after = self.finished(bob, att, prior)
|
|
check(ready == original == later and prior["attempts"] == after["attempts"],
|
|
"invalid broker message changed a ready result or created a new delivery effect")
|
|
finally:
|
|
self.action("reset")
|
|
|
|
def retry_replay(self):
|
|
self.action("reset")
|
|
alice, bob, _, chat = self.c.bootstrap()
|
|
schedules = []
|
|
try:
|
|
for point in ("retry-transient", "retry-transient", "fail-permanent"):
|
|
self.action("arm", point)
|
|
att, _ = self.c.attachment(alice, chat)
|
|
linked_key = key()
|
|
linked_body = {"text": "", "attachment_ids": [att["id"]]}
|
|
linked = None
|
|
if point == "fail-permanent":
|
|
linked = post(self.c, alice, chat, linked_key, "", body=linked_body)["json"]
|
|
self.action("activate", point, att["id"])
|
|
failed = until_status(self.c, bob, att, "failed", self.a.pipeline_timeout)
|
|
code = "invalid_image" if point == "fail-permanent" else "retry_exhausted"
|
|
check(failed["error_code"] == code and not failed["variants"], "wrong terminal error code/metadata")
|
|
row = self.snapshot(att)
|
|
self.action("failed", att["id"])
|
|
check(row["failed_registered"] and row["staging_exists"], "failed job not registered or replay input lost")
|
|
unavailable = self.c.call("GET", attachment_path(att) + "/content", 409, actor=bob)
|
|
check(unavailable["json"]["error"]["code"] == "conflict", "failed attachment content is not a conflict")
|
|
post(self.c, alice, chat, key(), "", body=linked_body, status=409, code="conflict")
|
|
if linked:
|
|
check(post(self.c, alice, chat, linked_key, "", body=linked_body)["json"] == linked,
|
|
"prior accepted Message must remain replayable after its attachment fails")
|
|
assert_history(self.c, bob, chat, [linked])
|
|
attempts = row["attempts"]
|
|
if point == "fail-permanent":
|
|
check(len(attempts) == 1 and attempts[0]["kind"] == "permanent"
|
|
and attempts[0]["delay_seconds"] is None, "permanent fault was retried")
|
|
else:
|
|
check(len(attempts) == row["max_attempts"] and len(attempts) >= 2
|
|
and all(x["kind"] == "temporary" for x in attempts),
|
|
"transient failure did not stop at configured attempt bound")
|
|
delays = row["scheduled_delays_ms"]
|
|
check(len(delays) == len(attempts)-1, "retry offsets were not recorded for each retry")
|
|
for i, (ms, attempt) in enumerate(zip(delays, attempts[:-1])):
|
|
upper = min(30, row["retry_base_seconds"] * (2 ** min(i, 4)))
|
|
observed = attempt["delay_seconds"]
|
|
check(1000 <= ms <= 1000 * upper and isinstance(observed, (int, float))
|
|
and 0 < observed <= upper, "retry outside documented backoff and jitter bounds")
|
|
schedules.append(delays)
|
|
self.action("clear", point, att["id"])
|
|
self.action("replay", att["id"])
|
|
# A checksum fault changed metadata only within this test; replay
|
|
# must serve the original fixture's data and checksum.
|
|
ready, current = self.finished(bob, att, row)
|
|
check(current["audit_replays"] == row["audit_replays"] + 1,
|
|
"operator replay did not leave exactly one audit record")
|
|
self.action("replay", att["id"])
|
|
snapshot = self.snapshot(att)
|
|
check(metadata(self.c, bob, att) == ready and snapshot["attempts"] == current["attempts"]
|
|
and snapshot["outbox"] == current["outbox"], "replay of ready job was not a no-op")
|
|
check(len(schedules) == 2 and schedules[0] != schedules[1], "identical retry schedules: jitter not observed")
|
|
finally:
|
|
self.action("reset")
|
|
|
|
|
|
def settings_with_consumer(pipeline):
|
|
settings = pipeline.action("worker-limits")
|
|
return settings if settings["consumers"] else None
|
|
|
|
|
|
def make_decoder(stand, executable):
|
|
if not executable:
|
|
return None
|
|
|
|
def decode(data, mime, w, h):
|
|
# Bytes are synthetic and the command sees only a temporary file.
|
|
suffix = ".jpg" if mime == "image/jpeg" else ".webp"
|
|
with tempfile.NamedTemporaryFile(suffix=suffix) as file:
|
|
file.write(data)
|
|
file.flush()
|
|
result = stand.command("decode downloaded " + mime, [
|
|
executable, "identify", "+ping", "-regard-warnings", "-format", "%wx%h", file.name,
|
|
], timeout=10)
|
|
check(result.stdout.decode().strip() == f"{w}x{h}", "full image decode has wrong dimensions")
|
|
return decode
|