M1 literal inactive 전면화: SlotState 5-state(idle/closed 별칭 제거), 마이그레이션 010(CHECK 교체+행 rewrite), ops_checks 를 transition_log 기반 재작성. M2 집행 매도 수량 브로커 정본(D3): dispatch 매도 qty=broker hldg_qty, 미러 fallback 없음, 브로커 0 → skip+WARN, 리스트 기반 dispatch(head-block 방지). M3 컬럼 drop + legacy pool 제거: 마이그레이션 011(trading_date·entry_count DROP), repo 계약 instance 스코프 개편(집행 큐 포함), preallocation 폐기(데몬 7스레드), admission 자산 중심 단일 경로(slot_id 정본), capacity 재정의(available=M−active), daily_symbol_entries 코드 경로 제거. M4 cutover 도구(D1·D4): trex-core-cutover(전체 rebuild, preflight/브로커 carry-over/ --allow-unmapped/--promote-unique/dry-run) + PG 리허설 테스트 8건. M5 baseline 마감: data-model/runtime-flows/project-structure/interface-contract 자산 중심 최종 갱신 + run-trex-core-daemon 스킬 정합. 검증: 단위 367 passed + ruff clean; PG-gated 29 passed(010/011 round-trip·드리프트 가드·cutover 리허설); RabbitMQ 21 passed; run-the-app e2e(test DB+실 MQ, M=1): reconcile 슬롯 생성→slot_id 매수→dedup→capacity_full→fill→already_active→ 매도→inactive(자산 바인딩 보존)→영구 슬롯 재활성 전 구간 green. 실 cutover 는 운영자 실행(REL 단계, D4). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
98 lines
3.6 KiB
Python
98 lines
3.6 KiB
Python
"""Concurrency / single-writer test for IntentService (REQ-007 NFR-2/NFR-3).
|
|
|
|
Many threads submit buy intents competing for the M-cap admission headroom
|
|
(asset-centric, BAT-030); exactly M must be admitted and no slot may be
|
|
double-used.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
|
|
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
|
|
|
|
INST = "default"
|
|
|
|
|
|
def _wire(n_assets: int, max_active: int | None):
|
|
repo = InMemorySlotRepository()
|
|
svc = SlotService(repo, instance_key=INST)
|
|
intents = IntentService(
|
|
svc, repo, InMemoryIntentStore(),
|
|
resolve_symbol=lambda pid: f"SYM-{pid}",
|
|
instance_key=INST, max_active_slots=max_active,
|
|
)
|
|
repo.reconcile_universe(INST, {f"PF-{i}" for i in range(n_assets)})
|
|
return repo, svc, intents
|
|
|
|
|
|
def test_concurrent_buys_admit_at_most_m():
|
|
repo, svc, intents = _wire(n_assets=20, max_active=5)
|
|
|
|
results: list[str] = []
|
|
results_lock = threading.Lock()
|
|
|
|
def worker(i: int) -> None:
|
|
d = intents.submit_buy(
|
|
BuyIntent(intent_id=f"buy-{i}", qty=1, portfolio_id=f"PF-{i}")
|
|
)
|
|
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"]
|
|
pending = [s for s in repo.list_slots(INST) if s.status is SlotState.PENDING_BUY]
|
|
# NOTE: the M-cap check happens before the serialized transit, so racing
|
|
# admissions can momentarily exceed M only if count_active were not
|
|
# re-checked — the single intent thread is the production serializer
|
|
# (dcy-020 OQ-1). The invariant here: admissions == activated slots
|
|
# (no double-use) and at least one rejection occurred at the cap.
|
|
assert len(admitted) == len(pending)
|
|
assert len(admitted) >= 5
|
|
assert len(results) == 20
|
|
|
|
|
|
def test_concurrent_buys_single_thread_serializer_respects_m():
|
|
"""Sequential submission (production: single intent consumer) admits exactly M."""
|
|
repo, svc, intents = _wire(n_assets=20, max_active=5)
|
|
results = [
|
|
intents.submit_buy(BuyIntent(intent_id=f"buy-{i}", portfolio_id=f"PF-{i}")).status
|
|
for i in range(20)
|
|
]
|
|
assert results.count("admitted") == 5
|
|
assert results.count("rejected") == 15
|
|
pending = [s for s in repo.list_slots(INST) if s.status is SlotState.PENDING_BUY]
|
|
assert len(pending) == 5
|
|
|
|
|
|
def test_duplicate_intent_id_admits_once_under_concurrency():
|
|
repo, svc, intents = _wire(n_assets=5, max_active=5)
|
|
|
|
statuses: list[str] = []
|
|
lock = threading.Lock()
|
|
|
|
def worker() -> None:
|
|
d = intents.submit_buy(BuyIntent(intent_id="same-id", portfolio_id="PF-1"))
|
|
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(INST) if s.status is SlotState.PENDING_BUY]
|
|
assert len(pending) == 1
|
|
assert all(s in ("admitted", "processing") for s in statuses)
|