import json import subprocess import time from pathlib import Path import pika from client import Client, check ROOT = Path(__file__).resolve().parents[1] BASE_URL = "http://localhost:8080" def sql(query): result = subprocess.run( [ "docker", "compose", "exec", "-T", "postgres", "psql", "-U", "lab2", "-d", "messenger", "-t", "-A", "-c", query, ], cwd=ROOT, capture_output=True, text=True, check=True, ) return result.stdout.strip() def job_state(attachment_id): result = sql(f""" SELECT row_to_json(t) FROM ( SELECT j.id AS job_id, j.attachment_id, j.status AS job_status, a.status AS attachment_status, j.attempt, j.generation, j.execution_id, j.finished_at, a.s3_key, a.variants FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE a.id = '{attachment_id}' ) t; """) check(bool(result), "job not found") return json.loads(result) def publish_duplicate(payload): result = subprocess.run( [ "docker", "compose", "exec", "-T", "worker", "python", "-c", """ import json import sys import pika from src.queue import connect, QUEUE payload = json.loads(sys.stdin.read()) connection, channel = connect() channel.confirm_delivery() channel.basic_publish( exchange="", routing_key=QUEUE, body=json.dumps(payload).encode(), properties=pika.BasicProperties( delivery_mode=2, content_type="application/json", message_id=payload["job_id"], ), mandatory=True, ) connection.close() """, ], cwd=ROOT, input=json.dumps(payload), capture_output=True, text=True, check=True, ) return result def test_duplicate(): client = Client(BASE_URL) alice, bob, _, chat = client.bootstrap() attachment, original = client.attachment(alice, chat) attachment_id = attachment["id"] client.wait_ready(bob, attachment, wait_seconds=120) before = job_state(attachment_id) check(before["job_status"] == "ready", "job is not ready") check(before["attachment_status"] == "ready", "attachment is not ready") payload = { "schema_version": 1, "job_id": before["job_id"], "type": "attachment.process.v1", "attachment_id": attachment_id, "pipeline_version": 1, "attempt": before["attempt"], "generation": before["generation"], "created_at": "2026-01-01T00:00:00Z", } publish_duplicate(payload) publish_duplicate(payload) deadline = time.monotonic() + 30 while time.monotonic() < deadline: queue = subprocess.run( [ "docker", "compose", "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", "name", "messages_ready", "messages_unacknowledged", "--quiet", ], cwd=ROOT, capture_output=True, text=True, check=True, ) lines = queue.stdout.splitlines() matching = [ line.split() for line in lines if line.startswith("attachment.process.v1") ] if matching and matching[0][1:] == ["0", "0"]: break time.sleep(1) else: raise AssertionError("duplicate messages were not consumed") after = job_state(attachment_id) check(before == after, "duplicate delivery changed committed result") content = client.call( "GET", f"/api/v1/attachments/{attachment_id}/content", actor=bob, ) check(content["bytes"] == original, "original content changed") print("PASS: duplicate delivery, state unchanged, original intact") def test_reorder(): client = Client(BASE_URL) alice, bob, _, chat = client.bootstrap() attachment, original = client.attachment(alice, chat) attachment_id = attachment["id"] client.wait_ready(bob, attachment, wait_seconds=120) before = job_state(attachment_id) check(before["job_status"] == "ready", "job is not ready") payload = { "schema_version": 1, "job_id": before["job_id"], "type": "attachment.process.v1", "attachment_id": attachment_id, "pipeline_version": 1, "attempt": before["attempt"], "generation": before["generation"], "created_at": "2026-01-01T00:00:00Z", } for attempt in ( before["attempt"] + 1, before["attempt"] - 1, before["attempt"], ): message = dict(payload) message["attempt"] = attempt publish_duplicate(message) deadline = time.monotonic() + 30 while time.monotonic() < deadline: queue = subprocess.run( [ "docker", "compose", "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", "name", "messages_ready", "messages_unacknowledged", "--quiet", ], cwd=ROOT, capture_output=True, text=True, check=True, ) matching = [ line.split() for line in queue.stdout.splitlines() if line.startswith("attachment.process.v1") ] if matching and matching[0][1:] == ["0", "0"]: break time.sleep(1) else: raise AssertionError("reordered messages were not consumed") after = job_state(attachment_id) check(before == after, "reordered delivery changed committed result") content = client.call( "GET", f"/api/v1/attachments/{attachment_id}/content", actor=bob, ) check(content["bytes"] == original, "original content changed") print("PASS: reordered attempts, state unchanged, original intact") def test_stale_generation(): client = Client(BASE_URL) alice, bob, _, chat = client.bootstrap() attachment, original = client.attachment(alice, chat) attachment_id = attachment["id"] client.wait_ready(bob, attachment, wait_seconds=120) before = job_state(attachment_id) check(before["job_status"] == "ready", "job is not ready") check(before["generation"] == 1, "unexpected initial generation") payload = { "schema_version": 1, "job_id": before["job_id"], "type": "attachment.process.v1", "attachment_id": attachment_id, "pipeline_version": 1, "attempt": before["attempt"], "generation": before["generation"], "created_at": "2026-01-01T00:00:00Z", } for generation in (0, 2, 1): message = dict(payload) message["generation"] = generation publish_duplicate(message) deadline = time.monotonic() + 30 while time.monotonic() < deadline: queue = subprocess.run( [ "docker", "compose", "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", "name", "messages_ready", "messages_unacknowledged", "--quiet", ], cwd=ROOT, capture_output=True, text=True, check=True, ) matching = [ line.split() for line in queue.stdout.splitlines() if line.startswith("attachment.process.v1") ] if matching and matching[0][1:] == ["0", "0"]: break time.sleep(1) else: raise AssertionError("generation messages were not consumed") after = job_state(attachment_id) check(before == after, "generation mismatch changed committed result") content = client.call( "GET", f"/api/v1/attachments/{attachment_id}/content", actor=bob, ) check(content["bytes"] == original, "original content changed") print("PASS: stale and future generations rejected, result unchanged") def test_replay_generation(): client = Client(BASE_URL) alice, bob, _, chat = client.bootstrap() attachment, original = client.attachment(alice, chat) attachment_id = attachment["id"] client.wait_ready(bob, attachment, wait_seconds=120) before = job_state(attachment_id) check(before["job_status"] == "ready", "initial job is not ready") check(before["generation"] == 1, "unexpected initial generation") job_id = before["job_id"] sql(f""" BEGIN; UPDATE attachment_jobs SET status = 'failed', last_error_code = 'test_replay', finished_at = now(), failed_published_at = now() WHERE id = '{job_id}' AND status = 'ready'; UPDATE attachments SET status = 'failed', error_code = 'test_replay', updated_at = now() WHERE id = '{attachment_id}' AND status = 'ready'; COMMIT; """) result = subprocess.run( [ "docker", "compose", "exec", "-T", "worker", "python", "-m", "scripts.replay_job", job_id, ], cwd=ROOT, capture_output=True, text=True, check=True, ) check("REPLAY ACCEPTED" in result.stdout, "replay was rejected") replayed = job_state(attachment_id) check(replayed["generation"] == 2, "generation did not increase") stale_payload = { "schema_version": 1, "job_id": job_id, "type": "attachment.process.v1", "attachment_id": attachment_id, "pipeline_version": 1, "attempt": 1, "generation": 1, "created_at": "2026-01-01T00:00:00Z", } publish_duplicate(stale_payload) deadline = time.monotonic() + 120 while time.monotonic() < deadline: current = job_state(attachment_id) if current["job_status"] == "ready": break check(current["job_status"] != "failed", "replay failed") time.sleep(0.5) else: raise AssertionError("replayed job did not become ready") check(current["generation"] == 2, "generation did not increase") check(current["attachment_status"] == "ready", "attachment not ready") check(current["execution_id"] != before["execution_id"], "execution ID unchanged") payload = { "schema_version": 1, "job_id": job_id, "type": "attachment.process.v1", "attachment_id": attachment_id, "pipeline_version": 1, "attempt": 1, "generation": 1, "created_at": "2026-01-01T00:00:00Z", } publish_duplicate(payload) deadline = time.monotonic() + 30 while time.monotonic() < deadline: queue = subprocess.run( [ "docker", "compose", "exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues", "name", "messages_ready", "messages_unacknowledged", "--quiet", ], cwd=ROOT, capture_output=True, text=True, check=True, ) matching = [ line.split() for line in queue.stdout.splitlines() if line.startswith("attachment.process.v1") ] if matching and matching[0][1:] == ["0", "0"]: break time.sleep(1) else: raise AssertionError("stale message was not consumed") after = job_state(attachment_id) check(current == after, "stale generation overwrote newer result") content = client.call( "GET", f"/api/v1/attachments/{attachment_id}/content", actor=bob, ) check(content["bytes"] == original, "original changed after replay") print("PASS: replay generation 1 -> 2, stale message rejected") if __name__ == "__main__": test_duplicate() test_reorder() test_stale_generation() test_replay_generation()