Files
mtusi2026lab5/student-tests/before_ack.py
T

263 lines
7.9 KiB
Python

from __future__ import annotations
import base64
import hashlib
import json
import secrets
import subprocess
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, api, dc, http, wait_ready
from outbox_gap import snapshot
EVIDENCE = ROOT / "evidence" / "before_ack.json"
def sql(query):
return dc(
"exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger",
"-X", "-A", "-t", "-v", "ON_ERROR_STOP=1",
"-c", query,
)
def worker_state():
ids = dc("ps", "-a", "-q", "worker").split()
if len(ids) != 1:
raise AssertionError("This test expects exactly one worker container")
template = (
'{"started_at":{{json .State.StartedAt}},'
'"restart_count":{{.RestartCount}}}'
)
result = subprocess.run(
["docker", "inspect", "--format", template, ids[0]],
capture_output=True,
text=True,
check=True,
)
return json.loads(result.stdout)
def object_keys(attachment_id):
code = """
import json
import sys
from uuid import UUID
from app.storage import bucket_name, get_client
attachment_id = str(UUID(sys.argv[1]))
client = get_client()
keys = []
for prefix in (
f"originals/{attachment_id}",
f"variants/{attachment_id}/",
):
for page in client.get_paginator("list_objects_v2").paginate(
Bucket=bucket_name(), Prefix=prefix,
):
keys.extend(item["Key"] for item in page.get("Contents", []))
print(json.dumps(sorted(keys)))
"""
return json.loads(
dc("exec", "-T", "worker", "python", "-c", code, attachment_id)
)
def main():
evidence = {"scenario": "worker crash after ready commit, before ack"}
job_id = None
restore = False
try:
wait_ready()
if not dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Start worker before this test")
username = "ack_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Before ack test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Before ack",
"member_ids": [user["id"]],
},
)
restore = True
dc("stop", "worker")
if dc("ps", "--status", "running", "-q", "worker"):
raise AssertionError("Worker is still running")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
before = snapshot(attachment_id)
job_id = str(UUID(before["job_id"]))
sql(f"""
INSERT INTO pipeline_fault_injections (job_id, stage)
VALUES ('{job_id}'::uuid, 'before_ack');
""")
evidence["attachment_id"] = attachment_id
evidence["job_id"] = job_id
evidence["initial_job"] = before
print(f"Armed one-shot before_ack fault for job {job_id}")
dc("start", "worker")
started_state = worker_state()
evidence["worker_before_fault"] = started_state
fault_line = f"fault_injection job_id={job_id} stage=before_ack"
redelivery_line = f"delivery job_id={job_id} redelivered=True"
ack_line = f"ack job_id={job_id}"
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
logs = dc("logs", "--no-color", "--tail=300", "worker")
fault_at = logs.find(fault_line)
redelivery_at = logs.find(redelivery_line)
ack_at = logs.find(ack_line)
if 0 <= fault_at < redelivery_at < ack_at:
break
time.sleep(1)
else:
raise AssertionError(
"Expected fault -> redelivered=True -> ack was not observed"
)
evidence["delivery_events"] = [
line for line in logs.splitlines()
if job_id in line
]
print("Observed: before_ack crash -> redelivered=True -> ack")
after_state = worker_state()
assert (
after_state["started_at"] != started_state["started_at"]
or after_state["restart_count"] > started_state["restart_count"]
)
evidence["worker_after_fault"] = after_state
consumed = json.loads(sql(f"""
SELECT json_build_object(
'consumed', consumed_at IS NOT NULL
)
FROM pipeline_fault_injections
WHERE job_id = '{job_id}'::uuid
AND stage = 'before_ack';
"""))
assert consumed["consumed"] is True
final = snapshot(attachment_id)
assert final["job_id"] == job_id
assert final["status"] == "ready"
assert final["attempt"] == 1
assert final["outbox_count"] == 1
current = api("GET", path, 200, token=token)
assert current["status"] == "ready"
assert current["error_code"] is None
variants = {item["name"]: item for item in current["variants"]}
assert len(current["variants"]) == 3
assert set(variants) == {"thumbnail", "crop", "optimized"}
status, body = http("GET", path + "/content", token=token)
assert status == 200 and body == original
for name, metadata in variants.items():
status, body = http(
"GET", path + "/content?variant=" + name,
token=token,
)
assert status == 200
assert len(body) == metadata["size_bytes"]
assert hashlib.sha256(body).hexdigest() == metadata["sha256"]
variant_count = int(sql(f"""
SELECT count(*)
FROM attachment_variants
WHERE attachment_id = '{attachment_id}'::uuid;
"""))
assert variant_count == 3
keys = object_keys(attachment_id)
expected_keys = sorted([
f"originals/{attachment_id}",
f"variants/{attachment_id}/v1/thumbnail",
f"variants/{attachment_id}/v1/crop",
f"variants/{attachment_id}/v1/optimized",
])
assert keys == expected_keys
evidence["final_job"] = final
evidence["fault"] = consumed
evidence["variant_rows"] = variant_count
evidence["final_object_keys"] = keys
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
if job_id is not None:
sql(f"""
UPDATE pipeline_fault_injections
SET consumed_at = clock_timestamp()
WHERE job_id = '{job_id}'::uuid
AND stage = 'before_ack'
AND consumed_at IS NULL;
""")
finally:
try:
if restore:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: crash before ack caused broker redelivery; "
"ready result preserved, attempt=1, variants=3, objects=4"
)
if __name__ == "__main__":
main()