forked from mtusi2026/mtusi2026lab5
203 lines
6.4 KiB
Python
203 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Demonstrate outbox recovery and operator replay (grade 4). Writes no tokens."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "student-tests"))
|
|
sys.path.insert(0, str(ROOT / "src"))
|
|
|
|
import imagegen # noqa: E402
|
|
from helpers import call, chat_for, register, upload, wait_ready # noqa: E402
|
|
|
|
OUT = ROOT / "evidence" / "lab5-outbox-replay.txt"
|
|
|
|
|
|
def _compose(*args: str) -> None:
|
|
subprocess.check_call(["docker", "compose", "--env-file", ".env", *args], cwd=str(ROOT))
|
|
|
|
|
|
def main() -> int:
|
|
lines: list[str] = []
|
|
|
|
def log(msg: str) -> None:
|
|
print(msg)
|
|
lines.append(msg)
|
|
|
|
# --- Crash after side effect before ack ---
|
|
_compose("stop", "worker")
|
|
_compose(
|
|
"run",
|
|
"-d",
|
|
"--name",
|
|
"lab5-worker-crash",
|
|
"-e",
|
|
"WORKER_CRASH_AFTER_SIDE_EFFECT=1",
|
|
"worker",
|
|
)
|
|
try:
|
|
time.sleep(3)
|
|
alice = register("ox_crash")
|
|
chat = chat_for(alice, title="crash-ack")
|
|
data = imagegen.rgb_png(48, 48)
|
|
att = upload(alice["token"], chat["id"], data, "c.png", "image/png", 202)["json"]
|
|
# Wait until ready despite worker exit after side effect (redelivery).
|
|
ready = wait_ready(alice["token"], att, wait_seconds=120)
|
|
log(
|
|
f"PASS crash-after-side-effect→redelivery ready "
|
|
f"attachment={att['id']} status={ready['status']} variants={len(ready['variants'])}"
|
|
)
|
|
finally:
|
|
subprocess.call(["docker", "rm", "-f", "lab5-worker-crash"], cwd=str(ROOT))
|
|
_compose("up", "-d", "worker")
|
|
time.sleep(3)
|
|
|
|
# --- Operator replay of a forced failed job via DLQ insert path ---
|
|
# Force a permanent fail by deleting staging after accept while worker is down,
|
|
# then restore staging is impossible → failed/source_missing; then we cannot
|
|
# usefully replay without bytes. Instead: mark a job failed via SQL and replay
|
|
# while staging still exists (worker stopped briefly).
|
|
_compose("stop", "worker")
|
|
time.sleep(1)
|
|
alice2 = register("ox_rep")
|
|
chat2 = chat_for(alice2, title="replay")
|
|
data2 = imagegen.rgb_png(32, 32)
|
|
att2 = upload(alice2["token"], chat2["id"], data2, "r.png", "image/png", 202)["json"]
|
|
# Inject a dead letter for this attachment (simulating exhausted attempts) while
|
|
# keeping staging; then operator replay → queued → ready after worker start.
|
|
def _psql(sql: str) -> str:
|
|
return subprocess.check_output(
|
|
[
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"psql",
|
|
"-U",
|
|
"messenger",
|
|
"-d",
|
|
"messenger",
|
|
"-v",
|
|
"ON_ERROR_STOP=1",
|
|
"-t",
|
|
"-A",
|
|
"-c",
|
|
sql,
|
|
],
|
|
cwd=str(ROOT),
|
|
text=True,
|
|
).strip()
|
|
|
|
_psql(
|
|
"UPDATE attachments SET status = 'failed', error_code = 'processing_failed', "
|
|
f"updated_at = now() WHERE id = '{att2['id']}';"
|
|
)
|
|
_psql(
|
|
"UPDATE attachment_jobs SET status = 'failed', updated_at = now() "
|
|
f"WHERE attachment_id = '{att2['id']}' AND status <> 'failed';"
|
|
)
|
|
dead_id = int(
|
|
_psql(
|
|
"INSERT INTO dead_letter_jobs "
|
|
"(job_id, attachment_id, pipeline_version, payload, error_code, attempts, failed_at) "
|
|
"SELECT gen_random_uuid(), a.id, 1, "
|
|
"jsonb_build_object("
|
|
"'job_id', gen_random_uuid()::text, "
|
|
"'attachment_id', a.id::text, "
|
|
"'pipeline_version', 1, "
|
|
"'attempt', 5, "
|
|
"'created_at', '1970-01-01T00:00:00Z'"
|
|
"), 'processing_failed', 5, now() "
|
|
f"FROM attachments a WHERE a.id = '{att2['id']}' "
|
|
"RETURNING id;"
|
|
).splitlines()[0]
|
|
)
|
|
meta = call("GET", f"/api/v1/attachments/{att2['id']}", 200, token=alice2["token"])["json"]
|
|
assert meta["status"] == "failed", meta
|
|
# Replay via API container module
|
|
replay_out = subprocess.check_output(
|
|
[
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
"exec",
|
|
"-T",
|
|
"api",
|
|
"python",
|
|
"-m",
|
|
"messenger.replay",
|
|
"--dead-letter-id",
|
|
str(dead_id),
|
|
"--note",
|
|
"evidence replay",
|
|
],
|
|
cwd=str(ROOT),
|
|
text=True,
|
|
)
|
|
log(f"PASS operator-replay dead_letter_id={dead_id} stdout={replay_out.strip()}")
|
|
_compose("up", "-d", "worker")
|
|
ready2 = wait_ready(alice2["token"], att2, wait_seconds=90)
|
|
log(
|
|
f"PASS failed→queued→ready after replay attachment={att2['id']} "
|
|
f"status={ready2['status']} variants={len(ready2['variants'])}"
|
|
)
|
|
|
|
# --- Staging retained while queued (janitor dry-run does not clear) ---
|
|
_compose("stop", "worker")
|
|
alice3 = register("ox_st")
|
|
chat3 = chat_for(alice3)
|
|
att3 = upload(
|
|
alice3["token"],
|
|
chat3["id"],
|
|
imagegen.rgb_png(16, 16),
|
|
"s.png",
|
|
"image/png",
|
|
202,
|
|
)["json"]
|
|
dry = subprocess.check_output(
|
|
[
|
|
"docker",
|
|
"compose",
|
|
"--env-file",
|
|
".env",
|
|
"exec",
|
|
"-T",
|
|
"api",
|
|
"python",
|
|
"-m",
|
|
"messenger.reconcile",
|
|
"--dry-run",
|
|
"--grace-seconds",
|
|
"0",
|
|
],
|
|
cwd=str(ROOT),
|
|
text=True,
|
|
)
|
|
meta3 = call("GET", f"/api/v1/attachments/{att3['id']}", 200, token=alice3["token"])["json"]
|
|
assert meta3["status"] in ("queued", "processing"), meta3
|
|
log(f"PASS janitor-dry-run while queued status={meta3['status']} report={dry.strip()[:300]}")
|
|
_compose("up", "-d", "worker")
|
|
wait_ready(alice3["token"], att3, wait_seconds=60)
|
|
log(f"PASS queued attachment survived janitor dry-run attachment={att3['id']}")
|
|
|
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
|
OUT.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
print(f"WROTE {OUT}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|