Перенести реализацию лабораторной 5 в лабораторную 6

This commit is contained in:
2026-11-21 11:35:52 +03:00
parent 470d9d6f1e
commit 36d84eaf44
53 changed files with 6420 additions and 29 deletions
+7
View File
@@ -0,0 +1,7 @@
# Окружение для запуска проверок: Python 3.12 (stdlib-тесты), make, docker CLI (action-скрипты).
FROM docker:28.5.1-cli AS docker-cli
FROM python:3.12.11-alpine3.22
RUN apk add --no-cache make
RUN pip install --no-cache-dir Pillow==11.0.0
COPY --from=docker-cli /usr/local/bin/docker /usr/local/bin/docker
WORKDIR /work
+129
View File
@@ -0,0 +1,129 @@
"""Offline regressions for malformed uploads; run with the app's Pillow installed.
python student-tests/image_validation_unit.py
No HTTP, Docker, credentials or test data in the application are required.
"""
from __future__ import annotations
import io
from pathlib import Path
import struct
import sys
import unittest
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from PIL import Image
from app.images import InvalidImage, PNG_SIGNATURE, TooManyPixels, validate_image
def chunk(kind: bytes, data: bytes) -> bytes:
return (struct.pack(">I", len(data)) + kind + data +
struct.pack(">I", zlib.crc32(kind + data)))
def ihdr(width=1, height=1, depth=8, color=2, interlace=0) -> bytes:
return chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace))
def png(raw=b"\x00\xff\x00\x00", *, header=None, before=b"", after=b"") -> bytes:
return (PNG_SIGNATURE + (header or ihdr()) + before + chunk(b"IDAT", zlib.compress(raw)) +
after + chunk(b"IEND", b""))
class ImageValidationTests(unittest.TestCase):
def validate(self, data: bytes, mime="image/png"):
return validate_image(io.BytesIO(data), mime, 40_000_000)
def assert_invalid(self, data: bytes, mime="image/png"):
with self.assertRaises(InvalidImage):
self.validate(data, mime)
def test_valid_png_and_trailing_padding(self):
image = self.validate(png() + b"\x00" * 100)
self.assertEqual((image.width, image.height), (1, 1))
def test_filter_values_and_row_boundaries(self):
for filter_byte in range(5):
self.validate(png(bytes([filter_byte, 0, 0, 0])))
self.assert_invalid(png(b"\x05\x00\x00\x00"))
# Second filter is after a row larger than the inflater's 64 KiB
# output piece. It must be checked despite that boundary.
self.assert_invalid(png(b"\x00" + bytes(90000) + b"\xff" + bytes(90000),
header=ihdr(30000, 2)))
def test_critical_headers_and_chunk_order(self):
# Wrong IHDR length is rejected before any payload read/allocation.
self.assert_invalid(PNG_SIGNATURE + struct.pack(">I4s", 10_000_000, b"IHDR"))
self.assert_invalid(png(before=ihdr()))
self.assert_invalid(png(before=chunk(b"ABCD", b"unknown critical")))
self.assert_invalid(png(before=chunk(b"abca", b"reserved lowercase")))
self.assert_invalid(png()[:-12] + chunk(b"IEND", b"invalid"))
self.assert_invalid(png(after=chunk(b"PLTE", b"\x00\x00\x00")))
self.assert_invalid(png(before=chunk(b"PLTE", b"\x00\x00")))
self.assert_invalid(png(before=chunk(b"PLTE", b"\x00\x00\x00") * 2))
def test_palette_shape_and_transparency(self):
header = ihdr(depth=1, color=3)
palette = chunk(b"PLTE", b"\xff\x00\x00")
self.validate(png(b"\x00\x00", header=header, before=palette))
self.assert_invalid(png(b"\x00\x00", header=header))
self.assert_invalid(png(b"\x00\x00", header=header,
before=chunk(b"PLTE", bytes(9))))
self.assert_invalid(png(before=chunk(b"tRNS", b"\x00")))
def test_crc_compressed_tail_and_pixel_bomb(self):
damaged = bytearray(png())
damaged[-1] ^= 1
self.assert_invalid(bytes(damaged))
self.assert_invalid(PNG_SIGNATURE + ihdr() +
chunk(b"IDAT", zlib.compress(b"\x00\xff\x00\x00") + b"junk") +
chunk(b"IEND", b""))
with self.assertRaises(TooManyPixels):
self.validate(PNG_SIGNATURE + ihdr(10000, 10000))
def test_adam7_pass_filter_boundaries(self):
width, height = 9, 7
passes = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8),
(2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
raw = bytearray()
pass_starts = []
for x, y, dx, dy in passes:
w = (width - x + dx - 1) // dx if width > x else 0
h = (height - y + dy - 1) // dy if height > y else 0
if w and h:
pass_starts.append(len(raw))
for _ in range(h):
raw.extend(b"\x00" + bytes(w * 4))
header = ihdr(width, height, color=6, interlace=1)
valid = png(bytes(raw), header=header)
self.validate(valid)
with Image.open(io.BytesIO(valid)) as decoded:
decoded.load()
self.assertEqual(decoded.size, (width, height))
for position in pass_starts:
corrupted = bytearray(raw)
corrupted[position] = 5
self.assert_invalid(png(bytes(corrupted), header=header))
def test_jpeg_and_truncated_progressive_above_old_bypass_limit(self):
image = Image.new("RGB", (4100, 4000), "white")
data = io.BytesIO()
image.save(data, format="JPEG", progressive=True)
image.close()
encoded = data.getvalue()
result = self.validate(encoded, "image/jpeg")
self.assertEqual((result.width, result.height), (4100, 4000))
# Keep SOF/header and final EOI, but truncate the first scan's
# header. The former >16 MP branch only inspected EOI and accepted
# this malformed file. Actual entropy decoding must reject it.
scan = encoded.index(b"\xff\xda")
corrupted = encoded[:scan + 4] + b"\xff\xd9"
self.assert_invalid(corrupted, "image/jpeg")
self.assert_invalid(encoded[:-2], "image/jpeg")
if __name__ == "__main__":
unittest.main(verbosity=2)
+158
View File
@@ -0,0 +1,158 @@
"""Shared helpers for the student's explicit lab5 checks; never log tokens."""
from __future__ import annotations
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from uuid import UUID
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def encoded(image: Image.Image, format: str = "PNG", **options) -> bytes:
output = io.BytesIO()
image.save(output, format=format, **options)
return output.getvalue()
def upload(client, actor, chat, content, *, filename="sample.png", mime="image/png"):
from urllib.parse import quote
result = client.call(
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename={quote(filename, safe='')}",
202, actor=actor, raw=content, headers={"Content-Type": mime}, schema="Attachment",
)["json"]
check(result["status"] == "queued", "upload must return its queued snapshot")
check(result["variants"] == [], "queued snapshot must not expose partial variants")
return result
def metadata(client, actor, attachment_id):
return client.call("GET", f"/api/v1/attachments/{attachment_id}", actor=actor,
schema="Attachment")["json"]
def wait_until(predicate, message, timeout=90, interval=0.3):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
value = predicate()
if value:
return value
time.sleep(interval)
raise Failure(message)
class Stand:
"""Control only containers bearing this lab's Compose project label."""
def __init__(self):
self.project = os.environ.get("COMPOSE_PROJECT", "messenger-lab6")
@staticmethod
def docker(*args, stdin=None, timeout=70):
process = subprocess.run(["docker", *args], input=stdin, text=True,
capture_output=True, timeout=timeout)
# Docker command output can contain secrets: do not echo it on errors.
if process.returncode:
raise Failure(f"docker {args[0]} failed (exit {process.returncode})")
return process.stdout.strip()
def ids(self, service, *, all=True):
args = ["ps", "-q"]
if all:
args.append("-a")
args += ["--filter", f"label=com.docker.compose.project={self.project}",
"--filter", f"label=com.docker.compose.service={service}"]
return self.docker(*args).split()
def one(self, service):
ids = self.ids(service)
check(len(ids) == 1, f"expected one {service} container")
return ids[0]
def stop(self, *services):
ids = [cid for service in services for cid in self.ids(service)]
check(bool(ids), "containers to stop were not found")
self.docker("stop", "--time", "3", *ids)
def start(self, *services):
ids = [cid for service in services for cid in self.ids(service)]
check(bool(ids), "containers to start were not found")
self.docker("start", *ids)
def restart(self, *services):
ids = [cid for service in services for cid in self.ids(service)]
self.docker("restart", "--time", "3", *ids)
def sql(self, statement):
return self.docker("exec", "-i", self.one("db"), "psql", "-U", "messenger",
"-d", "messenger", "-v", "ON_ERROR_STOP=1", "-tA",
stdin=statement)
def row(self, attachment_id):
aid = str(UUID(attachment_id))
value = self.sql(f"SELECT row_to_json(a) FROM attachments a WHERE id='{aid}';")
check(bool(value), "attachment row disappeared")
return json.loads(value)
def operator(self, *args):
# Use a running API image so stopping worker/publisher is supported.
apis = self.ids("api", all=False)
check(bool(apis), "no API available for operator command")
return self.docker("exec", apis[0], "python", "-m", "app.operator", *args)
def objects_exist(self, keys):
code = """
import asyncio, json, sys
from app.storage import storage
async def main():
await storage.start()
try:
print(json.dumps([await storage.exists(key) for key in json.load(sys.stdin)]))
finally:
await storage.close()
asyncio.run(main())
"""
apis = self.ids("api", all=False)
return json.loads(self.docker("exec", "-i", apis[0], "python", "-c", code,
stdin=json.dumps(keys)))
def replace_object(self, key, content, mime="image/png"):
"""Explicit fault-test operation; key must come from this test's DB row."""
import base64
code = """
import asyncio, base64, io, json, sys
from app.storage import storage
async def main():
key, encoded, mime = json.load(sys.stdin)
content = base64.b64decode(encoded)
await storage.start()
try:
await storage.put(key, io.BytesIO(content), len(content), mime)
finally:
await storage.close()
asyncio.run(main())
"""
self.docker("exec", "-i", self.ids("api", all=False)[0], "python", "-c", code,
stdin=json.dumps([key, base64.b64encode(content).decode(), mime]))
def ready(self):
for service in ("db", "broker", "api", "lb"):
for cid in self.ids(service):
raw = self.docker("inspect", "--format", "{{json .State}}", cid)
state = json.loads(raw)
if not state.get("Running"):
return False
if "Health" in state and state["Health"]["Status"] != "healthy":
return False
return True
def wait_ready(self):
wait_until(self.ready, "stand did not recover readiness", timeout=90)
+145
View File
@@ -0,0 +1,145 @@
"""Grade 4 image semantics, actual decoded bytes and upload rejection checks.
Run explicitly against the running lab5 stand:
python student-tests/lab5_images.py --base-url http://localhost:8080
Requires Pillow, also present in the application image.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import struct
import zlib
from PIL import Image
from lab5_helpers import Client, Failure, check, encoded, upload
def assert_variants(client, actor, att, source, expected_thumb, expected_optimized,
*, white_corner=False, green_crop=False):
ready = client.wait_ready(actor, att)
check(ready["sha256"] == hashlib.sha256(source).hexdigest(), "original SHA-256 changed")
check(ready["size_bytes"] == len(source), "original byte count changed")
check(ready["error_code"] is None, "ready has error_code")
by_name = {item["name"]: item for item in ready["variants"]}
check(len(ready["variants"]) == 3 and set(by_name) == {"thumbnail", "crop", "optimized"},
"ready must contain exactly the three promised variants")
check(not any(k in json.dumps(ready) for k in ("object_key", "staging_key", "broker_url")),
"storage internals leaked into metadata")
original = client.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=actor)
check(original["bytes"] == source, "original was re-encoded or changed")
check(original["headers"].get_content_type() == ready["content_type"],
"original Content-Type changed")
for name, expected_size, expected_format, mime in (
("thumbnail", expected_thumb, "JPEG", "image/jpeg"),
("crop", (128, 128), "JPEG", "image/jpeg"),
("optimized", expected_optimized, "WEBP", "image/webp"),
):
variant = by_name[name]
response = client.call("GET", f"/api/v1/attachments/{att['id']}/content?variant={name}",
actor=actor)
data = response["bytes"]
check(response["headers"].get_content_type() == mime, f"{name}: wrong MIME")
check(variant["content_type"] == mime, f"{name}: wrong metadata MIME")
check(variant["size_bytes"] == len(data), f"{name}: wrong size_bytes")
check(variant["sha256"] == hashlib.sha256(data).hexdigest(), f"{name}: wrong SHA-256")
with Image.open(io.BytesIO(data)) as image:
image.load()
check(image.format == expected_format, f"{name}: wrong actual format")
check(image.size == expected_size, f"{name}: wrong actual dimensions {image.size}")
check((variant["width"], variant["height"]) == expected_size,
f"{name}: dimensions metadata differs from bytes")
check(not image.getexif(), f"{name}: EXIF was retained")
if white_corner and name == "thumbnail":
check(min(image.convert("RGB").getpixel((0, 0))) > 245,
"transparent JPEG background is not white")
if green_crop and name == "crop":
pixel = image.convert("RGB").getpixel((10, 64))
check(pixel[1] > 180 and pixel[0] < 40 and pixel[2] < 40,
"crop is not taken from the centered square")
return ready
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default=None)
args = parser.parse_args()
client = Client(args.base_url, timeout=40)
alice, bob, eve, chat = client.bootstrap()
image = Image.new("RGB", (400, 200), (0, 220, 0))
image.paste((220, 0, 0), (0, 0, 100, 200))
image.paste((0, 0, 220), (300, 0, 400, 200))
source = encoded(image)
att = upload(client, alice, chat, source)
assert_variants(client, bob, att, source, (256, 128), (400, 200), green_crop=True)
for suffix in ("", "/content", "/content?variant=thumbnail", "/content?variant=crop",
"/content?variant=optimized"):
client.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, actor=eve)
print("PASS centered crop, three real variants, checksums, original bytes and ACL", flush=True)
for size, thumb, optimized in (
((11, 7), (11, 7), (11, 7)),
((513, 201), (256, 100), (513, 201)),
((1701, 1003), (256, 150), (1280, 754)),
):
source = encoded(Image.new("RGB", size, (30, 80, 170)))
att = upload(client, alice, chat, source)
assert_variants(client, bob, att, source, thumb, optimized)
print("PASS no upscaling and floor rounding for thumbnail/optimized", flush=True)
source = encoded(Image.new("RGBA", (320, 200), (200, 30, 30, 0)))
att = upload(client, alice, chat, source)
assert_variants(client, bob, att, source, (256, 160), (320, 200), white_corner=True)
print("PASS transparent PNG composited onto white JPEG", flush=True)
exif = Image.Exif()
exif[274] = 6
exif[270] = "student test metadata must be stripped"
source = encoded(Image.new("RGB", (320, 200), (90, 20, 170)), "JPEG", exif=exif)
att = upload(client, alice, chat, source, filename="rotated.jpg", mime="image/jpeg")
assert_variants(client, bob, att, source, (160, 256), (200, 320))
print("PASS EXIF orientation applied to variants and metadata removed", flush=True)
path = f"/api/v1/chats/{chat['id']}/attachments?filename=bad.png"
for data, mime, expected in ((b"this is not a PNG", "image/png", 415),
(source, "image/png", 415),
(b"x" * (10485760 + 1), "image/png", 413)):
client.call("POST", path, expected, actor=alice, raw=data, headers={"Content-Type": mime})
def png_chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
bad_filter = (b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", zlib.compress(b"\x05\x00\x00\x00"))
+ png_chunk(b"IEND", b""))
client.call("POST", path, 415, actor=alice, raw=bad_filter,
headers={"Content-Type": "image/png"})
with Image.new("RGB", (4100, 4000), "blue") as large:
progressive = encoded(large, "JPEG", progressive=True)
scan = progressive.index(b"\xff\xda")
client.call("POST", path, 415, actor=alice, raw=progressive[:scan + 4] + b"\xff\xd9",
headers={"Content-Type": "image/jpeg"})
print("PASS malformed PNG filter and truncated >16MP progressive JPEG rejected before 202", flush=True)
ihdr = struct.pack(">IIBBBBB", 10001, 4000, 8, 2, 0, 0, 0)
chunk = b"IHDR" + ihdr
oversized = b"\x89PNG\r\n\x1a\n" + struct.pack(">I", len(ihdr)) + chunk + struct.pack(">I", zlib.crc32(chunk))
client.call("POST", path, 413, actor=alice, raw=oversized,
headers={"Content-Type": "image/png"})
from urllib.parse import quote
for bad_name in ("../x.png", "a\\b.png", "a\x00.png", "a\n.png"):
client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={quote(bad_name, safe='')}",
400, actor=alice, raw=encoded(Image.new("RGB", (2, 2))),
headers={"Content-Type": "image/png"})
print("PASS invalid/MIME mismatch 415, >10MiB and >40M pixels 413, unsafe filenames 400", flush=True)
print("PASS: lab5 grade4 image checks")
if __name__ == "__main__":
try:
main()
except (Failure, ValueError, OSError) as exc:
print("FAIL:", str(exc), flush=True)
raise SystemExit(1)
+52
View File
@@ -0,0 +1,52 @@
"""Run inside the worker image; deliberately small limits, no stack changes.
PowerShell: Get-Content -Raw student-tests/lab5_limits.py | docker compose exec -T worker python
Linux: docker compose exec -T worker python < student-tests/lab5_limits.py
"""
import asyncio
import os
from pathlib import Path
import tempfile
import time
from PIL import Image
from app import worker
async def main():
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
source = directory / "large.png"
with Image.new("RGB", (4000, 4000), "green") as image:
image.save(source)
old_memory = os.environ.get("WORKER_MEMORY_MB")
old_timeout = worker.IMAGE_TIMEOUT
try:
os.environ["WORKER_MEMORY_MB"] = "48"
try:
await worker.generate(source, directory)
raise AssertionError("decoder exceeded its deliberately small memory budget")
except worker.PermanentFailure as error:
assert str(error) == "image_resource_limit", str(error)
print("PASS memory: real 16MP image decoder stopped at RLIMIT_AS=48MiB", flush=True)
os.environ["WORKER_MEMORY_MB"] = "768"
worker.IMAGE_TIMEOUT = 0.001
started = time.monotonic()
try:
await worker.generate(source, directory)
raise AssertionError("decoder exceeded wall timeout")
except worker.PermanentFailure as error:
assert str(error) == "image_timeout", str(error)
assert time.monotonic() - started < 3, "timed-out child was not promptly reaped"
print("PASS timeout: decoder killed and reaped; parent continues", flush=True)
finally:
worker.IMAGE_TIMEOUT = old_timeout
if old_memory is None:
os.environ.pop("WORKER_MEMORY_MB", None)
else:
os.environ["WORKER_MEMORY_MB"] = old_memory
print("PASS: lab5 decoder resource limits", flush=True)
asyncio.run(main())
+218
View File
@@ -0,0 +1,218 @@
"""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)