-- Shared idempotency ledger for POST /api/v1/chats/{id}/messages. -- The key scope is (user, method, path, key): the same key from another user or -- another chat is independent, as the contract requires. -- claim + response are committed in one transaction, so a committed row always -- carries status_code and response_body (there is no "poisoned" intermediate state). CREATE TABLE IF NOT EXISTS idempotency_keys ( user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, method text NOT NULL, path text NOT NULL, key text NOT NULL, request_fingerprint text NOT NULL, status_code integer, response_body jsonb, message_id uuid, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (user_id, method, path, key) ); CREATE INDEX IF NOT EXISTS idempotency_keys_created_at_idx ON idempotency_keys (created_at);