-- An idempotency key belongs to the authenticated user and target chat, not -- to the entire service. This is the POST /chats/{chat_id}/messages path; -- together (actor_id, chat_id, key) form the contract's user+method+path+key -- scope. ALTER TABLE idempotency_keys ADD COLUMN actor_id uuid REFERENCES users (id); -- All completed records created by the previous schema have message_id. -- Derive the actor from that immutable message before making the new scope -- mandatory. Any incomplete legacy row cannot be safely replayed, so remove -- it instead of assigning it to an arbitrary user. UPDATE idempotency_keys AS ik SET actor_id = m.sender_id FROM messages AS m WHERE ik.message_id = m.id AND ik.actor_id IS NULL; DELETE FROM idempotency_keys WHERE actor_id IS NULL; ALTER TABLE idempotency_keys ALTER COLUMN actor_id SET NOT NULL, DROP CONSTRAINT idempotency_keys_pkey, ADD PRIMARY KEY (actor_id, chat_id, key); CREATE INDEX idempotency_created_at_idx ON idempotency_keys (created_at);