"""Race protection of the in-memory store with real OS threads. The HTTP server itself runs on one event loop; these tests hit the Store from 10 threads at once to prove the lock and the "timestamp under the lock" rule: no lost/duplicated messages AND the history order equals (created_at, id). """ from __future__ import annotations import sys import threading import pytest from messenger.errors import Conflict from messenger.store import Store CLIENTS = 10 PER_CLIENT = 10 @pytest.fixture(autouse=True) def frequent_thread_switches(): """Force the interpreter to switch threads every 0.1 ms instead of every 5 ms. Without this the GIL rarely interrupts a short critical section and a race such as "timestamp taken before the lock" would pass unnoticed. With it the broken variant fails reliably. """ previous = sys.getswitchinterval() sys.setswitchinterval(1e-4) yield sys.setswitchinterval(previous) def run_concurrently(workers: int, target) -> list: barrier = threading.Barrier(workers) results: list = [None] * workers errors: list[BaseException] = [] def body(index: int) -> None: barrier.wait() # release all threads at the same moment try: results[index] = target(index) except BaseException as exc: # noqa: BLE001 - collected and re-raised in the test errors.append(exc) threads = [threading.Thread(target=body, args=(i,)) for i in range(workers)] for t in threads: t.start() for t in threads: t.join() if errors: raise errors[0] return results def walk(store: Store, user_id: str, chat_id: str, limit: int, max_items: int = 1000) -> list: """Cursor traversal like a client does it. If the stored order were broken, a cursor could point back to an already returned page and the walk would never end, so the number of returned items is bounded.""" items, after = [], None while True: page, has_more = store.list_messages(user_id, chat_id, after, limit) items.extend(page) assert len(items) <= max_items, "cursor traversal repeats messages (order is broken)" if not has_more: return items after = page[-1].key @pytest.mark.parametrize("round_", range(20)) def test_100_messages_from_10_clients_are_unique_and_ordered(round_): store = Store() users = [store.create_user(f"client_{i}", f"Клиент {i}") for i in range(CLIENTS)] chat = store.create_chat(users[0].id, "Нагрузка", [u.id for u in users]) def client(index: int): return [store.add_message(users[index].id, chat.id, f"c{index}-m{j}") for j in range(PER_CLIENT)] confirmed = [m for batch in run_concurrently(CLIENTS, client) for m in batch] history = walk(store, users[3].id, chat.id, limit=7) # multi-page cursor traversal # Compact messages on purpose: pytest's diff of 100 dataclasses is slow and unreadable. assert len(confirmed) == 100, f"confirmed {len(confirmed)} writes" ids = [m.id for m in history] assert len(ids) == 100, f"history has {len(ids)} messages" assert set(ids) == {m.id for m in confirmed}, "a confirmed message is missing" assert len(set(ids)) == 100, "duplicated message in history" keys = [m.key for m in history] inversions = sum(1 for a, b in zip(keys, keys[1:]) if not a < b) assert inversions == 0, f"{inversions} neighbours violate strict (created_at, id) order" for i in range(CLIENTS): own = [m.text for m in history if m.sender_id == users[i].id] assert own == [f"c{i}-m{j}" for j in range(PER_CLIENT)], f"client {i} order changed" def test_timestamps_increase_even_if_wall_clock_goes_back(): ticks = iter([5_000_000_000, 4_000_000_000, 4_000_000_000, 1_000_000_000] + [0] * 10) store = Store(clock_ns=lambda: next(ticks)) user = store.create_user("clock_user", "Часы") chat = store.create_chat(user.id, "Часы", [user.id]) messages = [store.add_message(user.id, chat.id, str(i)) for i in range(5)] stamps = [user.ts, chat.ts, *(m.ts for m in messages)] assert stamps == sorted(stamps) and len(set(stamps)) == len(stamps) assert [m.created_at for m in messages] == sorted(m.created_at for m in messages) def test_concurrent_registration_of_same_username_creates_one_user(): store = Store() def register(_index: int): try: return store.create_user("same_name", "Гонка") except Conflict: return None created = [u for u in run_concurrently(20, register) if u is not None] assert len(created) == 1 assert store.counts()["users"] == 1 def test_concurrent_chat_creation_keeps_indexes_consistent(): store = Store() users = [store.create_user(f"member_{i}", "Участник") for i in range(CLIENTS)] ids = [u.id for u in users] chats = run_concurrently(CLIENTS, lambda i: store.create_chat(ids[i], f"Чат {i}", ids)) for user in users: listed, has_more = store.list_chats(user.id, None, 100) assert not has_more assert {c.id for c in listed} == {c.id for c in chats} assert [c.key for c in listed] == sorted(c.key for c in listed)