"""Database atomicity and concurrent conflict checks, using isolated synthetic data.""" import unittest from concurrent.futures import ThreadPoolExecutor from unittest.mock import patch from uuid import uuid4 from sqlalchemy import func, select from sqlalchemy.orm import Session, sessionmaker from src.database import create_db_engine from src.errors import APIError from src.models import Chat, IdempotencyRecord, Message from src.store import PostgresStore class IdempotencyTests(unittest.TestCase): def setUp(self): self.engine = create_db_engine() self.store = PostgresStore() self.store.sessions = sessionmaker(self.engine, expire_on_commit=False) self.user = self.store.create_user('idem_' + uuid4().hex[:16], 'Idempotency', 'Synthetic-password-123') self.chat = self.store.create_chat(self.user['id'], 'Atomic', [self.user['id']]) def tearDown(self): self.engine.dispose() def test_record_and_message_rollback_together(self): real_add = Session.add def fail_record(session, instance, *args, **kwargs): if isinstance(instance, IdempotencyRecord): raise RuntimeError('Simulate failure after message INSERT, before COMMIT') return real_add(session, instance, *args, **kwargs) args = (self.chat['id'], self.user['id'], 'atomic', 'same-key') with patch.object(Session, 'add', fail_record): with self.assertRaises(RuntimeError): self.store.create_message(*args) with Session(self.engine) as session: self.assertEqual(session.scalar(select(func.count()).select_from(Message).where(Message.chat_id == self.chat['id'])), 0) self.assertIsNone(session.get(IdempotencyRecord, (self.user['id'], self.chat['id'], 'same-key'))) self.assertEqual(session.get(Chat, self.chat['id']).history_version, 0) first = self.store.create_message(*args) self.assertEqual(self.store.create_message(*args), first) def test_concurrent_different_payloads_have_one_winner(self): def send(index): try: return self.store.create_message(self.chat['id'], self.user['id'], str(index), 'conflict'), 201 except APIError as exc: return None, exc.status_code with ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(send, range(8))) self.assertEqual(sorted(code for _, code in results), [201] + [409] * 7) with Session(self.engine) as session: self.assertEqual(session.scalar(select(func.count()).select_from(Message).where(Message.chat_id == self.chat['id'])), 1) self.assertEqual(session.get(Chat, self.chat['id']).history_version, 1)