"""Prove that one idempotency key creates one message across both replicas.""" import concurrent.futures import json import sys import threading import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, arguments, check, run # noqa: E402 def main(): args = arguments("Concurrent cross-replica idempotency check") base = Client(args.base_url, args.ca_file) alice, _, _, chat = base.bootstrap() path = "/api/v1/chats/" + chat["id"] + "/messages" key = "parallel-" + uuid.uuid4().hex body = {"text": "one logical concurrent message"} workers = 12 barrier = threading.Barrier(workers) def send(_): client = Client(args.base_url, args.ca_file) barrier.wait() result = client.call("POST", path, 201, actor=alice, body=body, headers={"Idempotency-Key": key}, schema="Message") return result["json"], result["headers"]["X-Instance-Id"] with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: responses = list(pool.map(send, range(workers))) messages = [item[0] for item in responses] instances = sorted(set(item[1] for item in responses)) ids = sorted(set(item["id"] for item in messages)) check(len(ids) == 1, "one key created more than one message") check(all(item == messages[0] for item in messages), "idempotent responses differ") check(len(instances) >= 2, "requests did not cross two API replicas") base.call("POST", path, 409, actor=alice, body={"text": "different body"}, headers={"Idempotency-Key": key}) page = base.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"] check(sum(item["id"] == ids[0] for item in page["items"]) == 1, "history contains a duplicate message") result = {"parallel_requests": workers, "instances": instances, "unique_message_ids": len(ids), "conflicting_reuse_status": 409} (ROOT / "evidence").mkdir(exist_ok=True) (ROOT / "evidence" / "idempotency.json").write_text( json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print("PASS:", json.dumps(result, ensure_ascii=False)) if __name__ == "__main__": run(main)