#!/usr/bin/env python3 """Prove that a failure after the chat insert rolls back the whole chat. Run inside the API container (psycopg is installed there): docker compose exec -T api python student-tests/rollback_chat.py A temporary trigger aborts the second chat_members insert. The API must return a bounded 500 and leave no chat row, because chat + membership share one transaction. """ from __future__ import annotations import argparse import os import uuid import psycopg from common import HttpClient, assert_status, error_code def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL")) args = parser.parse_args() if not args.database_url: raise SystemExit("DATABASE_URL is required") client = HttpClient(args.base_url) actor, actor_registration = client.register() victim, _victim_registration = client.register() session = client.login(actor_registration) token = session["token"] title = "rollback-" + uuid.uuid4().hex function_name = "test_fail_member_" + uuid.uuid4().hex[:8] victim_id = str(uuid.UUID(victim["id"])) with psycopg.connect(args.database_url, autocommit=True) as conn: conn.execute( f""" CREATE FUNCTION {function_name}() RETURNS trigger AS $$ BEGIN IF NEW.user_id = '{victim_id}'::uuid THEN RAISE EXCEPTION 'injected membership failure'; END IF; RETURN NEW; END $$ LANGUAGE plpgsql """ ) conn.execute( f"CREATE TRIGGER {function_name} BEFORE INSERT ON chat_members " f"FOR EACH ROW EXECUTE FUNCTION {function_name}()" ) try: status, _, payload, _ = client.call( "POST", "/api/v1/chats", {"title": title, "member_ids": [actor["id"], victim["id"]]}, token=token, ) assert_status(status, 500, "injected membership failure") if error_code(payload) != "internal_error": raise AssertionError("unexpected error code for injected failure") rows = conn.execute("SELECT count(*) FROM chats WHERE title = %s", (title,)).fetchone() if rows[0] != 0: raise AssertionError("chat survived a failed membership transaction") finally: conn.execute(f"DROP TRIGGER IF EXISTS {function_name} ON chat_members") conn.execute(f"DROP FUNCTION IF EXISTS {function_name}()") status, _, chat, _ = client.call( "POST", "/api/v1/chats", {"title": title + "-ok", "member_ids": [actor["id"], victim["id"]]}, token=token, ) assert_status(status, 201, "chat after trigger cleanup") assert set(chat["member_ids"]) == {actor["id"], victim["id"]} print("PASS: failed membership insert rolled back the chat; subsequent create is atomic") if __name__ == "__main__": main()