"""Concurrency / single-writer test for IntentService (REQ-007 NFR-2/NFR-3). Many threads submit buy intents competing for a limited number of idle slots; exactly that many must be admitted and no slot may be double-used. """ from __future__ import annotations import threading from datetime import date from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore from trex_core.application.intents import BuyIntent, IntentService from trex_core.domain.slot import SlotService, SlotState from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository DAY = date(2026, 6, 3) def test_concurrent_buys_admit_exactly_idle_count(): repo = InMemorySlotRepository() svc = SlotService(repo) intents = IntentService(svc, repo, InMemoryIntentStore()) svc.preallocate_daily_slots(DAY, 5) # only 5 idle slots results: list[str] = [] results_lock = threading.Lock() def worker(i: int) -> None: d = intents.submit_buy(BuyIntent(intent_id=f"buy-{i}", trading_date=DAY, symbol="005930", qty=1)) with results_lock: results.append(d.status) threads = [threading.Thread(target=worker, args=(i,)) for i in range(20)] for t in threads: t.start() for t in threads: t.join() admitted = [s for s in results if s == "admitted"] rejected = [s for s in results if s == "rejected"] assert len(admitted) == 5 # exactly the idle slots assert len(rejected) == 15 # every non-idle slot is pending_buy exactly once (no double-use) pending = [s for s in repo.list_slots(DAY) if s.status is SlotState.PENDING_BUY] idle = [s for s in repo.list_slots(DAY) if s.status is SlotState.IDLE] assert len(pending) == 5 and len(idle) == 0 def test_duplicate_intent_id_admits_once_under_concurrency(): repo = InMemorySlotRepository() svc = SlotService(repo) intents = IntentService(svc, repo, InMemoryIntentStore()) svc.preallocate_daily_slots(DAY, 5) statuses: list[str] = [] lock = threading.Lock() def worker() -> None: d = intents.submit_buy(BuyIntent(intent_id="same-id", trading_date=DAY, symbol="005930")) with lock: statuses.append(d.status) threads = [threading.Thread(target=worker) for _ in range(10)] for t in threads: t.start() for t in threads: t.join() # same intent_id submitted 10x concurrently -> exactly ONE slot transitioned # (the core idempotency guarantee). Racing duplicates observe the winner's # decision, which may still be 'processing' before finalize; never 'rejected'. pending = [s for s in repo.list_slots(DAY) if s.status is SlotState.PENDING_BUY] assert len(pending) == 1 assert all(s in ("admitted", "processing") for s in statuses)