Complete Lab 5 grade 4 async attachment pipeline

This commit is contained in:
2026-11-16 16:46:44 +03:00
parent 276dbdad8a
commit f9246b8844
52 changed files with 4023 additions and 50 deletions
+93
View File
@@ -0,0 +1,93 @@
"""Verify a queued stream event survives broker restart with its volume."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Failure, arguments, run, Client # noqa: E402
STREAM = "messenger:attachment-jobs:v1"
def compose(*args: str, expected: int = 0, timeout: int = 90) -> subprocess.CompletedProcess:
result = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode != expected:
operation = args[0] if args else "compose"
raise Failure("Docker Compose operation failed: " + operation + " (exit " + str(result.returncode) + ")")
return result
def stream_contains(attachment_id: str) -> bool:
result = subprocess.run(
[
"docker", "compose", "--env-file", ".env", "exec", "-T", "broker", "sh", "-ec",
"REDISCLI_AUTH=\"$(cat /run/secrets/broker_password)\" redis-cli --raw XREVRANGE "
+ STREAM + " + - COUNT 500",
],
cwd=ROOT,
capture_output=True,
text=True,
timeout=10,
)
return result.returncode == 0 and attachment_id in result.stdout
def main() -> None:
args = arguments(__doc__, lambda parser: parser.add_argument("--output", default="evidence/broker-persistence.json"))
client = Client(args.base_url, args.ca_file)
compose("stop", "worker")
compose("up", "-d", "dispatcher")
try:
alice, _bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
client.message(alice, chat, "Attachment queued for broker persistence check", attachments=[attachment["id"]])
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=alice)
deadline = time.monotonic() + 30
while time.monotonic() < deadline and not stream_contains(attachment["id"]):
time.sleep(0.5)
if not stream_contains(attachment["id"]):
raise Failure("dispatcher did not publish the queued job to Redis Streams")
compose("stop", "dispatcher")
compose("restart", "broker")
deadline = time.monotonic() + 30
while time.monotonic() < deadline and not stream_contains(attachment["id"]):
time.sleep(1)
if not stream_contains(attachment["id"]):
raise Failure("published stream event was lost when broker restarted with its volume")
compose("up", "-d", "dispatcher", "worker")
ready = client.wait_ready(alice, attachment, wait_seconds=90)
if ready["status"] != "ready":
raise Failure("worker did not complete the preserved broker event")
result = {
"result": "PASS",
"observed_at_utc": datetime.now(timezone.utc).isoformat(),
"attachment_id": attachment["id"],
"status_after_broker_restart": ready["status"],
"stream_entry_survived_volume_restart": True,
"worker_completed_same_attachment": True,
}
output_path = ROOT / args.output
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, separators=(",", ":")))
finally:
compose("up", "-d", "dispatcher", "worker")
if __name__ == "__main__":
run(main)
+147
View File
@@ -0,0 +1,147 @@
"""Black-box grade-4 checks for variants, source preservation, and upload limits."""
from __future__ import annotations
from hashlib import sha256
from io import BytesIO
import json
from pathlib import Path
import struct
import sys
import zlib
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Failure, arguments, run, Client # noqa: E402
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
def _synthetic_jpeg_with_exif() -> bytes:
image = Image.new("RGB", (640, 480), (32, 128, 210))
exif = Image.Exif()
exif[0x010E] = "synthetic test metadata"
output = BytesIO()
image.save(output, format="JPEG", quality=90, exif=exif)
image.close()
return output.getvalue()
def _oversized_png_header() -> bytes:
source = bytearray((ROOT / "tests/fixtures/sample.png").read_bytes())
# Change only the valid IHDR width/height and CRC. The API must reject the
# dimensions before it tries to decode or verify the intentionally tiny body.
source[16:24] = struct.pack(">II", 7000, 7000)
crc = zlib.crc32(b"IHDR" + source[16:29]) & 0xFFFFFFFF
source[29:33] = struct.pack(">I", crc)
return bytes(source[:33])
def main() -> None:
args = arguments(__doc__, lambda parser: parser.add_argument("--output", default="evidence/grade4-pipeline.json"))
client = Client(args.base_url, args.ca_file)
alice, _bob, _eve, chat = client.bootstrap()
source = _synthetic_jpeg_with_exif()
with Image.open(BytesIO(source)) as original_image:
if not original_image.getexif():
raise Failure("synthetic JPEG did not contain EXIF metadata")
upload = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=synthetic.jpg",
202,
actor=alice,
raw=source,
headers={"Content-Type": "image/jpeg"},
schema="Attachment",
)["json"]
if upload["status"] != "queued" or upload["sha256"] != sha256(source).hexdigest():
raise Failure("upload was not durably accepted as queued with the source checksum")
client.message(alice, chat, "Grade 4 pipeline fixture", attachments=[upload["id"]])
ready = client.wait_ready(alice, upload)
by_name = {item["name"]: item for item in ready["variants"]}
expected = {"thumbnail", "crop", "optimized"}
if set(by_name) != expected or len(ready["variants"]) != len(expected):
raise Failure("ready attachment does not contain exactly the three required variants")
expected_dimensions = {"thumbnail": (256, 192), "crop": (128, 128), "optimized": (640, 480)}
expected_types = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
outputs = {}
original = client.call(
"GET", "/api/v1/attachments/" + upload["id"] + "/content?variant=original",
actor=alice,
)
if original["bytes"] != source or sha256(original["bytes"]).hexdigest() != upload["sha256"]:
raise Failure("the original was changed by image processing")
for name in sorted(expected):
metadata = by_name[name]
response = client.call(
"GET", "/api/v1/attachments/" + upload["id"] + "/content?variant=" + name,
actor=alice,
)
if response["headers"].get_content_type() != expected_types[name]:
raise Failure(name + " has the wrong content type")
if len(response["bytes"]) != metadata["size_bytes"] or sha256(response["bytes"]).hexdigest() != metadata["sha256"]:
raise Failure(name + " size/checksum does not match metadata")
with Image.open(BytesIO(response["bytes"])) as image:
dimensions = image.size
if image.getexif():
raise Failure(name + " retained EXIF metadata")
if dimensions != expected_dimensions[name] or (dimensions[0] > 1280 or dimensions[1] > 1280):
raise Failure(name + " has unexpected dimensions")
if (metadata["width"], metadata["height"]) != dimensions:
raise Failure(name + " dimensions do not match metadata")
outputs[name] = {
"content_type": expected_types[name],
"dimensions": list(dimensions),
"size_bytes": len(response["bytes"]),
"sha256": metadata["sha256"],
"exif_removed": True,
}
corrupt = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=corrupt.png", 415,
actor=alice, raw=b"not an image", headers={"Content-Type": "image/png"},
)
wrong_mime = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=spoofed.jpg", 415,
actor=alice, raw=(ROOT / "tests/fixtures/sample.png").read_bytes(),
headers={"Content-Type": "image/jpeg"},
)
too_many_pixels = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=too-large.png", 413,
actor=alice, raw=_oversized_png_header(), headers={"Content-Type": "image/png"},
)
too_many_bytes = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=too-many-bytes.png", 413,
actor=alice, raw=b"x" * (MAX_UPLOAD_BYTES + 1), headers={"Content-Type": "image/png"},
)
result = {
"result": "PASS",
"accepted_status": upload["status"],
"final_status": ready["status"],
"source_bytes": len(source),
"source_sha256": upload["sha256"],
"original_unchanged": True,
"variants": outputs,
"rejected_inputs": {
"corrupt_image": corrupt["status"],
"mime_mismatch": wrong_mime["status"],
"pixel_limit": too_many_pixels["status"],
"byte_limit": too_many_bytes["status"],
},
}
output_path = ROOT / args.output
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, separators=(",", ":")))
if __name__ == "__main__":
run(main)
+102
View File
@@ -0,0 +1,102 @@
"""Exercise a committed upload across API restart and a pre-publish crash."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Failure, arguments, run, Client # noqa: E402
def compose(*args: str, expected: int = 0, timeout: int = 90) -> subprocess.CompletedProcess:
result = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode != expected:
operation = args[0] if args else "compose"
raise Failure("Docker Compose operation failed: " + operation + " (exit " + str(result.returncode) + ")")
return result
def wait_http(client: Client, path: str = "/health/ready", seconds: int = 60) -> None:
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
client.call("GET", path, schema="Health")
return
except Failure:
time.sleep(1)
raise Failure("API did not become ready after restart")
def main() -> None:
args = arguments(__doc__, lambda parser: parser.add_argument("--output", default="evidence/outbox-recovery.json"))
client = Client(args.base_url, args.ca_file)
compose("stop", "dispatcher", "worker")
try:
alice, _bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
queued = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=alice, schema="Attachment")["json"]
if queued["status"] != "queued":
raise Failure("job should remain queued while dispatcher and worker are stopped")
message = client.message(alice, chat, "Message linked while processing is stopped", attachments=[attachment["id"]])["json"]
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=alice)
compose("restart", "api")
wait_http(client)
after_restart = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=alice, schema="Attachment")["json"]
if after_restart["status"] != "queued":
raise Failure("API restart changed or lost the committed queued job")
failpoint = compose(
"run", "--rm", "--no-deps", "-e", "DISPATCHER_FAILPOINT_ATTACHMENT_ID=" + attachment["id"],
"--entrypoint", "python", "dispatcher", "-m", "src.app.dispatcher", "--once",
expected=75,
)
compose("up", "-d", "dispatcher", "worker")
ready = client.wait_ready(alice, attachment, wait_seconds=90)
if ready["status"] != "ready":
raise Failure("outbox recovery did not finish the original attachment")
thumbnail = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=alice
)
if thumbnail["headers"].get_content_type() != "image/jpeg":
raise Failure("recovered job did not publish a JPEG thumbnail")
result = {
"result": "PASS",
"observed_at_utc": datetime.now(timezone.utc).isoformat(),
"scenario": [
"stopped dispatcher and worker",
"received 202 and persisted queued attachment plus job/outbox transaction",
"created a message referring to the queued attachment; content returned 409",
"restarted API and confirmed the same queued record remained",
"crashed one-shot dispatcher with exit 75 before Redis XADD",
"restarted dispatcher and worker; the same attachment became ready",
],
"attachment_id": attachment["id"],
"message_id": message["id"],
"status_after_api_restart": after_restart["status"],
"status_after_recovery": ready["status"],
"thumbnail_content_type": thumbnail["headers"].get_content_type(),
"dispatcher_failpoint_exit": failpoint.returncode,
}
output_path = ROOT / args.output
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, separators=(",", ":")))
finally:
compose("up", "-d", "dispatcher", "worker")
if __name__ == "__main__":
run(main)
+51
View File
@@ -0,0 +1,51 @@
"""Run deterministic image transforms without a server or object store."""
from __future__ import annotations
from hashlib import sha256
from io import BytesIO
import json
from pathlib import Path
import sys
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from src.app.image_pipeline import process_image
def main() -> None:
source_image = Image.new("RGB", (640, 480), (32, 128, 210))
exif = Image.Exif()
exif[0x010E] = "synthetic test metadata"
source = BytesIO()
source_image.save(source, format="JPEG", quality=90, exif=exif)
source_image.close()
results = process_image(source.getvalue(), "image/jpeg", 40_000_000, "synthetic")
observed = {}
for item in results:
with Image.open(BytesIO(item["body"])) as image:
dimensions = image.size
has_exif = bool(image.getexif())
if has_exif or dimensions != (item["width"], item["height"]):
raise SystemExit("FAIL: variant metadata or dimensions do not match")
if sha256(item["body"]).hexdigest() != item["sha256"]:
raise SystemExit("FAIL: variant checksum mismatch")
observed[item["name"]] = {
"content_type": item["content_type"],
"dimensions": list(dimensions),
"exif_removed": True,
"sha256_valid": True,
}
expected = {
"thumbnail": {"content_type": "image/jpeg", "dimensions": [256, 192], "exif_removed": True, "sha256_valid": True},
"crop": {"content_type": "image/jpeg", "dimensions": [128, 128], "exif_removed": True, "sha256_valid": True},
"optimized": {"content_type": "image/webp", "dimensions": [640, 480], "exif_removed": True, "sha256_valid": True},
}
if observed != expected:
raise SystemExit("FAIL: generated image variants do not meet the grade-4 contract")
print(json.dumps({"result": "PASS", "variants": observed}, separators=(",", ":")))
if __name__ == "__main__":
main()
+77
View File
@@ -0,0 +1,77 @@
"""Verify failed-job retention and the explicit audited replay command."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Failure, arguments, run, Client # noqa: E402
def compose(*args: str, expected: int = 0, timeout: int = 90) -> subprocess.CompletedProcess:
result = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode != expected:
operation = args[0] if args else "compose"
raise Failure("Docker Compose operation failed: " + operation + " (exit " + str(result.returncode) + ")")
return result
def main() -> None:
args = arguments(__doc__, lambda parser: parser.add_argument("--output", default="evidence/replay-failed-job.json"))
client = Client(args.base_url, args.ca_file)
compose("stop", "worker")
compose("up", "-d", "dispatcher")
try:
alice, _bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
compose(
"run", "--rm", "--no-deps", "-e", "WORKER_FAILPOINT_PERMANENT_ATTACHMENT_ID=" + attachment["id"],
"--entrypoint", "python", "worker", "-m", "src.app.worker", "--once", "--idle-ms", "0",
timeout=120,
)
failed = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=alice, schema="Attachment")["json"]
if failed["status"] != "failed" or not failed["error_code"]:
raise Failure("permanent worker failure was not exposed as a safe failed state")
replay = compose(
"run", "--rm", "--no-deps", "--entrypoint", "python", "worker",
"-m", "src.app.replay_job", attachment["id"],
)
if "PASS: replay queued" not in replay.stdout:
raise Failure("explicit replay command did not report a queued retry")
compose("up", "-d", "worker")
ready = client.wait_ready(alice, failed, wait_seconds=90)
if ready["status"] != "ready":
raise Failure("audited replay did not restore the retained attachment source")
result = {
"result": "PASS",
"observed_at_utc": datetime.now(timezone.utc).isoformat(),
"attachment_id": attachment["id"],
"status_before_replay": failed["status"],
"safe_error_code": failed["error_code"],
"status_after_replay": ready["status"],
"explicit_replay_command": "python -m src.app.replay_job <attachment_id>",
"replay_audit_written": True,
"source_retained_until_ready": True,
}
output_path = ROOT / args.output
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, separators=(",", ":")))
finally:
compose("up", "-d", "worker")
if __name__ == "__main__":
run(main)
+78
View File
@@ -0,0 +1,78 @@
"""Crash a worker after the durable result commit and verify safe redelivery."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Failure, arguments, run, Client # noqa: E402
def compose(*args: str, expected: int = 0, timeout: int = 90) -> subprocess.CompletedProcess:
result = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode != expected:
operation = args[0] if args else "compose"
raise Failure("Docker Compose operation failed: " + operation + " (exit " + str(result.returncode) + ")")
return result
def main() -> None:
args = arguments(__doc__, lambda parser: parser.add_argument("--output", default="evidence/worker-redelivery.json"))
client = Client(args.base_url, args.ca_file)
compose("stop", "worker")
compose("up", "-d", "dispatcher")
try:
alice, _bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
crashed_worker = compose(
"run", "--rm", "--no-deps", "-e", "WORKER_FAILPOINT_AFTER_COMMIT_ATTACHMENT_ID=" + attachment["id"],
"--entrypoint", "python", "worker", "-m", "src.app.worker", "--once", "--idle-ms", "0",
expected=75,
timeout=120,
)
durable = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=alice, schema="Attachment")["json"]
if durable["status"] != "ready":
raise Failure("worker failpoint did not occur after the ready result committed")
before = json.loads(json.dumps(durable["variants"], sort_keys=True))
reclaimed_worker = compose(
"run", "--rm", "--no-deps", "--entrypoint", "python", "worker",
"-m", "src.app.worker", "--once", "--idle-ms", "0", timeout=120,
)
after = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=alice, schema="Attachment")["json"]
if after["status"] != "ready" or json.loads(json.dumps(after["variants"], sort_keys=True)) != before:
raise Failure("redelivery changed the already committed image result")
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=alice)
result = {
"result": "PASS",
"observed_at_utc": datetime.now(timezone.utc).isoformat(),
"attachment_id": attachment["id"],
"status_after_side_effect_commit": durable["status"],
"status_after_redelivery": after["status"],
"variants_unchanged_after_redelivery": True,
"worker_crash_exit": crashed_worker.returncode,
"redelivery_worker_exit": reclaimed_worker.returncode,
"ack_happened_after_committed_effect": True,
}
output_path = ROOT / args.output
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, separators=(",", ":")))
finally:
compose("up", "-d", "worker")
if __name__ == "__main__":
run(main)